@aikaara/chat-sdk 1.5.8 → 1.5.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AikaaraLinkButton-BkEca4FR.cjs → AikaaraLinkButton-RQCl2v5d.cjs} +1 -1
- package/dist/{AikaaraLinkButton-BkNh8yg4.mjs → AikaaraLinkButton-XSw0hJzC.mjs} +1 -1
- package/dist/{MountTenant-D8G4MBFf.cjs → MountTenant-CSFT9afH.cjs} +86 -86
- package/dist/{MountTenant-B--ByCKH.mjs → MountTenant-CjM3SXpf.mjs} +5257 -4840
- package/dist/cdn/aikaara-chat.iife.js +77 -77
- 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,18 +1,18 @@
|
|
|
1
|
-
"use strict";class ta{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 fn{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 ta(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 po{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 Pc=1e3,Mc=10,Rc=400,Lc=600,Ro="#6366f1",Nc=12,jc="system-ui, -apple-system, sans-serif",Lo="Type a message...",Uc="bottom-right",Bc="light",Dc={x:20,y:20},en="aikaara_conversation_id";class ra extends po{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 fn(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??Mc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Pc)*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 fn(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 na{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 ia{_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=No(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=No(t,r);if(o){const n=Hr(o),i=Hr(r);!n&&i&&Object.assign(o,r,{id:o.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function No(s,e,t=15e3){const r=e.attachments&&e.attachments[0],o=(e.metadata??{}).attributes;if(!(!!r||!!(o&&o.fileMessage)))return null;const i=Hr(e),a=jo(e),l=Uo(e);if(!i&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=s.length-1;u>=0;u--){const h=s[u],p=h.attachments&&h.attachments[0],b=(h.metadata??{}).attributes;if(!(!!p||!!(b&&b.fileMessage)))continue;const g=(h.content||"").trim().toLowerCase();if(g==="file_uploaded"||g==="file_upload"||Math.abs(c-new Date(h.createdAt).getTime())>t)continue;const y=Hr(h);if(i&&y&&i===y)return h;const w=jo(h);if(a&&w&&a===w)return h;const m=Uo(h);if(l&&m&&l===m)return h}return null}function jo(s){const e=s.attachments&&s.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=oa(s);if(t)return t}function Uo(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 Hr(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=oa(s);if(r){const o=/[?&]cloudFileId=([^&]+)/.exec(r);if(o)return decodeURIComponent(o[1])}}function oa(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 sa{_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(en)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(en)}catch{return null}}saveToStorage(e){try{localStorage.setItem(en,e)}catch{}}}var mo=Object.defineProperty,$c=Object.getOwnPropertyDescriptor,Fc=Object.getOwnPropertyNames,qc=Object.prototype.hasOwnProperty,Je=(s,e)=>()=>(s&&(e=s(s=0)),e),pe=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Gt=(s,e)=>{for(var t in e)mo(s,t,{get:e[t],enumerable:!0})},Hc=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fc(e))!qc.call(s,o)&&o!==t&&mo(s,o,{get:()=>e[o],enumerable:!(r=$c(e,o))||r.enumerable});return s},Re=s=>Hc(mo({},"__esModule",{value:!0}),s),le=Je(()=>{}),Ne={};Gt(Ne,{_debugEnd:()=>Kn,_debugProcess:()=>Vn,_events:()=>li,_eventsCount:()=>ci,_exiting:()=>Mn,_fatalExceptions:()=>Hn,_getActiveHandles:()=>fa,_getActiveRequests:()=>da,_kill:()=>Nn,_linkedBinding:()=>ua,_maxListeners:()=>ai,_preload_modules:()=>oi,_rawDebug:()=>Cn,_startProfilerIdleNotifier:()=>Gn,_stopProfilerIdleNotifier:()=>Yn,_tickCallback:()=>zn,abort:()=>Zn,addListener:()=>ui,allowedNodeEnvironmentFlags:()=>Fn,arch:()=>mn,argv:()=>yn,argv0:()=>ii,assert:()=>pa,binding:()=>xn,browser:()=>Tn,chdir:()=>An,config:()=>Rn,cpuUsage:()=>nr,cwd:()=>En,debugPort:()=>ni,default:()=>bo,dlopen:()=>ha,domain:()=>Pn,emit:()=>mi,emitWarning:()=>kn,env:()=>bn,execArgv:()=>vn,execPath:()=>ri,exit:()=>Dn,features:()=>qn,hasUncaughtExceptionCaptureCallback:()=>ma,hrtime:()=>yr,kill:()=>Bn,listeners:()=>ba,memoryUsage:()=>Un,moduleLoadList:()=>On,nextTick:()=>la,off:()=>di,on:()=>ct,once:()=>hi,openStdin:()=>$n,pid:()=>ei,platform:()=>gn,ppid:()=>ti,prependListener:()=>gi,prependOnceListener:()=>bi,reallyExit:()=>Ln,release:()=>In,removeAllListeners:()=>pi,removeListener:()=>fi,resourceUsage:()=>jn,setSourceMapsEnabled:()=>si,setUncaughtExceptionCaptureCallback:()=>Wn,stderr:()=>Qn,stdin:()=>Xn,stdout:()=>Jn,title:()=>pn,umask:()=>Sn,uptime:()=>ga,version:()=>wn,versions:()=>_n});function go(s){throw new Error("Node.js process "+s+" is not supported by JSPM core outside of Node.js")}function Wc(){!Rt||!Pt||(Rt=!1,Pt.length?st=Pt.concat(st):ar=-1,st.length&&aa())}function aa(){if(!Rt){var s=setTimeout(Wc,0);Rt=!0;for(var e=st.length;e;){for(Pt=st,st=[];++ar<e;)Pt&&Pt[ar].run();ar=-1,e=st.length}Pt=null,Rt=!1,clearTimeout(s)}}function la(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];st.push(new ca(s,e)),st.length===1&&!Rt&&setTimeout(aa,0)}function ca(s,e){this.fun=s,this.array=e}function He(){}function ua(s){go("_linkedBinding")}function ha(s){go("dlopen")}function da(){return[]}function fa(){return[]}function pa(s,e){if(!s)throw new Error(e||"assertion error")}function ma(){return!1}function ga(){return ht.now()/1e3}function yr(s){var e=Math.floor((Date.now()-ht.now())*.001),t=ht.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+=vr)),[r,o]}function ct(){return bo}function ba(s){return[]}var st,Rt,Pt,ar,pn,mn,gn,bn,yn,vn,wn,_n,kn,xn,Sn,En,An,In,Tn,Cn,On,Pn,Mn,Rn,Ln,Nn,nr,jn,Un,Bn,Dn,$n,Fn,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ni,ii,oi,si,ht,tn,vr,ai,li,ci,ui,hi,di,fi,pi,mi,gi,bi,bo,zc=Je(()=>{le(),ue(),ce(),st=[],Rt=!1,ar=-1,ca.prototype.run=function(){this.fun.apply(null,this.array)},pn="browser",mn="x64",gn="browser",bn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},yn=["/usr/bin/node"],vn=[],wn="v16.8.0",_n={},kn=function(s,e){console.warn((e?e+": ":"")+s)},xn=function(s){go("binding")},Sn=function(s){return 0},En=function(){return"/"},An=function(s){},In={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Tn=!0,Cn=He,On=[],Pn={},Mn=!1,Rn={},Ln=He,Nn=He,nr=function(){return{}},jn=nr,Un=nr,Bn=He,Dn=He,$n=He,Fn={},qn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Hn=He,Wn=He,zn=He,Vn=He,Kn=He,Gn=He,Yn=He,Jn=void 0,Qn=void 0,Xn=void 0,Zn=He,ei=2,ti=1,ri="/bin/usr/node",ni=9229,ii="node",oi=[],si=He,ht={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ht.now===void 0&&(tn=Date.now(),ht.timing&&ht.timing.navigationStart&&(tn=ht.timing.navigationStart),ht.now=()=>Date.now()-tn),vr=1e9,yr.bigint=function(s){var e=yr(s);return typeof BigInt>"u"?e[0]*vr+e[1]:BigInt(e[0]*vr)+BigInt(e[1])},ai=10,li={},ci=0,ui=ct,hi=ct,di=ct,fi=ct,pi=ct,mi=He,gi=ct,bi=ct,bo={version:wn,versions:_n,arch:mn,platform:gn,browser:Tn,release:In,_rawDebug:Cn,moduleLoadList:On,binding:xn,_linkedBinding:ua,_events:li,_eventsCount:ci,_maxListeners:ai,on:ct,addListener:ui,once:hi,off:di,removeListener:fi,removeAllListeners:pi,emit:mi,prependListener:gi,prependOnceListener:bi,listeners:ba,domain:Pn,_exiting:Mn,config:Rn,dlopen:ha,uptime:ga,_getActiveRequests:da,_getActiveHandles:fa,reallyExit:Ln,_kill:Nn,cpuUsage:nr,resourceUsage:jn,memoryUsage:Un,kill:Bn,exit:Dn,openStdin:$n,allowedNodeEnvironmentFlags:Fn,assert:pa,features:qn,_fatalExceptions:Hn,setUncaughtExceptionCaptureCallback:Wn,hasUncaughtExceptionCaptureCallback:ma,emitWarning:kn,nextTick:la,_tickCallback:zn,_debugProcess:Vn,_debugEnd:Kn,_startProfilerIdleNotifier:Gn,_stopProfilerIdleNotifier:Yn,stdout:Jn,stdin:Xn,stderr:Qn,abort:Zn,umask:Sn,chdir:An,cwd:En,env:bn,title:pn,argv:yn,execArgv:vn,pid:ei,ppid:ti,execPath:ri,debugPort:ni,hrtime:yr,argv0:ii,_preload_modules:oi,setSourceMapsEnabled:si}}),ce=Je(()=>{zc()});function Vc(){if(yi)return qt;yi=!0,qt.byteLength=a,qt.toByteArray=c,qt.fromByteArray=p;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(b){var d=b.length;if(d%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var g=b.indexOf("=");g===-1&&(g=d);var y=g===d?0:4-g%4;return[g,y]}function a(b){var d=i(b),g=d[0],y=d[1];return(g+y)*3/4-y}function l(b,d,g){return(d+g)*3/4-g}function c(b){var d,g=i(b),y=g[0],w=g[1],m=new t(l(b,y,w)),_=0,x=w>0?y-4:y,v;for(v=0;v<x;v+=4)d=e[b.charCodeAt(v)]<<18|e[b.charCodeAt(v+1)]<<12|e[b.charCodeAt(v+2)]<<6|e[b.charCodeAt(v+3)],m[_++]=d>>16&255,m[_++]=d>>8&255,m[_++]=d&255;return w===2&&(d=e[b.charCodeAt(v)]<<2|e[b.charCodeAt(v+1)]>>4,m[_++]=d&255),w===1&&(d=e[b.charCodeAt(v)]<<10|e[b.charCodeAt(v+1)]<<4|e[b.charCodeAt(v+2)]>>2,m[_++]=d>>8&255,m[_++]=d&255),m}function u(b){return s[b>>18&63]+s[b>>12&63]+s[b>>6&63]+s[b&63]}function h(b,d,g){for(var y,w=[],m=d;m<g;m+=3)y=(b[m]<<16&16711680)+(b[m+1]<<8&65280)+(b[m+2]&255),w.push(u(y));return w.join("")}function p(b){for(var d,g=b.length,y=g%3,w=[],m=16383,_=0,x=g-y;_<x;_+=m)w.push(h(b,_,_+m>x?x:_+m));return y===1?(d=b[g-1],w.push(s[d>>2]+s[d<<4&63]+"==")):y===2&&(d=(b[g-2]<<8)+b[g-1],w.push(s[d>>10]+s[d>>4&63]+s[d<<2&63]+"=")),w.join("")}return qt}function Kc(){return vi?ir:(vi=!0,ir.read=function(s,e,t,r,o){var n,i,a=o*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,h=t?o-1:0,p=t?-1:1,b=s[e+h];for(h+=p,n=b&(1<<-u)-1,b>>=-u,u+=a;u>0;n=n*256+s[e+h],h+=p,u-=8);for(i=n&(1<<-u)-1,n>>=-u,u+=r;u>0;i=i*256+s[e+h],h+=p,u-=8);if(n===0)n=1-c;else{if(n===l)return i?NaN:(b?-1:1)*(1/0);i=i+Math.pow(2,r),n=n-c}return(b?-1:1)*i*Math.pow(2,n-r)},ir.write=function(s,e,t,r,o,n){var i,a,l,c=n*8-o-1,u=(1<<c)-1,h=u>>1,p=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,b=r?0:n-1,d=r?1:-1,g=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+h>=1?e+=p/l:e+=p*Math.pow(2,1-h),e*l>=2&&(i++,l/=2),i+h>=u?(a=0,i=u):i+h>=1?(a=(e*l-1)*Math.pow(2,o),i=i+h):(a=e*Math.pow(2,h-1)*Math.pow(2,o),i=0));o>=8;s[t+b]=a&255,b+=d,a/=256,o-=8);for(i=i<<o|a,c+=o;c>0;s[t+b]=i&255,b+=d,i/=256,c-=8);s[t+b-d]|=g*128},ir)}function Gc(){if(wi)return _t;wi=!0;let s=Vc(),e=Kc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;_t.Buffer=i,_t.SlowBuffer=w,_t.INSPECT_MAX_BYTES=50;let r=2147483647;_t.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 f=new Uint8Array(1),k={foo:function(){return 42}};return Object.setPrototypeOf(k,Uint8Array.prototype),Object.setPrototypeOf(f,k),f.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(f){if(f>r)throw new RangeError('The value "'+f+'" is invalid for option "size"');let k=new Uint8Array(f);return Object.setPrototypeOf(k,i.prototype),k}function i(f,k,A){if(typeof f=="number"){if(typeof k=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(f)}return a(f,k,A)}i.poolSize=8192;function a(f,k,A){if(typeof f=="string")return h(f,k);if(ArrayBuffer.isView(f))return b(f);if(f==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof f);if(H(f,ArrayBuffer)||f&&H(f.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(f,SharedArrayBuffer)||f&&H(f.buffer,SharedArrayBuffer)))return d(f,k,A);if(typeof f=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=f.valueOf&&f.valueOf();if(B!=null&&B!==f)return i.from(B,k,A);let X=g(f);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof f[Symbol.toPrimitive]=="function")return i.from(f[Symbol.toPrimitive]("string"),k,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof f)}i.from=function(f,k,A){return a(f,k,A)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function l(f){if(typeof f!="number")throw new TypeError('"size" argument must be of type number');if(f<0)throw new RangeError('The value "'+f+'" is invalid for option "size"')}function c(f,k,A){return l(f),f<=0?n(f):k!==void 0?typeof A=="string"?n(f).fill(k,A):n(f).fill(k):n(f)}i.alloc=function(f,k,A){return c(f,k,A)};function u(f){return l(f),n(f<0?0:y(f)|0)}i.allocUnsafe=function(f){return u(f)},i.allocUnsafeSlow=function(f){return u(f)};function h(f,k){if((typeof k!="string"||k==="")&&(k="utf8"),!i.isEncoding(k))throw new TypeError("Unknown encoding: "+k);let A=m(f,k)|0,B=n(A),X=B.write(f,k);return X!==A&&(B=B.slice(0,X)),B}function p(f){let k=f.length<0?0:y(f.length)|0,A=n(k);for(let B=0;B<k;B+=1)A[B]=f[B]&255;return A}function b(f){if(H(f,Uint8Array)){let k=new Uint8Array(f);return d(k.buffer,k.byteOffset,k.byteLength)}return p(f)}function d(f,k,A){if(k<0||f.byteLength<k)throw new RangeError('"offset" is outside of buffer bounds');if(f.byteLength<k+(A||0))throw new RangeError('"length" is outside of buffer bounds');let B;return k===void 0&&A===void 0?B=new Uint8Array(f):A===void 0?B=new Uint8Array(f,k):B=new Uint8Array(f,k,A),Object.setPrototypeOf(B,i.prototype),B}function g(f){if(i.isBuffer(f)){let k=y(f.length)|0,A=n(k);return A.length===0||f.copy(A,0,0,k),A}if(f.length!==void 0)return typeof f.length!="number"||me(f.length)?n(0):p(f);if(f.type==="Buffer"&&Array.isArray(f.data))return p(f.data)}function y(f){if(f>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return f|0}function w(f){return+f!=f&&(f=0),i.alloc(+f)}i.isBuffer=function(f){return f!=null&&f._isBuffer===!0&&f!==i.prototype},i.compare=function(f,k){if(H(f,Uint8Array)&&(f=i.from(f,f.offset,f.byteLength)),H(k,Uint8Array)&&(k=i.from(k,k.offset,k.byteLength)),!i.isBuffer(f)||!i.isBuffer(k))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(f===k)return 0;let A=f.length,B=k.length;for(let X=0,he=Math.min(A,B);X<he;++X)if(f[X]!==k[X]){A=f[X],B=k[X];break}return A<B?-1:B<A?1:0},i.isEncoding=function(f){switch(String(f).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(f,k){if(!Array.isArray(f))throw new TypeError('"list" argument must be an Array of Buffers');if(f.length===0)return i.alloc(0);let A;if(k===void 0)for(k=0,A=0;A<f.length;++A)k+=f[A].length;let B=i.allocUnsafe(k),X=0;for(A=0;A<f.length;++A){let he=f[A];if(H(he,Uint8Array))X+he.length>B.length?(i.isBuffer(he)||(he=i.from(he)),he.copy(B,X)):Uint8Array.prototype.set.call(B,he,X);else if(i.isBuffer(he))he.copy(B,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=he.length}return B};function m(f,k){if(i.isBuffer(f))return f.length;if(ArrayBuffer.isView(f)||H(f,ArrayBuffer))return f.byteLength;if(typeof f!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof f);let A=f.length,B=arguments.length>2&&arguments[2]===!0;if(!B&&A===0)return 0;let X=!1;for(;;)switch(k){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return F(f).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(f).length;default:if(X)return B?-1:F(f).length;k=(""+k).toLowerCase(),X=!0}}i.byteLength=m;function _(f,k,A){let B=!1;if((k===void 0||k<0)&&(k=0),k>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,k>>>=0,A<=k))return"";for(f||(f="utf8");;)switch(f){case"hex":return V(this,k,A);case"utf8":case"utf-8":return q(this,k,A);case"ascii":return ae(this,k,A);case"latin1":case"binary":return Y(this,k,A);case"base64":return T(this,k,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,k,A);default:if(B)throw new TypeError("Unknown encoding: "+f);f=(f+"").toLowerCase(),B=!0}}i.prototype._isBuffer=!0;function x(f,k,A){let B=f[k];f[k]=f[A],f[A]=B}i.prototype.swap16=function(){let f=this.length;if(f%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let k=0;k<f;k+=2)x(this,k,k+1);return this},i.prototype.swap32=function(){let f=this.length;if(f%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let k=0;k<f;k+=4)x(this,k,k+3),x(this,k+1,k+2);return this},i.prototype.swap64=function(){let f=this.length;if(f%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let k=0;k<f;k+=8)x(this,k,k+7),x(this,k+1,k+6),x(this,k+2,k+5),x(this,k+3,k+4);return this},i.prototype.toString=function(){let f=this.length;return f===0?"":arguments.length===0?q(this,0,f):_.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(f){if(!i.isBuffer(f))throw new TypeError("Argument must be a Buffer");return this===f?!0:i.compare(this,f)===0},i.prototype.inspect=function(){let f="",k=_t.INSPECT_MAX_BYTES;return f=this.toString("hex",0,k).replace(/(.{2})/g,"$1 ").trim(),this.length>k&&(f+=" ... "),"<Buffer "+f+">"},t&&(i.prototype[t]=i.prototype.inspect),i.prototype.compare=function(f,k,A,B,X){if(H(f,Uint8Array)&&(f=i.from(f,f.offset,f.byteLength)),!i.isBuffer(f))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof f);if(k===void 0&&(k=0),A===void 0&&(A=f?f.length:0),B===void 0&&(B=0),X===void 0&&(X=this.length),k<0||A>f.length||B<0||X>this.length)throw new RangeError("out of range index");if(B>=X&&k>=A)return 0;if(B>=X)return-1;if(k>=A)return 1;if(k>>>=0,A>>>=0,B>>>=0,X>>>=0,this===f)return 0;let he=X-B,ke=A-k,z=Math.min(he,ke),ie=this.slice(B,X),Ae=f.slice(k,A);for(let Ie=0;Ie<z;++Ie)if(ie[Ie]!==Ae[Ie]){he=ie[Ie],ke=Ae[Ie];break}return he<ke?-1:ke<he?1:0};function v(f,k,A,B,X){if(f.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:f.length-1),A<0&&(A=f.length+A),A>=f.length){if(X)return-1;A=f.length-1}else if(A<0)if(X)A=0;else return-1;if(typeof k=="string"&&(k=i.from(k,B)),i.isBuffer(k))return k.length===0?-1:E(f,k,A,B,X);if(typeof k=="number")return k=k&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(f,k,A):Uint8Array.prototype.lastIndexOf.call(f,k,A):E(f,[k],A,B,X);throw new TypeError("val must be string, number or Buffer")}function E(f,k,A,B,X){let he=1,ke=f.length,z=k.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(f.length<2||k.length<2)return-1;he=2,ke/=2,z/=2,A/=2}function ie(Ie,Ce){return he===1?Ie[Ce]:Ie.readUInt16BE(Ce*he)}let Ae;if(X){let Ie=-1;for(Ae=A;Ae<ke;Ae++)if(ie(f,Ae)===ie(k,Ie===-1?0:Ae-Ie)){if(Ie===-1&&(Ie=Ae),Ae-Ie+1===z)return Ie*he}else Ie!==-1&&(Ae-=Ae-Ie),Ie=-1}else for(A+z>ke&&(A=ke-z),Ae=A;Ae>=0;Ae--){let Ie=!0;for(let Ce=0;Ce<z;Ce++)if(ie(f,Ae+Ce)!==ie(k,Ce)){Ie=!1;break}if(Ie)return Ae}return-1}i.prototype.includes=function(f,k,A){return this.indexOf(f,k,A)!==-1},i.prototype.indexOf=function(f,k,A){return v(this,f,k,A,!0)},i.prototype.lastIndexOf=function(f,k,A){return v(this,f,k,A,!1)};function S(f,k,A,B){A=Number(A)||0;let X=f.length-A;B?(B=Number(B),B>X&&(B=X)):B=X;let he=k.length;B>he/2&&(B=he/2);let ke;for(ke=0;ke<B;++ke){let z=parseInt(k.substr(ke*2,2),16);if(me(z))return ke;f[A+ke]=z}return ke}function I(f,k,A,B){return ye(F(k,f.length-A),f,A,B)}function O(f,k,A,B){return ye(ee(k),f,A,B)}function P(f,k,A,B){return ye(fe(k),f,A,B)}function j(f,k,A,B){return ye(de(k,f.length-A),f,A,B)}i.prototype.write=function(f,k,A,B){if(k===void 0)B="utf8",A=this.length,k=0;else if(A===void 0&&typeof k=="string")B=k,A=this.length,k=0;else if(isFinite(k))k=k>>>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-k;if((A===void 0||A>X)&&(A=X),f.length>0&&(A<0||k<0)||k>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let he=!1;for(;;)switch(B){case"hex":return S(this,f,k,A);case"utf8":case"utf-8":return I(this,f,k,A);case"ascii":case"latin1":case"binary":return O(this,f,k,A);case"base64":return P(this,f,k,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,f,k,A);default:if(he)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),he=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(f,k,A){return k===0&&A===f.length?s.fromByteArray(f):s.fromByteArray(f.slice(k,A))}function q(f,k,A){A=Math.min(f.length,A);let B=[],X=k;for(;X<A;){let he=f[X],ke=null,z=he>239?4:he>223?3:he>191?2:1;if(X+z<=A){let ie,Ae,Ie,Ce;switch(z){case 1:he<128&&(ke=he);break;case 2:ie=f[X+1],(ie&192)===128&&(Ce=(he&31)<<6|ie&63,Ce>127&&(ke=Ce));break;case 3:ie=f[X+1],Ae=f[X+2],(ie&192)===128&&(Ae&192)===128&&(Ce=(he&15)<<12|(ie&63)<<6|Ae&63,Ce>2047&&(Ce<55296||Ce>57343)&&(ke=Ce));break;case 4:ie=f[X+1],Ae=f[X+2],Ie=f[X+3],(ie&192)===128&&(Ae&192)===128&&(Ie&192)===128&&(Ce=(he&15)<<18|(ie&63)<<12|(Ae&63)<<6|Ie&63,Ce>65535&&Ce<1114112&&(ke=Ce))}}ke===null?(ke=65533,z=1):ke>65535&&(ke-=65536,B.push(ke>>>10&1023|55296),ke=56320|ke&1023),B.push(ke),X+=z}return U(B)}let D=4096;function U(f){let k=f.length;if(k<=D)return String.fromCharCode.apply(String,f);let A="",B=0;for(;B<k;)A+=String.fromCharCode.apply(String,f.slice(B,B+=D));return A}function ae(f,k,A){let B="";A=Math.min(f.length,A);for(let X=k;X<A;++X)B+=String.fromCharCode(f[X]&127);return B}function Y(f,k,A){let B="";A=Math.min(f.length,A);for(let X=k;X<A;++X)B+=String.fromCharCode(f[X]);return B}function V(f,k,A){let B=f.length;(!k||k<0)&&(k=0),(!A||A<0||A>B)&&(A=B);let X="";for(let he=k;he<A;++he)X+=ve[f[he]];return X}function re(f,k,A){let B=f.slice(k,A),X="";for(let he=0;he<B.length-1;he+=2)X+=String.fromCharCode(B[he]+B[he+1]*256);return X}i.prototype.slice=function(f,k){let A=this.length;f=~~f,k=k===void 0?A:~~k,f<0?(f+=A,f<0&&(f=0)):f>A&&(f=A),k<0?(k+=A,k<0&&(k=0)):k>A&&(k=A),k<f&&(k=f);let B=this.subarray(f,k);return Object.setPrototypeOf(B,i.prototype),B};function $(f,k,A){if(f%1!==0||f<0)throw new RangeError("offset is not uint");if(f+k>A)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(f,k,A){f=f>>>0,k=k>>>0,A||$(f,k,this.length);let B=this[f],X=1,he=0;for(;++he<k&&(X*=256);)B+=this[f+he]*X;return B},i.prototype.readUintBE=i.prototype.readUIntBE=function(f,k,A){f=f>>>0,k=k>>>0,A||$(f,k,this.length);let B=this[f+--k],X=1;for(;k>0&&(X*=256);)B+=this[f+--k]*X;return B},i.prototype.readUint8=i.prototype.readUInt8=function(f,k){return f=f>>>0,k||$(f,1,this.length),this[f]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(f,k){return f=f>>>0,k||$(f,2,this.length),this[f]|this[f+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(f,k){return f=f>>>0,k||$(f,2,this.length),this[f]<<8|this[f+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(f,k){return f=f>>>0,k||$(f,4,this.length),(this[f]|this[f+1]<<8|this[f+2]<<16)+this[f+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(f,k){return f=f>>>0,k||$(f,4,this.length),this[f]*16777216+(this[f+1]<<16|this[f+2]<<8|this[f+3])},i.prototype.readBigUInt64LE=se(function(f){f=f>>>0,J(f,"offset");let k=this[f],A=this[f+7];(k===void 0||A===void 0)&&ge(f,this.length-8);let B=k+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24,X=this[++f]+this[++f]*2**8+this[++f]*2**16+A*2**24;return BigInt(B)+(BigInt(X)<<BigInt(32))}),i.prototype.readBigUInt64BE=se(function(f){f=f>>>0,J(f,"offset");let k=this[f],A=this[f+7];(k===void 0||A===void 0)&&ge(f,this.length-8);let B=k*2**24+this[++f]*2**16+this[++f]*2**8+this[++f],X=this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(X)}),i.prototype.readIntLE=function(f,k,A){f=f>>>0,k=k>>>0,A||$(f,k,this.length);let B=this[f],X=1,he=0;for(;++he<k&&(X*=256);)B+=this[f+he]*X;return X*=128,B>=X&&(B-=Math.pow(2,8*k)),B},i.prototype.readIntBE=function(f,k,A){f=f>>>0,k=k>>>0,A||$(f,k,this.length);let B=k,X=1,he=this[f+--B];for(;B>0&&(X*=256);)he+=this[f+--B]*X;return X*=128,he>=X&&(he-=Math.pow(2,8*k)),he},i.prototype.readInt8=function(f,k){return f=f>>>0,k||$(f,1,this.length),this[f]&128?(255-this[f]+1)*-1:this[f]},i.prototype.readInt16LE=function(f,k){f=f>>>0,k||$(f,2,this.length);let A=this[f]|this[f+1]<<8;return A&32768?A|4294901760:A},i.prototype.readInt16BE=function(f,k){f=f>>>0,k||$(f,2,this.length);let A=this[f+1]|this[f]<<8;return A&32768?A|4294901760:A},i.prototype.readInt32LE=function(f,k){return f=f>>>0,k||$(f,4,this.length),this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24},i.prototype.readInt32BE=function(f,k){return f=f>>>0,k||$(f,4,this.length),this[f]<<24|this[f+1]<<16|this[f+2]<<8|this[f+3]},i.prototype.readBigInt64LE=se(function(f){f=f>>>0,J(f,"offset");let k=this[f],A=this[f+7];(k===void 0||A===void 0)&&ge(f,this.length-8);let B=this[f+4]+this[f+5]*2**8+this[f+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(k+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24)}),i.prototype.readBigInt64BE=se(function(f){f=f>>>0,J(f,"offset");let k=this[f],A=this[f+7];(k===void 0||A===void 0)&&ge(f,this.length-8);let B=(k<<24)+this[++f]*2**16+this[++f]*2**8+this[++f];return(BigInt(B)<<BigInt(32))+BigInt(this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+A)}),i.prototype.readFloatLE=function(f,k){return f=f>>>0,k||$(f,4,this.length),e.read(this,f,!0,23,4)},i.prototype.readFloatBE=function(f,k){return f=f>>>0,k||$(f,4,this.length),e.read(this,f,!1,23,4)},i.prototype.readDoubleLE=function(f,k){return f=f>>>0,k||$(f,8,this.length),e.read(this,f,!0,52,8)},i.prototype.readDoubleBE=function(f,k){return f=f>>>0,k||$(f,8,this.length),e.read(this,f,!1,52,8)};function Z(f,k,A,B,X,he){if(!i.isBuffer(f))throw new TypeError('"buffer" argument must be a Buffer instance');if(k>X||k<he)throw new RangeError('"value" argument is out of bounds');if(A+B>f.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(f,k,A,B){if(f=+f,k=k>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,f,k,A,ke,0)}let X=1,he=0;for(this[k]=f&255;++he<A&&(X*=256);)this[k+he]=f/X&255;return k+A},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(f,k,A,B){if(f=+f,k=k>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,f,k,A,ke,0)}let X=A-1,he=1;for(this[k+X]=f&255;--X>=0&&(he*=256);)this[k+X]=f/he&255;return k+A},i.prototype.writeUint8=i.prototype.writeUInt8=function(f,k,A){return f=+f,k=k>>>0,A||Z(this,f,k,1,255,0),this[k]=f&255,k+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(f,k,A){return f=+f,k=k>>>0,A||Z(this,f,k,2,65535,0),this[k]=f&255,this[k+1]=f>>>8,k+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(f,k,A){return f=+f,k=k>>>0,A||Z(this,f,k,2,65535,0),this[k]=f>>>8,this[k+1]=f&255,k+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(f,k,A){return f=+f,k=k>>>0,A||Z(this,f,k,4,4294967295,0),this[k+3]=f>>>24,this[k+2]=f>>>16,this[k+1]=f>>>8,this[k]=f&255,k+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(f,k,A){return f=+f,k=k>>>0,A||Z(this,f,k,4,4294967295,0),this[k]=f>>>24,this[k+1]=f>>>16,this[k+2]=f>>>8,this[k+3]=f&255,k+4};function M(f,k,A,B,X){G(k,B,X,f,A,7);let he=Number(k&BigInt(4294967295));f[A++]=he,he=he>>8,f[A++]=he,he=he>>8,f[A++]=he,he=he>>8,f[A++]=he;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return f[A++]=ke,ke=ke>>8,f[A++]=ke,ke=ke>>8,f[A++]=ke,ke=ke>>8,f[A++]=ke,A}function Q(f,k,A,B,X){G(k,B,X,f,A,7);let he=Number(k&BigInt(4294967295));f[A+7]=he,he=he>>8,f[A+6]=he,he=he>>8,f[A+5]=he,he=he>>8,f[A+4]=he;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return f[A+3]=ke,ke=ke>>8,f[A+2]=ke,ke=ke>>8,f[A+1]=ke,ke=ke>>8,f[A]=ke,A+8}i.prototype.writeBigUInt64LE=se(function(f,k=0){return M(this,f,k,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=se(function(f,k=0){return Q(this,f,k,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(f,k,A,B){if(f=+f,k=k>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,f,k,A,z-1,-z)}let X=0,he=1,ke=0;for(this[k]=f&255;++X<A&&(he*=256);)f<0&&ke===0&&this[k+X-1]!==0&&(ke=1),this[k+X]=(f/he>>0)-ke&255;return k+A},i.prototype.writeIntBE=function(f,k,A,B){if(f=+f,k=k>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,f,k,A,z-1,-z)}let X=A-1,he=1,ke=0;for(this[k+X]=f&255;--X>=0&&(he*=256);)f<0&&ke===0&&this[k+X+1]!==0&&(ke=1),this[k+X]=(f/he>>0)-ke&255;return k+A},i.prototype.writeInt8=function(f,k,A){return f=+f,k=k>>>0,A||Z(this,f,k,1,127,-128),f<0&&(f=255+f+1),this[k]=f&255,k+1},i.prototype.writeInt16LE=function(f,k,A){return f=+f,k=k>>>0,A||Z(this,f,k,2,32767,-32768),this[k]=f&255,this[k+1]=f>>>8,k+2},i.prototype.writeInt16BE=function(f,k,A){return f=+f,k=k>>>0,A||Z(this,f,k,2,32767,-32768),this[k]=f>>>8,this[k+1]=f&255,k+2},i.prototype.writeInt32LE=function(f,k,A){return f=+f,k=k>>>0,A||Z(this,f,k,4,2147483647,-2147483648),this[k]=f&255,this[k+1]=f>>>8,this[k+2]=f>>>16,this[k+3]=f>>>24,k+4},i.prototype.writeInt32BE=function(f,k,A){return f=+f,k=k>>>0,A||Z(this,f,k,4,2147483647,-2147483648),f<0&&(f=4294967295+f+1),this[k]=f>>>24,this[k+1]=f>>>16,this[k+2]=f>>>8,this[k+3]=f&255,k+4},i.prototype.writeBigInt64LE=se(function(f,k=0){return M(this,f,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=se(function(f,k=0){return Q(this,f,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(f,k,A,B,X,he){if(A+B>f.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(f,k,A,B,X){return k=+k,A=A>>>0,X||be(f,k,A,4),e.write(f,k,A,B,23,4),A+4}i.prototype.writeFloatLE=function(f,k,A){return te(this,f,k,!0,A)},i.prototype.writeFloatBE=function(f,k,A){return te(this,f,k,!1,A)};function we(f,k,A,B,X){return k=+k,A=A>>>0,X||be(f,k,A,8),e.write(f,k,A,B,52,8),A+8}i.prototype.writeDoubleLE=function(f,k,A){return we(this,f,k,!0,A)},i.prototype.writeDoubleBE=function(f,k,A){return we(this,f,k,!1,A)},i.prototype.copy=function(f,k,A,B){if(!i.isBuffer(f))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),k>=f.length&&(k=f.length),k||(k=0),B>0&&B<A&&(B=A),B===A||f.length===0||this.length===0)return 0;if(k<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),f.length-k<B-A&&(B=f.length-k+A);let X=B-A;return this===f&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(k,A,B):Uint8Array.prototype.set.call(f,this.subarray(A,B),k),X},i.prototype.fill=function(f,k,A,B){if(typeof f=="string"){if(typeof k=="string"?(B=k,k=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(f.length===1){let he=f.charCodeAt(0);(B==="utf8"&&he<128||B==="latin1")&&(f=he)}}else typeof f=="number"?f=f&255:typeof f=="boolean"&&(f=Number(f));if(k<0||this.length<k||this.length<A)throw new RangeError("Out of range index");if(A<=k)return this;k=k>>>0,A=A===void 0?this.length:A>>>0,f||(f=0);let X;if(typeof f=="number")for(X=k;X<A;++X)this[X]=f;else{let he=i.isBuffer(f)?f:i.from(f,B),ke=he.length;if(ke===0)throw new TypeError('The value "'+f+'" is invalid for argument "value"');for(X=0;X<A-k;++X)this[X+k]=he[X%ke]}return this};let K={};function N(f,k,A){K[f]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:k.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${f}]`,this.stack,delete this.name}get code(){return f}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${f}]: ${this.message}`}}}N("ERR_BUFFER_OUT_OF_BOUNDS",function(f){return f?`${f} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),N("ERR_INVALID_ARG_TYPE",function(f,k){return`The "${f}" argument must be of type number. Received type ${typeof k}`},TypeError),N("ERR_OUT_OF_RANGE",function(f,k,A){let B=`The value of "${f}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>2**32?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 ${k}. Received ${X}`,B},RangeError);function ne(f){let k="",A=f.length,B=f[0]==="-"?1:0;for(;A>=B+4;A-=3)k=`_${f.slice(A-3,A)}${k}`;return`${f.slice(0,A)}${k}`}function W(f,k,A){J(k,"offset"),(f[k]===void 0||f[k+A]===void 0)&&ge(k,f.length-(A+1))}function G(f,k,A,B,X,he){if(f>A||f<k){let ke=typeof k=="bigint"?"n":"",z;throw k===0||k===BigInt(0)?z=`>= 0${ke} and < 2${ke} ** ${(he+1)*8}${ke}`:z=`>= -(2${ke} ** ${(he+1)*8-1}${ke}) and < 2 ** ${(he+1)*8-1}${ke}`,new K.ERR_OUT_OF_RANGE("value",z,f)}W(B,X,he)}function J(f,k){if(typeof f!="number")throw new K.ERR_INVALID_ARG_TYPE(k,"number",f)}function ge(f,k,A){throw Math.floor(f)!==f?(J(f,A),new K.ERR_OUT_OF_RANGE("offset","an integer",f)):k<0?new K.ERR_BUFFER_OUT_OF_BOUNDS:new K.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${k}`,f)}let oe=/[^+/0-9A-Za-z-_]/g;function R(f){if(f=f.split("=")[0],f=f.trim().replace(oe,""),f.length<2)return"";for(;f.length%4!==0;)f=f+"=";return f}function F(f,k){k=k||1/0;let A,B=f.length,X=null,he=[];for(let ke=0;ke<B;++ke){if(A=f.charCodeAt(ke),A>55295&&A<57344){if(!X){if(A>56319){(k-=3)>-1&&he.push(239,191,189);continue}else if(ke+1===B){(k-=3)>-1&&he.push(239,191,189);continue}X=A;continue}if(A<56320){(k-=3)>-1&&he.push(239,191,189),X=A;continue}A=(X-55296<<10|A-56320)+65536}else X&&(k-=3)>-1&&he.push(239,191,189);if(X=null,A<128){if((k-=1)<0)break;he.push(A)}else if(A<2048){if((k-=2)<0)break;he.push(A>>6|192,A&63|128)}else if(A<65536){if((k-=3)<0)break;he.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((k-=4)<0)break;he.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return he}function ee(f){let k=[];for(let A=0;A<f.length;++A)k.push(f.charCodeAt(A)&255);return k}function de(f,k){let A,B,X,he=[];for(let ke=0;ke<f.length&&!((k-=2)<0);++ke)A=f.charCodeAt(ke),B=A>>8,X=A%256,he.push(X),he.push(B);return he}function fe(f){return s.toByteArray(R(f))}function ye(f,k,A,B){let X;for(X=0;X<B&&!(X+A>=k.length||X>=f.length);++X)k[X+A]=f[X];return X}function H(f,k){return f instanceof k||f!=null&&f.constructor!=null&&f.constructor.name!=null&&f.constructor.name===k.name}function me(f){return f!==f}let ve=(function(){let f="0123456789abcdef",k=new Array(256);for(let A=0;A<16;++A){let B=A*16;for(let X=0;X<16;++X)k[B+X]=f[A]+f[X]}return k})();function se(f){return typeof BigInt>"u"?Oe:f}function Oe(){throw new Error("BigInt not supported")}return _t}var qt,yi,ir,vi,_t,wi,Yc=Je(()=>{le(),ue(),ce(),qt={},yi=!1,ir={},vi=!1,_t={},wi=!1}),$e={};Gt($e,{Buffer:()=>Wr,INSPECT_MAX_BYTES:()=>ya,default:()=>ut,kMaxLength:()=>va});var ut,Wr,ya,va,Fe=Je(()=>{le(),ue(),ce(),Yc(),ut=Gc(),ut.Buffer,ut.SlowBuffer,ut.INSPECT_MAX_BYTES,ut.kMaxLength,Wr=ut.Buffer,ya=ut.INSPECT_MAX_BYTES,va=ut.kMaxLength}),ue=Je(()=>{Fe()}),Ue=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}}),wa=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}=wa(),{AggregateError:o}=Ue(),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 h(m,_){if(!m)throw new u.ERR_INTERNAL_ASSERTION(_)}function p(m){let _="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)_=`_${m.slice(x-3,x)}${_}`;return`${m.slice(0,x)}${_}`}function b(m,_,x){if(typeof _=="function")return h(_.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${_.length}).`),_(...x);let v=(_.match(/%[dfijoOs]/g)||[]).length;return h(v===x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${v}).`),x.length===0?_:t(_,...x)}function d(m,_,x){x||(x=Error);class v extends x{constructor(...S){super(b(m,_,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 g(m){let _=c+m.name;return Object.defineProperty(m,"name",{value:_}),m}function y(m,_){if(m&&_&&m!==_){if(Array.isArray(_.errors))return _.errors.push(m),_;let x=new n([_,m],_.message);return x.code=_.code,x}return m||_}var w=class extends Error{constructor(m="The operation was aborted",_=void 0){if(_!==void 0&&typeof _!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",_);super(m,_),this.code="ABORT_ERR",this.name="AbortError"}};d("ERR_ASSERTION","%s",Error),d("ERR_INVALID_ARG_TYPE",(m,_,x)=>{h(typeof m=="string","'name' must be a string"),Array.isArray(_)||(_=[_]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let E=[],S=[],I=[];for(let P of _)h(typeof P=="string","All expected entries have to be of type string"),a.includes(P)?E.push(P.toLowerCase()):l.test(P)?S.push(P):(h(P!=="object",'The value "object" should be written as "Object"'),I.push(P));if(S.length>0){let P=E.indexOf("object");P!==-1&&(E.splice(E,P,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 P=E.pop();v+=`one of type ${E.join(", ")}, or ${P}`}}(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 P=S.pop();v+=`an instance of ${S.join(", ")}, or ${P}`}}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 P=I.pop();v+=`one of ${I.join(", ")}, or ${P}`}}if(x==null)v+=`. Received ${x}`;else if(typeof x=="function"&&x.name)v+=`. Received function ${x.name}`;else if(typeof x=="object"){var O;if((O=x.constructor)!==null&&O!==void 0&&O.name)v+=`. Received an instance of ${x.constructor.name}`;else{let P=r(x,{depth:-1});v+=`. Received ${P}`}}else{let P=r(x,{colors:!1});P.length>25&&(P=`${P.slice(0,25)}...`),v+=`. Received type ${typeof x} (${P})`}return v},TypeError),d("ERR_INVALID_ARG_VALUE",(m,_,x="is invalid")=>{let v=r(_);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${x}. Received ${v}`},TypeError),d("ERR_INVALID_RETURN_VALUE",(m,_,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 "${_}" function but got ${E}.`},TypeError),d("ERR_MISSING_ARGS",(...m)=>{h(m.length>0,"At least one arg needs to be specified");let _,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:_+=`The ${m[0]} argument`;break;case 2:_+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();_+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${_} must be specified`},TypeError),d("ERR_OUT_OF_RANGE",(m,_,x)=>{h(_,'Missing "range" argument');let v;if(Number.isInteger(x)&&Math.abs(x)>2**32)v=p(String(x));else if(typeof x=="bigint"){v=String(x);let E=BigInt(2)**BigInt(32);(x>E||x<-E)&&(v=p(v)),v+="n"}else v=r(x);return`The value of "${m}" is out of range. It must be ${_}. Received ${v}`},RangeError),d("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),d("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),d("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),d("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),d("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),d("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),d("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),d("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),d("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),d("ERR_STREAM_WRITE_AFTER_END","write after end",Error),d("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:g(y),hideStackFrames:g,codes:u}}),cr=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}),St={};Gt(St,{EventEmitter:()=>_a,default:()=>Ht,defaultMaxListeners:()=>ka,init:()=>xa,listenerCount:()=>Sa,on:()=>Ea,once:()=>Aa});function Jc(){if(_i)return or;_i=!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)}or=n,or.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 O;if(v.length>0&&(O=v[0]),O instanceof Error)throw O;var P=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw P.context=O,P}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=d(j,T),E=0;E<T;++E)e(q[E],this,v);return!0};function c(x,v,E,S){var I,O,P;if(a(E),O=x._events,O===void 0?(O=x._events=Object.create(null),x._eventsCount=0):(O.newListener!==void 0&&(x.emit("newListener",v,E.listener?E.listener:E),O=x._events),P=O[v]),P===void 0)P=O[v]=E,++x._eventsCount;else if(typeof P=="function"?P=O[v]=S?[E,P]:[P,E]:S?P.unshift(E):P.push(E),I=l(x),I>0&&P.length>I&&!P.warned){P.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+P.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=x,j.type=v,j.count=P.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 h(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,h(this,x,v)),this},n.prototype.prependOnceListener=function(x,v){return a(v),this.prependListener(x,h(this,x,v)),this},n.prototype.removeListener=function(x,v){var E,S,I,O,P;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,O=E.length-1;O>=0;O--)if(E[O]===v||E[O].listener===v){P=E[O].listener,I=O;break}if(I<0)return this;I===0?E.shift():g(E,I),E.length===1&&(S[x]=E[0]),S.removeListener!==void 0&&this.emit("removeListener",x,P||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),O;for(S=0;S<I.length;++S)O=I[S],O!=="removeListener"&&this.removeAllListeners(O);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 p(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):d(I,I.length)}n.prototype.listeners=function(x){return p(this,x,!0)},n.prototype.rawListeners=function(x){return p(this,x,!1)},n.listenerCount=function(x,v){return typeof x.listenerCount=="function"?x.listenerCount(v):b.call(x,v)},n.prototype.listenerCount=b;function b(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 d(x,v){for(var E=new Array(v),S=0;S<v;++S)E[S]=x[S];return E}function g(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(P){x.removeListener(v,O),S(P)}function O(){typeof x.removeListener=="function"&&x.removeListener("error",I),E([].slice.call(arguments))}_(x,v,O,{once:!0}),v!=="error"&&m(x,I,{once:!0})})}function m(x,v,E){typeof x.on=="function"&&_(x,"error",v,E)}function _(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(O){S.once&&x.removeEventListener(v,I),E(O)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return or}var or,_i,Ht,_a,ka,xa,Sa,Ea,Aa,jt=Je(()=>{le(),ue(),ce(),or={},_i=!1,Ht=Jc(),Ht.once,Ht.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)})},Ht.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,h)=>r.push({resolve:u,reject:h}))},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:_a,defaultMaxListeners:ka,init:xa,listenerCount:Sa,on:Ea,once:Aa}=Ht}),Ye=pe((s,e)=>{le(),ue(),ce();var t=(Fe(),Re($e)),{format:r,inspect:o}=wa(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ke(),{kResistStopPropagation:i,AggregateError:a,SymbolDispose:l}=Ue(),c=globalThis.AbortSignal||cr().AbortSignal,u=globalThis.AbortController||cr().AbortController,h=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,b=typeof p<"u"?function(y){return y instanceof p}:function(y){return!1},d=(y,w)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new n(w,"AbortSignal",y)},g=(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,_)=>{y=m,w=_}),resolve:y,reject:w}},promisify(y){return new Promise((w,m)=>{y((_,...x)=>_?m(_):w(...x))})},debuglog(){return function(){}},format:r,inspect:o,types:{isAsyncFunction(y){return y instanceof h},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:b,deprecate(y,w){return y},addAbortListener:(jt(),Re(St)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);d(y,"signal"),g(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 _;(_=m)===null||_===void 0||_()}}},AbortSignalAny:c.any||function(y){if(y.length===1)return y[0];let w=new u,m=()=>w.abort();return y.forEach(_=>{d(_,"signals"),_.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{y.forEach(_=>_.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),ur=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:h,RegExpPrototypeExec:p,String:b,StringPrototypeToUpperCase:d,StringPrototypeTrim:g}=Ue(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:_,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ke(),{normalizeEncoding:E}=Ye(),{isAsyncFunction:S,isArrayBufferView:I}=Ye().types,O={};function P(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(p(T,H)===null)throw new _(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,Oe=4294967295;if(H<se||H>Oe)throw new x(me,`>= ${se} && <= ${Oe}`,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,Oe=>typeof Oe=="string"?`'${Oe}'`:b(Oe)),", ");throw new _(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||!h(H,me)?ve:H[me]}var Q=y((H,me,ve=null)=>{let se=M(ve,"allowArray",!1),Oe=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!se&&t(H)||typeof H!="object"&&(!Oe||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 _(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],Oe=`${me}[${ve}]`;if(se==null)throw new m(Oe,"AbortSignal",se);ge(se,Oe)}}function ne(H,me="signal"){if(V(H,me),O[H]===void 0)throw O[d(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 _("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"&&g(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 de=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!p(de,H))throw new _(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 Oe=H[se];fe(Oe,"hints"),ve+=Oe,se!==me-1&&(ve+=", ")}return ve}throw new _("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:P,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}}),Ut=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,h,p=-1;function b(){!u||!h||(u=!1,h.length?c=h.concat(c):p=-1,c.length&&d())}function d(){if(!u){var w=a(b);u=!0;for(var m=c.length;m;){for(h=c,c=[];++p<m;)h&&h[p].run();p=-1,m=c.length}h=null,u=!1,l(w)}}t.nextTick=function(w){var m=new Array(arguments.length-1);if(arguments.length>1)for(var _=1;_<arguments.length;_++)m[_-1]=arguments[_];c.push(new g(w,m)),c.length===1&&!u&&a(d)};function g(w,m){this.fun=w,this.array=m}g.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}}),mt=pe((s,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:o}=Ue(),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"),h=o("nodejs.webstream.controllerErrorFunction");function p(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 b(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 d(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function g(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&&!g(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function w(M){return!!(M&&!g(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!g(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function _(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(!g(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(!b(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(!b(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(!p(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 O(M,Q){if(!p(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 P(M){return M&&M[a]!=null?M[a]:typeof M?.readable!="boolean"?null:v(M)?!1:p(M)&&M.readable&&!O(M)}function j(M){return M&&M[l]!=null?M[l]:typeof M?.writable!="boolean"?null:v(M)?!1:b(M)&&M.writable&&!E(M)}function T(M,Q){return g(M)?v(M)?!0:!(Q?.readable!==!1&&P(M)||Q?.writable!==!1&&j(M)):null}function q(M){var Q,be;return g(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 g(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(!g(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(!g(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:P,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:h,kIsWritable:l,isClosed:U,isDuplexNodeStream:d,isFinished:T,isIterable:x,isReadableNodeStream:p,isReadableStream:y,isReadableEnded:I,isReadableFinished:O,isReadableErrored:D,isNodeStream:g,isWebStream:_,isWritable:j,isWritableNodeStream:b,isWritableStream:w,isWritableEnded:E,isWritableFinished:S,isWritableErrored:q,isServerRequest:V,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),Et=pe((s,e)=>{le(),ue(),ce();var t=Ut(),{AbortError:r,codes:o}=Ke(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=o,{kEmptyObject:a,once:l}=Ye(),{validateAbortSignal:c,validateFunction:u,validateObject:h,validateBoolean:p}=ur(),{Promise:b,PromisePrototypeThen:d,SymbolDispose:g}=Ue(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:_,isReadableFinished:x,isReadableErrored:v,isWritable:E,isWritableNodeStream:S,isWritableStream:I,isWritableFinished:O,isWritableErrored:P,isNodeStream:j,willEmitClose:T,kIsClosedPromise:q}=mt(),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:h(Z,"options"),u(M,"callback"),c(Z.signal,"options.signal"),M=l(M),_($)||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=O($,!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=P($)||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&&!O($,!1))return M.call($,new i);M.call($)},de=()=>{F=!0;let H=P($)||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(de):(!te&&(!W||w($))&&(G||E($)===!1)||!we&&(!W||E($))&&(ge||w($)===!1)||N&&$.req&&$.aborted)&&t.nextTick(de);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||Ye().addAbortListener;let me=D(Z.signal,H),ve=M;M=l((...se)=>{me[g](),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||Ye().addAbortListener;let we=D(Z.signal,be),K=M;M=l((...N)=>{we[g](),K.apply($,N)})}let te=(...we)=>{Q||t.nextTick(()=>M.apply($,we))};return d($[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&&(p(Z.cleanup,"cleanup"),Q=Z.cleanup),new b((be,te)=>{let we=Y($,Z,K=>{Q&&we(),K?te(K):be()})})}e.exports=Y,e.exports.finished=re}),Yt=pe((s,e)=>{le(),ue(),ce();var t=Ut(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:n}=Ke(),{Symbol:i}=Ue(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=mt(),h=i("kDestroy"),p=i("kConstruct");function b(T,q,D){T&&(T.stack,q&&!q.errored&&(q.errored=T),D&&!D.errored&&(D.errored=T))}function d(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):(b(T,U,D),U&&(U.destroyed=!0),D&&(D.destroyed=!0),ae.constructed?g(this,T,q):this.once(h,function(Y){g(this,r(Y,T),q)}),this)}function g(T,q,D){let U=!1;function ae(Y){if(U)return;U=!0;let V=T._readableState,re=T._writableState;b(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 _(){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(p,q),!(T.listenerCount(p)>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(h,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(p)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function O(T){T.emit("close")}function P(T,q){T.emit("error",q),t.nextTick(O,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(P,T,q):t.nextTick(O,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:j,destroy:d,undestroy:_,errorOrDestroy:x}}),yo=pe((s,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Ue(),{EventEmitter:o}=(jt(),Re(St));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 h(){c.readable&&c.resume&&c.resume()}a.on("drain",h),!a._isStdio&&(!l||l.end!==!1)&&(c.on("end",b),c.on("close",d));let p=!1;function b(){p||(p=!0,a.end())}function d(){p||(p=!0,typeof a.destroy=="function"&&a.destroy())}function g(w){y(),o.listenerCount(this,"error")===0&&this.emit("error",w)}i(c,"error",g),i(a,"error",g);function y(){c.removeListener("data",u),a.removeListener("drain",h),c.removeListener("end",b),c.removeListener("close",d),c.removeListener("error",g),a.removeListener("error",g),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}}),Kr=pe((s,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Ue(),{AbortError:r,codes:o}=Ke(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:a}=mt(),l=Et(),{ERR_INVALID_ARG_TYPE:c}=o,u,h=(p,b)=>{if(typeof p!="object"||!("aborted"in p))throw new c(b,"AbortSignal",p)};e.exports.addAbortSignal=function(p,b){if(h(p,"signal"),!n(b)&&!i(b))throw new c("stream",["ReadableStream","WritableStream","Stream"],b);return e.exports.addAbortSignalNoValidate(p,b)},e.exports.addAbortSignalNoValidate=function(p,b){if(typeof p!="object"||!("aborted"in p))return b;let d=n(b)?()=>{b.destroy(new r(void 0,{cause:p.reason}))}:()=>{b[a](new r(void 0,{cause:p.reason}))};if(p.aborted)d();else{u=u||Ye().addAbortListener;let g=u(p,d);l(b,g[t])}return b}}),Qc=pe((s,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:o,Uint8Array:n}=Ue(),{Buffer:i}=(Fe(),Re($e)),{inspect:a}=Ye();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,h=0;for(;u;)o(c,u.data,h),h+=u.data.length,u=u.next;return c}consume(l,c){let u=this.head.data;if(l<u.length){let h=u.slice(0,l);return this.head.data=u.slice(l),h}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,h=0;do{let p=u.data;if(l>p.length)c+=p,l-=p.length;else{l===p.length?(c+=p,++h,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,l),this.head=u,u.data=t(p,l));break}++h}while((u=u.next)!==null);return this.length-=h,c}_getBuffer(l){let c=i.allocUnsafe(l),u=l,h=this.head,p=0;do{let b=h.data;if(l>b.length)o(c,b,u-l),l-=b.length;else{l===b.length?(o(c,b,u-l),++p,h.next?this.head=h.next:this.head=this.tail=null):(o(c,new n(b.buffer,b.byteOffset,l),u-l),this.head=h,h.data=b.slice(l));break}++p}while((h=h.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),Gr=pe((s,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Ue(),{validateInteger:o}=ur(),{ERR_INVALID_ARG_VALUE:n}=Ke().codes,i=16*1024,a=16;function l(p,b,d){return p.highWaterMark!=null?p.highWaterMark:b?p[d]:null}function c(p){return p?a:i}function u(p,b){o(b,"value",0),p?a=b:i=b}function h(p,b,d,g){let y=l(b,g,d);if(y!=null){if(!r(y)||y<0){let w=g?`options.${d}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(p.objectMode)}e.exports={getHighWaterMark:h,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),Xc=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)}}),Zc=pe(s=>{le(),ue(),ce();var e=Xc().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 _;;)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(_)return;m=(""+m).toLowerCase(),_=!0}}function o(m){var _=r(m);if(typeof _!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return _||m}s.StringDecoder=n;function n(m){this.encoding=o(m);var _;switch(this.encoding){case"utf16le":this.text=p,this.end=b,_=4;break;case"utf8":this.fillLast=c,_=4;break;case"base64":this.text=d,this.end=g,_=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(_)}n.prototype.write=function(m){if(m.length===0)return"";var _,x;if(this.lastNeed){if(_=this.fillLast(m),_===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?_?_+this.text(m,x):this.text(m,x):_||""},n.prototype.end=h,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,_,x){var v=_.length-1;if(v<x)return 0;var E=i(_[v]);return E>=0?(E>0&&(m.lastNeed=E-1),E):--v<x||E===-2?0:(E=i(_[v]),E>=0?(E>0&&(m.lastNeed=E-2),E):--v<x||E===-2?0:(E=i(_[v]),E>=0?(E>0&&(E===2?E=0:m.lastNeed=E-3),E):0))}function l(m,_,x){if((_[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&_.length>1){if((_[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&_.length>2&&(_[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var _=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,_,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,_,0,m.length),this.lastNeed-=m.length}function u(m,_){var x=a(this,m,_);if(!this.lastNeed)return m.toString("utf8",_);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",_,v)}function h(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+"�":_}function p(m,_){if((m.length-_)%2===0){var x=m.toString("utf16le",_);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",_,m.length-1)}function b(m){var _=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return _+this.lastChar.toString("utf16le",0,x)}return _}function d(m,_){var x=(m.length-_)%3;return x===0?m.toString("base64",_):(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",_,m.length-x))}function g(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+this.lastChar.toString("base64",0,3-this.lastNeed):_}function y(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),Ia=pe((s,e)=>{le(),ue(),ce();var t=Ut(),{PromisePrototypeThen:r,SymbolAsyncIterator:o,SymbolIterator:n}=Ue(),{Buffer:i}=(Fe(),Re($e)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ke().codes;function c(u,h,p){let b;if(typeof h=="string"||h instanceof i)return new u({objectMode:!0,...p,read(){this.push(h),this.push(null)}});let d;if(h&&h[o])d=!0,b=h[o]();else if(h&&h[n])d=!1,b=h[n]();else throw new a("iterable",["Iterable"],h);let g=new u({objectMode:!0,highWaterMark:1,...p}),y=!1;g._read=function(){y||(y=!0,m())},g._destroy=function(_,x){r(w(_),()=>t.nextTick(x,_),v=>t.nextTick(x,v||_))};async function w(_){let x=_!=null,v=typeof b.throw=="function";if(x&&v){let{value:E,done:S}=await b.throw(_);if(await E,S)return}if(typeof b.return=="function"){let{value:E}=await b.return();await E}}async function m(){for(;;){try{let{value:_,done:x}=d?await b.next():b.next();if(x)g.push(null);else{let v=_&&typeof _.then=="function"?await _:_;if(v===null)throw y=!1,new l;if(g.push(v))continue;y=!1}}catch(_){g.destroy(_)}break}}return g}e.exports=c}),Yr=pe((s,e)=>{le(),ue(),ce();var t=Ut(),{ArrayPrototypeIndexOf:r,NumberIsInteger:o,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:h,SymbolAsyncDispose:p,SymbolAsyncIterator:b,Symbol:d}=Ue();e.exports=se,se.ReadableState=ve;var{EventEmitter:g}=(jt(),Re(St)),{Stream:y,prependListener:w}=yo(),{Buffer:m}=(Fe(),Re($e)),{addAbortSignal:_}=Kr(),x=Et(),v=Ye().debuglog("stream",C=>{v=C}),E=Qc(),S=Yt(),{getHighWaterMark:I,getDefaultHighWaterMark:O}=Gr(),{aggregateTwoErrors:P,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}=ur(),V=d("kPaused"),{StringDecoder:re}=Zc(),$=Ia();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,de=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(de),multiAwaitDrain:me(fe),readingMore:me(ye),dataEmitted:me(H)});function ve(C,L,_e){typeof _e!="boolean"&&(_e=L instanceof ft()),this.state=oe|R|K|N,C&&C.objectMode&&(this.state|=Q),_e&&C&&C.readableObjectMode&&(this.state|=Q),this.highWaterMark=C?I(this,C,"readableHighWaterMark",_e):O(!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&&_(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[g.captureRejectionSymbol]=function(C){this.destroy(C)},se.prototype[p]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new ae,this.destroy(C)),new u((L,_e)=>x(this,xe=>xe&&xe!==C?_e(xe):L(null)))},se.prototype.push=function(C,L){return Oe(this,C,L,!1)},se.prototype.unshift=function(C,L){return Oe(this,C,L,!0)};function Oe(C,L,_e,xe){v("readableAddChunk",L);let Se=C._readableState,Be;if((Se.state&Q)===0&&(typeof L=="string"?(_e=_e||Se.defaultEncoding,Se.encoding!==_e&&(xe&&Se.encoding?L=m.from(L,_e).toString(Se.encoding):(L=m.from(L,_e),_e=""))):L instanceof m?_e="":y._isUint8Array(L)?(L=y._uint8ArrayToBuffer(L),_e=""):L!=null&&(Be=new j("chunk",["string","Buffer","Uint8Array"],L))),Be)M(C,Be);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;f(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&&!_e?(L=Se.decoder.write(L),Se.objectMode||L.length!==0?f(C,Se,L,!1):z(C,Se)):f(C,Se,L,!1)}else xe||(Se.state&=~we,z(C,Se));return!Se.ended&&(Se.length<Se.highWaterMark||Se.length===0)}function f(C,L,_e,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",_e)):(L.length+=L.objectMode?1:_e.length,xe?L.buffer.unshift(_e):L.buffer.push(_e),(L.state&ne)!==0&&he(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 _e=this._readableState.buffer,xe="";for(let Se of _e)xe+=L.write(Se);return _e.clear(),xe!==""&&_e.push(xe),this._readableState.length=xe.length,this};var k=1073741824;function A(C){if(C>k)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,_e=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?nt(this):he(this),null;if(C=B(C,L),C===0&&L.ended)return L.length===0&&nt(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(Be){M(this,Be)}L.state&=~N,L.reading||(C=B(_e,L))}let Se;return C>0?Se=$t(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),_e!==C&&L.ended&&nt(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 _e=L.decoder.end();_e&&_e.length&&(L.buffer.push(_e),L.length+=L.objectMode?1:_e.length)}L.ended=!0,L.sync?he(C):(L.needReadable=!1,L.emittedReadable=!0,ke(C))}}function he(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(ke,C))}function ke(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,tt(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 _e=L.length;if(v("maybeReadMore read 0"),C.read(0),_e===L.length)break}L.readingMore=!1}se.prototype._read=function(C){throw new T("_read()")},se.prototype.pipe=function(C,L){let _e=this,xe=this._readableState;xe.pipes.length===1&&(xe.multiAwaitDrain||(xe.multiAwaitDrain=!0,xe.awaitDrainWriters=new h(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?Ve:Tt;xe.endEmitted?t.nextTick(Se):_e.once("end",Se),C.on("unpipe",Be);function Be(ot,lt){v("onunpipe"),ot===_e&<&<.hasUnpiped===!1&&(lt.hasUnpiped=!0,er())}function Ve(){v("onend"),C.end()}let Ze,Zt=!1;function er(){v("cleanup"),C.removeListener("close",it),C.removeListener("finish",yt),Ze&&C.removeListener("drain",Ze),C.removeListener("error",It),C.removeListener("unpipe",Be),_e.removeListener("end",Ve),_e.removeListener("end",Tt),_e.removeListener("data",fr),Zt=!0,Ze&&xe.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&Ze()}function tr(){Zt||(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)),_e.pause()),Ze||(Ze=Ae(_e,C),C.on("drain",Ze))}_e.on("data",fr);function fr(ot){v("ondata");let lt=C.write(ot);v("dest.write",lt),lt===!1&&tr()}function It(ot){if(v("onerror",ot),Tt(),C.removeListener("error",It),C.listenerCount("error")===0){let lt=C._writableState||C._readableState;lt&&!lt.errorEmitted?M(C,ot):C.emit("error",ot)}}w(C,"error",It);function it(){C.removeListener("finish",yt),Tt()}C.once("close",it);function yt(){v("onfinish"),C.removeListener("close",it),Tt()}C.once("finish",yt);function Tt(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?tr():xe.flowing||(v("pipe resume"),_e.resume()),C};function Ae(C,L){return function(){let _e=C._readableState;_e.awaitDrainWriters===L?(v("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(v("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(L)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}se.prototype.unpipe=function(C){let L=this._readableState,_e={hasUnpiped:!1};if(L.pipes.length===0)return this;if(!C){let Se=L.pipes;L.pipes=[],this.pause();for(let Be=0;Be<Se.length;Be++)Se[Be].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,_e),this)},se.prototype.on=function(C,L){let _e=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?he(this):xe.reading||t.nextTick(Ce,this)),_e},se.prototype.addListener=se.prototype.on,se.prototype.removeListener=function(C,L){let _e=y.prototype.removeListener.call(this,C,L);return C==="readable"&&t.nextTick(Ie,this),_e},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(Ie,this),L};function Ie(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 Ce(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,Pe(this,C)),C[V]=!1,this};function Pe(C,L){L.resumeScheduled||(L.resumeScheduled=!0,t.nextTick(et,C,L))}function et(C,L){v("resume",L.reading),L.reading||C.read(0),L.resumeScheduled=!1,C.emit("resume"),tt(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 tt(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 _e=l(C);for(let xe=1;xe<_e.length;xe++){let Se=_e[xe];this[Se]===void 0&&typeof C[Se]=="function"&&(this[Se]=C[Se].bind(C))}return this},se.prototype[b]=function(){return qe(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),qe(this,C)};function qe(C,L){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let _e=rt(C,L);return _e.stream=C,_e}async function*rt(C,L){let _e=Z;function xe(Ve){this===C?(_e(),_e=Z):_e=Ve}C.on("readable",xe);let Se,Be=x(C,{writable:!1},Ve=>{Se=Ve?P(Se,Ve):null,_e(),_e=Z});try{for(;;){let Ve=C.destroyed?null:C.read();if(Ve!==null)yield Ve;else{if(Se)throw Se;if(Se===null)return;await new u(xe)}}}catch(Ve){throw Se=P(Se,Ve),Se}finally{(Se||L?.destroyOnReturn!==!1)&&(Se===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",xe),Be())}}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=$t;function $t(C,L){if(L.length===0)return null;let _e;return L.objectMode?_e=L.buffer.shift():!C||C>=L.length?(L.decoder?_e=L.buffer.join(""):L.buffer.length===1?_e=L.buffer.first():_e=L.buffer.concat(L.length),L.buffer.clear()):_e=L.buffer.consume(C,L.decoder),_e}function nt(C){let L=C._readableState;v("endReadable",L.endEmitted),L.endEmitted||(L.ended=!0,t.nextTick(Qe,L,C))}function Qe(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(dr,L);else if(C.autoDestroy){let _e=L._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&L.destroy()}}}function dr(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,L){return $(se,C,L)};var Ft;function Xt(){return Ft===void 0&&(Ft={}),Ft}se.fromWeb=function(C,L){return Xt().newStreamReadableFromReadableStream(C,L)},se.toWeb=function(C,L){return Xt().newReadableStreamFromStreamReadable(C,L)},se.wrap=function(C,L){var _e,xe;return new se({objectMode:(_e=(xe=C.readableObjectMode)!==null&&xe!==void 0?xe:C.objectMode)!==null&&_e!==void 0?_e:!0,...L,destroy(Se,Be){S.destroyer(C,Se),Be(Se)}}).wrap(C)}}),vo=pe((s,e)=>{le(),ue(),ce();var t=Ut(),{ArrayPrototypeSlice:r,Error:o,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:h}=Ue();e.exports=Y,Y.WritableState=U;var{EventEmitter:p}=(jt(),Re(St)),b=yo().Stream,{Buffer:d}=(Fe(),Re($e)),g=Yt(),{addAbortSignal:y}=Kr(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=Gr(),{ERR_INVALID_ARG_TYPE:_,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:O,ERR_STREAM_WRITE_AFTER_END:P,ERR_UNKNOWN_ENCODING:j}=Ke().codes,{errorOrDestroy:T}=g;l(Y.prototype,b.prototype),l(Y,b);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 de=!!(R&&R.decodeStrings===!1);this.decodeStrings=!de,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)),b.call(this,R),g.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),W(this,ee)})}i(Y,h,{__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,de){let fe=R._writableState;if(typeof ee=="function")de=ee,ee=fe.defaultEncoding;else{if(!ee)ee=fe.defaultEncoding;else if(ee!=="buffer"&&!d.isEncoding(ee))throw new j(ee);typeof de!="function"&&(de=q)}if(F===null)throw new O;if(!fe.objectMode)if(typeof F=="string")fe.decodeStrings!==!1&&(F=d.from(F,ee),ee="buffer");else if(F instanceof d)ee="buffer";else if(b._isUint8Array(F))F=b._uint8ArrayToBuffer(F),ee="buffer";else throw new _("chunk",["string","Buffer","Uint8Array"],F);let ye;return fe.ending?ye=new P:fe.destroyed&&(ye=new S("write")),ye?(t.nextTick(de,ye),T(R,ye,!0),ye):(fe.pendingcb++,re(R,fe,F,ee,de))}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)),!d.isEncoding(R))throw new j(R);return this._writableState.defaultEncoding=R,this};function re(R,F,ee,de,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:de,callback:fe}),F.allBuffers&&de!=="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,de,F.onwrite),F.sync=!1),H&&!F.errored&&!F.destroyed}function $(R,F,ee,de,fe,ye,H){F.writelen=de,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,de){--F.pendingcb,de(ee),te(F),T(R,ee)}function M(R,F){let ee=R._writableState,de=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),de?t.nextTick(Z,R,ee,F,fe):Z(R,ee,F,fe)):(ee.buffered.length>ee.bufferedIndex&&we(R,ee),de?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:de}){return F.afterWriteTickInfo=null,be(R,F,ee,de)}function be(R,F,ee,de){for(!F.ending&&!R.destroyed&&F.length===0&&F.needDrain&&(F.needDrain=!1,R.emit("drain"));ee-- >0;)F.pendingcb--,de();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 de;ee[fe]((de=R.errored)!==null&&de!==void 0?de:new S("end"))}ae(R)}function we(R,F){if(F.corked||F.bufferProcessing||F.destroyed||!F.constructed)return;let{buffered:ee,bufferedIndex:de,objectMode:fe}=F,ye=ee.length-de;if(!ye)return;let H=de;if(F.bufferProcessing=!0,ye>1&&R._writev){F.pendingcb-=ye-1;let me=F.allNoop?q:se=>{for(let Oe=H;Oe<ee.length;++Oe)ee[Oe].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 Oe=fe?1:me.length;$(R,F,!1,Oe,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 de=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 de.corked&&(de.corked=1,this.uncork()),fe||(!de.errored&&!de.ending?(de.ending=!0,W(this,de,!0),de.ended=!0):de.finished?fe=new I("end"):de.destroyed&&(fe=new S("end"))),typeof ee=="function"&&(fe||de.finished?t.nextTick(ee,fe):de[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 de(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(de)}catch(fe){de(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((de,fe)=>{K(fe)?G(de,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 de=0;de<ee.length;de++)ee[de]();if(R.emit("finish"),F.autoDestroy){let de=R._readableState;(!de||de.autoDestroy&&(de.endEmitted||de.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=g.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=g.undestroy,Y.prototype._destroy=function(R,F){F(R)},Y.prototype[p.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)}}),eu=pe((s,e)=>{le(),ue(),ce();var t=Ut(),r=(Fe(),Re($e)),{isReadable:o,isWritable:n,isIterable:i,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:h,isWritableStream:p}=mt(),b=Et(),{AbortError:d,codes:{ERR_INVALID_ARG_TYPE:g,ERR_INVALID_RETURN_VALUE:y}}=Ke(),{destroyer:w}=Yt(),m=ft(),_=Yr(),x=vo(),{createDeferredPromise:v}=Ye(),E=Ia(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},O=globalThis.AbortController||cr().AbortController,{FunctionPrototypeCall:P}=Ue(),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(h(U))return q({readable:_.fromWeb(U)});if(p(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=P(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(h(U?.readable)&&p(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 P(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 g(ae,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(D){let{promise:U,resolve:ae}=v(),Y=new O,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 d(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"?_.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&&(b(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&&(b(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 d),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}=Ue();e.exports=l;var i=Yr(),a=vo();n(l.prototype,i.prototype),n(l,i);{let p=o(a.prototype);for(let b=0;b<p.length;b++){let d=p[b];l.prototype[d]||(l.prototype[d]=a.prototype[d])}}function l(p){if(!(this instanceof l))return new l(p);i.call(this,p),a.call(this,p),p?(this.allowHalfOpen=p.allowHalfOpen!==!1,p.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),p.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(p){this._readableState&&this._writableState&&(this._readableState.destroyed=p,this._writableState.destroyed=p)}}});var c;function u(){return c===void 0&&(c={}),c}l.fromWeb=function(p,b){return u().newStreamDuplexFromReadableWritablePair(p,b)},l.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var h;l.from=function(p){return h||(h=eu()),h(p,"body")}}),Ta=pe((s,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Ue();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:o}=Ke().codes,n=ft(),{getHighWaterMark:i}=Gr();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(h){if(!(this instanceof l))return new l(h);let p=h?i(this,h,"readableHighWaterMark",!0):null;p===0&&(h={...h,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:h.writableHighWaterMark||0}),n.call(this,h),this._readableState.sync=!1,this[a]=null,h&&(typeof h.transform=="function"&&(this._transform=h.transform),typeof h.flush=="function"&&(this._flush=h.flush)),this.on("prefinish",u)}function c(h){typeof this._flush=="function"&&!this.destroyed?this._flush((p,b)=>{if(p){h?h(p):this.destroy(p);return}b!=null&&this.push(b),this.push(null),h&&h()}):(this.push(null),h&&h())}function u(){this._final!==c&&c.call(this)}l.prototype._final=c,l.prototype._transform=function(h,p,b){throw new o("_transform()")},l.prototype._write=function(h,p,b){let d=this._readableState,g=this._writableState,y=d.length;this._transform(h,p,(w,m)=>{if(w){b(w);return}m!=null&&this.push(m),g.ended||y===d.length||d.length<d.highWaterMark?b():this[a]=b})},l.prototype._read=function(){if(this[a]){let h=this[a];this[a]=null,h()}}}),Ca=pe((s,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Ue();e.exports=o;var r=Ta();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)}}),wo=pe((s,e)=>{le(),ue(),ce();var t=Ut(),{ArrayIsArray:r,Promise:o,SymbolAsyncIterator:n,SymbolDispose:i}=Ue(),a=Et(),{once:l}=Ye(),c=Yt(),u=ft(),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:b,ERR_MISSING_ARGS:d,ERR_STREAM_DESTROYED:g,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ke(),{validateFunction:m,validateAbortSignal:_}=ur(),{isIterable:x,isReadable:v,isReadableNodeStream:E,isNodeStream:S,isTransformStream:I,isWebStream:O,isReadableStream:P,isReadableFinished:j}=mt(),T=globalThis.AbortController||cr().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 g("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 p("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){D||(D=Yr()),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?h(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 d("streams");let N=new T,ne=N.signal,W=K?.signal,G=[];_(W,"options.signal");function J(){fe(new w)}U=U||Ye().addAbortListener;let ge;W&&(ge=U(W,J));let oe,R,F=[],ee=0;function de(ve){fe(ve,--ee===0)}function fe(ve,se){var Oe;if(ve&&(!oe||oe.code==="ERR_STREAM_PREMATURE_CLOSE")&&(oe=ve),!(!oe&&!se)){for(;F.length;)F.shift()(oe);(Oe=ge)===null||Oe===void 0||Oe[i](),N.abort(),se&&(oe||G.forEach(f=>f()),t.nextTick(we,oe,R))}}let ye;for(let ve=0;ve<te.length;ve++){let se=te[ve],Oe=ve<te.length-1,f=ve>0,k=Oe||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"&&de(X)};if(k){let{destroy:X,cleanup:he}=ae(se,Oe,f);F.push(X),v(se)&&A&&G.push(he)}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 b("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}),Oe){if(!x(ye,!0))throw new b("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;q||(q=Ca());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),k&&B.end(),t.nextTick(de)},z=>{B.destroy(z),t.nextTick(de,z)});else if(x(ye,!0))ee++,$(ye,B,de,{end:k});else if(P(ye)||I(ye)){let z=ye.readable||ye;ee++,$(z,B,de,{end:k})}else throw new b("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:he,cleanup:ke}=ae(ye,!1,!0);F.push(he),A&&G.push(ke)}}else if(S(se)){if(E(ye)){ee+=2;let B=be(ye,se,de,{end:k});v(se)&&A&&G.push(B)}else if(I(ye)||P(ye)){let B=ye.readable||ye;ee++,$(B,se,de,{end:k})}else if(x(ye))ee++,$(ye,se,de,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else if(O(se)){if(E(ye))ee++,Z(V(ye),se,de,{end:k});else if(P(ye)||x(ye))ee++,Z(ye,se,de,{end:k});else if(I(ye))ee++,Z(ye.readable,se,de,{end:k});else throw new p("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}}),Oa=pe((s,e)=>{le(),ue(),ce();var{pipeline:t}=wo(),r=ft(),{destroyer:o}=Yt(),{isNodeStream:n,isReadable:i,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:h}=mt(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:b,ERR_MISSING_ARGS:d}}=Ke(),g=Et();e.exports=function(...y){if(y.length===0)throw new d("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])||h(y[T])||c(y[T])))throw new b(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(y[T])||u(y[T])||c(y[T])))throw new b(`streams[${T}]`,w[T],"must be writable")}let m,_,x,v,E;function S(T){let q=v;v=null,q?q(T):T?E.destroy(T):!j&&!P&&E.destroy()}let I=y[0],O=t(y,S),P=!!(a(I)||u(I)||c(I)),j=!!(i(O)||h(O)||c(O));if(E=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(O!=null&&O.readableObjectMode),writable:P,readable:j}),P){if(n(I))E._write=function(q,D,U){I.write(q,D)?U():m=U},E._final=function(q){I.end(),_=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(()=>{}),_=D}catch(U){D(U)}}}let T=c(O)?O.readable:O;g(T,()=>{if(_){let q=_;_=null,q()}})}if(j){if(n(O))O.on("readable",function(){if(x){let T=x;x=null,T()}}),O.on("end",function(){E.push(null)}),E._read=function(){for(;;){let T=O.read();if(T===null){x=E._read;return}if(!E.push(T))return}};else if(l(O)){let T=(c(O)?O.readable:O).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 p),x=null,m=null,_=null,v===null?q(T):(v=q,n(O)&&o(O,T))},E}}),tu=pe((s,e)=>{le(),ue(),ce();var t=globalThis.AbortController||cr().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}=ur(),h=Ue().Symbol("kWeak"),p=Ue().Symbol("kResistStopPropagation"),{finished:b}=Et(),d=Oa(),{addAbortSignalNoValidate:g}=Kr(),{isWritable:y,isNodeStream:w}=mt(),{deprecate:m}=Ye(),{ArrayPrototypePush:_,Boolean:x,MathFloor:v,Number:E,NumberIsNaN:S,Promise:I,PromiseReject:O,PromiseResolve:P,PromisePrototypeThen:j,Symbol:T}=Ue(),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=d(this,W);return G!=null&&G.signal&&g(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=Ye().AbortSignalAny([G?.signal].filter(x)),R=this,F=[],ee={signal:oe},de,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 Oe(){try{for await(let f of R){if(ye)return;if(oe.aborted)throw new a;try{if(f=W(f,ee),f===q)continue;f=P(f)}catch(k){f=O(k)}H+=1,j(f,ve,me),F.push(f),de&&(de(),de=null),!ye&&(F.length>=ge||H>=J)&&await new I(k=>{fe=k})}F.push(D)}catch(f){let k=O(f);j(k,ve,me),F.push(k)}finally{ye=!0,de&&(de(),de=null)}}Oe();try{for(;;){for(;F.length>0;){let f=await F[0];if(f===D)return;if(oe.aborted)throw new a;f!==q&&(yield f),F.shift(),se()}await new I(f=>{de=f})}}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 b(this.destroy(fe)),fe}let R=new t,F=R.signal;if(J!=null&&J.signal){let fe={once:!0,[h]:this,[p]:!0};J.signal.addEventListener("abort",()=>R.abort(),fe)}let ee=!1;try{for await(let fe of this){var de;if(ee=!0,J!=null&&(de=J.signal)!==null&&de!==void 0&&de.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});_(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:$}}),Pa=pe((s,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Ue(),{isIterable:o,isNodeStream:n,isWebStream:i}=mt(),{pipelineImpl:a}=wo(),{finished:l}=Et();Ma();function c(...u){return new r((h,p)=>{let b,d,g=u[u.length-1];if(g&&typeof g=="object"&&!n(g)&&!o(g)&&!i(g)){let y=t(u);b=y.signal,d=y.end}a(u,(y,w)=>{y?p(y):h(w)},{signal:b,end:d})})}e.exports={finished:l,pipeline:c}}),Ma=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=(Fe(),Re($e)),{ObjectDefineProperty:r,ObjectKeys:o,ReflectApply:n}=Ue(),{promisify:{custom:i}}=Ye(),{streamReturningOperators:a,promiseReturningOperators:l}=tu(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ke(),u=Oa(),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:p}=Gr(),{pipeline:b}=wo(),{destroyer:d}=Yt(),g=Et(),y=Pa(),w=mt(),m=e.exports=yo().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=Yr();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=vo(),m.Duplex=ft(),m.Transform=Ta(),m.PassThrough=Ca(),m.pipeline=b;var{addAbortSignal:_}=Kr();m.addAbortSignal=_,m.finished=g,m.destroy=d,m.compose=u,m.setDefaultHighWaterMark=h,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(b,i,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(g,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)}}),Bt=pe((s,e)=>{le(),ue(),ce();var t=Ma(),r=Pa(),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}),ru=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}}}),nu=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),h=l-a,p=h,b=c&&i||0,d=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 g=0;g<this._bufs.length;g++)this._bufs[g].copy(n,b),b+=this._bufs[g].length;return n}if(p<=this._bufs[u[0]].length-d)return c?this._bufs[u[0]].copy(n,i,d,d+p):this._bufs[u[0]].slice(d,d+p);c||(n=t.allocUnsafe(h));for(let g=u[0];g<this._bufs.length;g++){let y=this._bufs[g].length-d;if(p>y)this._bufs[g].copy(n,b,d),b+=y;else{this._bufs[g].copy(n,b,d,d+p),b+=y;break}p-=y,d&&(d=0)}return n.length>b?n.slice(0,b):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 h=this._bufs[c];for(;u<h.length;)if(h.length-u>=n.length){let p=h.indexOf(n,u);if(p!==-1)return this._reverseOffset([c,p]);u=h.length-n.length+1}else{let p=this._reverseOffset([c,u]);if(this._match(p,n))return p;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}),iu=pe((s,e)=>{le(),ue(),ce();var t=Bt().Duplex,r=ru(),o=nu();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}),ou=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}),Ra=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"}}),su=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(p,b){b=b||{};var d=typeof p;if(d==="string"&&p.length>0)return l(p);if(d==="number"&&isFinite(p))return b.long?u(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function l(p){if(p=String(p),!(p.length>100)){var b=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(b){var d=parseFloat(b[1]),g=(b[2]||"ms").toLowerCase();switch(g){case"years":case"year":case"yrs":case"yr":case"y":return d*a;case"weeks":case"week":case"w":return d*i;case"days":case"day":case"d":return d*n;case"hours":case"hour":case"hrs":case"hr":case"h":return d*o;case"minutes":case"minute":case"mins":case"min":case"m":return d*r;case"seconds":case"second":case"secs":case"sec":case"s":return d*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return d;default:return}}}}function c(p){var b=Math.abs(p);return b>=n?Math.round(p/n)+"d":b>=o?Math.round(p/o)+"h":b>=r?Math.round(p/r)+"m":b>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var b=Math.abs(p);return b>=n?h(p,b,n,"day"):b>=o?h(p,b,o,"hour"):b>=r?h(p,b,r,"minute"):b>=t?h(p,b,t,"second"):p+" ms"}function h(p,b,d,g){var y=b>=d*1.5;return Math.round(p/d)+" "+g+(y?"s":"")}}),au=pe((s,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=h,n.disable=c,n.enable=a,n.enabled=u,n.humanize=su(),n.destroy=p,Object.keys(r).forEach(b=>{n[b]=r[b]}),n.names=[],n.skips=[],n.formatters={};function o(b){let d=0;for(let g=0;g<b.length;g++)d=(d<<5)-d+b.charCodeAt(g),d|=0;return n.colors[Math.abs(d)%n.colors.length]}n.selectColor=o;function n(b){let d,g=null,y,w;function m(..._){if(!m.enabled)return;let x=m,v=Number(new Date),E=v-(d||v);x.diff=E,x.prev=d,x.curr=v,d=v,_[0]=n.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let S=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(I,O)=>{if(I==="%%")return"%";S++;let P=n.formatters[O];if(typeof P=="function"){let j=_[S];I=P.call(x,j),_.splice(S,1),S--}return I}),n.formatArgs.call(x,_),(x.log||n.log).apply(x,_)}return m.namespace=b,m.useColors=n.useColors(),m.color=n.selectColor(b),m.extend=i,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(y!==n.namespaces&&(y=n.namespaces,w=n.enabled(b)),w),set:_=>{g=_}}),typeof n.init=="function"&&n.init(m),m}function i(b,d){let g=n(this.namespace+(typeof d>"u"?":":d)+b);return g.log=this.log,g}function a(b){n.save(b),n.namespaces=b,n.names=[],n.skips=[];let d=(typeof b=="string"?b:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let g of d)g[0]==="-"?n.skips.push(g.slice(1)):n.names.push(g)}function l(b,d){let g=0,y=0,w=-1,m=0;for(;g<b.length;)if(y<d.length&&(d[y]===b[g]||d[y]==="*"))d[y]==="*"?(w=y,m=g,y++):(g++,y++);else if(w!==-1)y=w+1,m++,g=m;else return!1;for(;y<d.length&&d[y]==="*";)y++;return y===d.length}function c(){let b=[...n.names,...n.skips.map(d=>"-"+d)].join(",");return n.enable(""),b}function u(b){for(let d of n.skips)if(l(b,d))return!1;for(let d of n.names)if(l(b,d))return!0;return!1}function h(b){return b instanceof Error?b.stack||b.message:b}function p(){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,h=0;l[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(h=u))}),l.splice(h,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=au()(s);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),lu=pe((s,e)=>{le(),ue(),ce();var t=iu(),{EventEmitter:r}=(jt(),Re(St)),o=ou(),n=Ra(),i=pt()("mqtt-packet:parser"),a=class ki extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof ki?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new ki().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 h=c&15,p=n.requiredHeaderFlags[u];return p!=null&&h!==p?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,h,p,b={},d=this.packet,g=this._parseString();if(g===null)return this._emitError(new Error("Cannot parse protocolId"));if(g!=="MQTT"&&g!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(d.protocolId=g,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(d.protocolVersion=this._list.readUInt8(this._pos),d.protocolVersion>=128&&(d.bridgeMode=!0,d.protocolVersion=d.protocolVersion-128),d.protocolVersion!==3&&d.protocolVersion!==4&&d.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"));b.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,b.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,b.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(b.will)d.will={},d.will.retain=y,d.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(d.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,d.keepalive=this._parseNum(),d.keepalive===-1)return this._emitError(new Error("Packet too short"));if(d.protocolVersion===5){let _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(d.properties=_)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(d.clientId=m,i("_parseConnect: packet.clientId: %s",d.clientId),b.will){if(d.protocolVersion===5){let _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(d.will.properties=_)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(d.will.topic=c,i("_parseConnect: packet.will.topic: %s",d.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));d.will.payload=u,i("_parseConnect: packet.will.paylaod: %s",d.will.payload)}if(b.username){if(p=this._parseString(),p===null)return this._emitError(new Error("Cannot parse username"));d.username=p,i("_parseConnect: packet.username: %s",d.username)}if(b.password){if(h=this._parseBuffer(),h===null)return this._emitError(new Error("Cannot parse password"));d.password=h}return this.settings=d,i("_parseConnect: complete"),d}_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 h=this._parseProperties();Object.getOwnPropertyNames(h).length&&(c.properties=h)}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,h,p,b,d,g,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(h=this._parseByte(),this.settings.protocolVersion===5){if(h&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(h&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=h&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(g=(h>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,d=(h>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,b=h>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,b>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));y={topic:u,qos:p},this.settings.protocolVersion===5?(y.nl=g,y.rap=d,y.rh=b):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 h=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[h])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(h)}}}_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(),h=u+this._pos;if(u===-1||h>this._list.length||h>this.packet.length)return null;let p=this._list.toString("utf8",this._pos,h);return this._pos+=u,i("_parseString: result: %s",p),p}_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 h=this._list.slice(this._pos,u);return this._pos+=c,i("_parseBuffer: result: %o",h),h}_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,h=0,p=1,b=0,d=!1,g,y=this._pos?this._pos:0;for(;h<u&&y+h<this._list.length;){if(g=this._list.readUInt8(y+h++),b+=p*(g&n.VARBYTEINT_MASK),p*=128,(g&n.VARBYTEINT_FIN_MASK)===0){d=!0;break}if(this._list.length<=h)break}return!d&&h===u&&this._list.length>=h&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=h),d?c?d={bytes:h,value:b}:d=b:d=!1,i("_parseVarByteNum: result: %o",d),d}_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,h={};for(;this._pos<u;){let p=this._parseByte();if(!p)return this._emitError(new Error("Cannot parse property code type")),!1;let b=n.propertiesCodes[p];if(!b)return this._emitError(new Error("Unknown property")),!1;if(b==="userProperties"){h[b]||(h[b]=Object.create(null));let d=this._parseByType(n.propertiesTypes[b]);if(h[b][d.name])if(Array.isArray(h[b][d.name]))h[b][d.name].push(d.value);else{let g=h[b][d.name];h[b][d.name]=[g],h[b][d.name].push(d.value)}else h[b][d.name]=d.value;continue}h[b]?Array.isArray(h[b])?h[b].push(this._parseByType(n.propertiesTypes[b])):(h[b]=[h[b]],h[b].push(this._parseByType(n.propertiesTypes[b]))):h[b]=this._parseByType(n.propertiesTypes[b])}return h}_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}),cu=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 h=t.allocUnsafe(2);return h.writeUInt8(u>>8,0),h.writeUInt8(u&255,1),h}function a(){for(let u=0;u<r;u++)o[u]=i(u)}function l(u){let h=0,p=0,b=t.allocUnsafe(4);do h=u%128|0,u=u/128|0,u>0&&(h=h|128),b.writeUInt8(h,p++);while(u>0&&p<4);return u>0&&(p=0),n?b.subarray(0,p):b.slice(0,p)}function c(u){let h=t.allocUnsafe(4);return h.writeUInt32BE(u,0),h}e.exports={cache:o,generateCache:a,generateNumber:i,genBufVariableByteInt:l,generate4ByteBuffer:c}}),uu=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)})}}}),La=pe((s,e)=>{le(),ue(),ce();var t=Ra(),{Buffer:r}=(Fe(),Re($e)),o=r.allocUnsafe(0),n=r.from([0]),i=cu(),a=uu().nextTick,l=pt()("mqtt-packet:writeToStream"),c=i.cache,u=i.generateNumber,h=i.generateCache,p=i.genBufVariableByteInt,b=i.generate4ByteBuffer,d=Y,g=!0;function y(K,N,ne){switch(l("generate called"),N.cork&&(N.cork(),a(w,N)),g&&(g=!1,h()),l("generate: packet.cmd: %s",K.cmd),K.cmd){case"connect":return m(K,N);case"connack":return _(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 O(K,N,ne);case"pingreq":case"pingresp":return P(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 d===Y},set(K){K?((!c||Object.keys(c).length===0)&&(g=!0),d=Y):(g=!1,d=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,de=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(de!=null){if(!ve)return N.destroy(new Error("Username is required to use password")),!1;if(we(de))ye+=te(de)+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|=de!=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])),d(N,R),J===5&&H.write(),$(N,F),ge&&(J===5&&me.write(),U(N,ge.topic),$(N,ge.payload)),ee!=null&&$(N,ee),de!=null&&$(N,de),!0}function _(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,de=0;if(typeof oe=="string")de+=r.byteLength(oe)+2;else if(r.isBuffer(oe))de+=oe.length+2;else return N.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?de+=R.length:de+=r.byteLength(R),J&&typeof F!="number")return N.destroy(new Error("Invalid messageId")),!1;J&&(de+=2);let fe=null;if(W===5){if(fe=Z(N,ee),!fe)return!1;de+=fe.length}return N.write(t.PUBLISH_HEADER[J][G.dup?1:0][ge?1:0]),D(N,de),d(N,te(oe)),N.write(oe),J>0&&d(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,de=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,de),!fe)return!1;de+=fe.length}return N.write(t.ACKS[J][R][oe][0]),de===3&&(de+=F!==0?1:-1),D(N,de),d(N,ge),W===5&&de!==2&&N.write(r.from([F])),fe!==null?fe.write():de===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),d(N,ge),ee!==null&&ee.write();let de=!0;for(let fe of oe){let ye=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,se=fe.rh,Oe;U(N,ye),Oe=t.SUBSCRIBE_OPTIONS_QOS[H],W===5&&(Oe|=me?t.SUBSCRIBE_OPTIONS_NL:0,Oe|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Oe|=se?t.SUBSCRIBE_OPTIONS_RH[se]:0),de=N.write(r.from([Oe]))}return de}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),d(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),d(N,J),ee!==null&&ee.write();let de=!0;for(let fe=0;fe<oe.length;fe++)de=U(N,oe[fe]);return de}function O(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,de=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;de+=1}else return N.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(W===5){if(fe=M(N,R,ne,de),!fe)return!1;de+=fe.length}return N.write(t.ACKS[F][ee][ge][0]),D(N,de),d(N,J),fe!==null&&fe.write(),W===5&&N.write(r.from(oe)),!0}function P(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=p(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 d(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=b(N);return l("write4ByteNumber: %o",ne),K.write(ne)}function $(K,N){typeof N=="string"?U(K,N):N?(d(K,N.length),K.write(N)):d(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(p(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((de,fe)=>(de+=3+r.byteLength(F.toString())+2+r.byteLength(fe.toString()),de),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(p(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]])),d(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}),hu=pe((s,e)=>{le(),ue(),ce();var t=La(),{EventEmitter:r}=(jt(),Re(St)),{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,h;for(h=0;h<c.length&&c[h]!==void 0;h++)typeof c[h]!="string"?l[h]=c[h].length:l[h]=o.byteLength(c[h]),a+=l[h];let p=o.allocUnsafe(a);for(h=0;h<c.length&&c[h]!==void 0;h++)typeof c[h]!="string"?(c[h].copy(p,u),u+=l[h]):(p.write(c[h],u),u+=l[h]);return p}destroy(a){a&&this.emit("error",a)}};e.exports=n}),du=pe(s=>{le(),ue(),ce(),s.parser=lu().parser,s.generate=hu(),s.writeToStream=La()}),fu=pe((s,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof Wr?Wr.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,h=>new Date(h)),i.set(Map,(h,p)=>new Map(l(Array.from(h),p))),i.set(Set,(h,p)=>new Set(l(Array.from(h),p))),n.constructorHandlers)for(let h of n.constructorHandlers)i.set(h[0],h[1]);let a=null;return n.proto?u:c;function l(h,p){let b=Object.keys(h),d=new Array(b.length);for(let g=0;g<b.length;g++){let y=b[g],w=h[y];typeof w!="object"||w===null?d[y]=w:w.constructor!==Object&&(a=i.get(w.constructor))?d[y]=a(w,p):ArrayBuffer.isView(w)?d[y]=t(w):d[y]=p(w)}return d}function c(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return l(h,c);if(h.constructor!==Object&&(a=i.get(h.constructor)))return a(h,c);let p={};for(let b in h){if(Object.hasOwnProperty.call(h,b)===!1)continue;let d=h[b];typeof d!="object"||d===null?p[b]=d:d.constructor!==Object&&(a=i.get(d.constructor))?p[b]=a(d,c):ArrayBuffer.isView(d)?p[b]=t(d):p[b]=c(d)}return p}function u(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return l(h,u);if(h.constructor!==Object&&(a=i.get(h.constructor)))return a(h,u);let p={};for(let b in h){let d=h[b];typeof d!="object"||d===null?p[b]=d:d.constructor!==Object&&(a=i.get(d.constructor))?p[b]=a(d,u):ArrayBuffer.isView(d)?p[b]=t(d):p[b]=u(d)}return p}}function o(n){let i=[],a=[],l=new Map;if(l.set(Date,b=>new Date(b)),l.set(Map,(b,d)=>new Map(u(Array.from(b),d))),l.set(Set,(b,d)=>new Set(u(Array.from(b),d))),n.constructorHandlers)for(let b of n.constructorHandlers)l.set(b[0],b[1]);let c=null;return n.proto?p:h;function u(b,d){let g=Object.keys(b),y=new Array(g.length);for(let w=0;w<g.length;w++){let m=g[w],_=b[m];if(typeof _!="object"||_===null)y[m]=_;else if(_.constructor!==Object&&(c=l.get(_.constructor)))y[m]=c(_,d);else if(ArrayBuffer.isView(_))y[m]=t(_);else{let x=i.indexOf(_);x!==-1?y[m]=a[x]:y[m]=d(_)}}return y}function h(b){if(typeof b!="object"||b===null)return b;if(Array.isArray(b))return u(b,h);if(b.constructor!==Object&&(c=l.get(b.constructor)))return c(b,h);let d={};i.push(b),a.push(d);for(let g in b){if(Object.hasOwnProperty.call(b,g)===!1)continue;let y=b[g];if(typeof y!="object"||y===null)d[g]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))d[g]=c(y,h);else if(ArrayBuffer.isView(y))d[g]=t(y);else{let w=i.indexOf(y);w!==-1?d[g]=a[w]:d[g]=h(y)}}return i.pop(),a.pop(),d}function p(b){if(typeof b!="object"||b===null)return b;if(Array.isArray(b))return u(b,p);if(b.constructor!==Object&&(c=l.get(b.constructor)))return c(b,p);let d={};i.push(b),a.push(d);for(let g in b){let y=b[g];if(typeof y!="object"||y===null)d[g]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))d[g]=c(y,p);else if(ArrayBuffer.isView(y))d[g]=t(y);else{let w=i.indexOf(y);w!==-1?d[g]=a[w]:d[g]=p(y)}}return i.pop(),a.pop(),d}}}),pu=pe((s,e)=>{le(),ue(),ce(),e.exports=fu()()}),Na=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}}),ja=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Bt(),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}),mu=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 h;if(o.properties&&(h=o.properties.topicAlias),typeof h<"u")if(i.length===0)if(h>0&&h<=65535){let p=r.topicAliasRecv.getTopicByAlias(h);if(p)i=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",i,h);else{r.log("handlePublish :: unregistered topic alias. alias: %d",h),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",h),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(i,h))r.log("handlePublish :: registered topic: %s - alias: %d",i,h);else{r.log("handlePublish :: topic alias out of range. alias: %d",h),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,(h,p)=>{if(typeof h=="number"&&(p=h,h=null),h)return r.emit("error",h);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:p},n):r.incomingStore.put(o,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(i,a,o,(h,p)=>{if(typeof h=="number"&&(p=h,h=null),h)return r.emit("error",h);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",i,a,o),r.handleMessage(o,b=>{if(b)return n&&n(b);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},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}),gu=pe((s,e)=>{e.exports={version:"5.15.0"}}),Jt=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 Ua extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,Ua.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};s.ErrorWithReasonCode=e;var t=class Ba extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,Ba.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=gu().version}),Jr=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=void 0;var e=Jt();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 h=0;h<u.length;h++){let p=u[h];if((p&128)!==0){c=new Error(`Subscribe error: ${s.ReasonCodes[p]}`),c.code=p;let b=r.messageIdToTopic[n];b&&b.forEach(d=>{delete r._resubscribeTopics[d]})}}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}),bu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Jt(),t=Jr(),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 h=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);o.emit("error",h)}})};s.default=r}),yu=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=(b,d,g,y)=>{typeof r.emitWarning=="function"?r.emitWarning(b,d,g,y):console.error(`[${g}] ${d}: ${b}`)},n=globalThis.AbortController,i=globalThis.AbortSignal;if(typeof n>"u"){i=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(g,y){this._onabort.push(y)}},n=class{constructor(){d()}signal=new i;abort(g){if(!this.signal.aborted){this.signal.reason=g,this.signal.aborted=!0;for(let y of this.signal._onabort)y(g);this.signal.onabort?.(g)}}};let b=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",d=()=>{b&&(b=!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",d))}}var a=b=>!t.has(b),l=b=>b&&b===Math.floor(b)&&b>0&&isFinite(b),c=b=>l(b)?b<=Math.pow(2,8)?Uint8Array:b<=Math.pow(2,16)?Uint16Array:b<=Math.pow(2,32)?Uint32Array:b<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(b){super(b),this.fill(0)}},h=class sr{heap;length;static#l=!1;static create(d){let g=c(d);if(!g)return[];sr.#l=!0;let y=new sr(d,g);return sr.#l=!1,y}constructor(d,g){if(!sr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new g(d),this.length=0}push(d){this.heap[this.length++]=d}pop(){return this.heap[--this.length]}},p=class Da{#l;#h;#m;#g;#O;#P;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#d;#a;#o;#y;#s;#v;#w;#f;#_;#A;#u;static unsafeExposeInternals(d){return{starts:d.#w,ttls:d.#f,sizes:d.#v,keyMap:d.#n,keyList:d.#r,valList:d.#e,next:d.#c,prev:d.#d,get head(){return d.#a},get tail(){return d.#o},free:d.#y,isBackgroundFetch:g=>d.#t(g),backgroundFetch:(g,y,w,m)=>d.#L(g,y,w,m),moveToTail:g=>d.#C(g),indexes:g=>d.#k(g),rindexes:g=>d.#x(g),isStale:g=>d.#p(g)}}get max(){return this.#l}get maxSize(){return this.#h}get calculatedSize(){return this.#b}get size(){return this.#i}get fetchMethod(){return this.#O}get memoMethod(){return this.#P}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(d){let{max:g=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:_,updateAgeOnHas:x,allowStale:v,dispose:E,disposeAfter:S,noDisposeOnSet:I,noUpdateTTL:O,maxSize:P=0,maxEntrySize:j=0,sizeCalculation:T,fetchMethod:q,memoMethod:D,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:V,ignoreFetchAbort:re}=d;if(g!==0&&!l(g))throw new TypeError("max option must be a nonnegative integer");let $=g?c(g):Array;if(!$)throw new Error("invalid max value: "+g);if(this.#l=g,this.#h=P,this.maxEntrySize=j||this.#h,this.sizeCalculation=T,this.sizeCalculation){if(!this.#h&&!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.#P=D,q!==void 0&&typeof q!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=q,this.#A=!!q,this.#n=new Map,this.#r=new Array(g).fill(void 0),this.#e=new Array(g).fill(void 0),this.#c=new $(g),this.#d=new $(g),this.#a=0,this.#o=0,this.#y=h.create(g),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.#_=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!O,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!V,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#h!==0&&!l(this.#h))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=!!_,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.#h===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#l&&!this.#h){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,Da))}}getRemainingTTL(d){return this.#n.has(d)?1/0:0}#N(){let d=new u(this.#l),g=new u(this.#l);this.#f=d,this.#w=g,this.#j=(m,_,x=e.now())=>{if(g[m]=_!==0?x:0,d[m]=_,_!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},_+1);v.unref&&v.unref()}},this.#I=m=>{g[m]=d[m]!==0?e.now():0},this.#E=(m,_)=>{if(d[_]){let x=d[_],v=g[_];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 _=setTimeout(()=>y=0,this.ttlResolution);_.unref&&_.unref()}return m};this.getRemainingTTL=m=>{let _=this.#n.get(m);if(_===void 0)return 0;let x=d[_],v=g[_];if(!x||!v)return 1/0;let E=(y||w())-v;return x-E},this.#p=m=>{let _=g[m],x=d[m];return!!x&&!!_&&(y||w())-_>x}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#F(){let d=new u(this.#l);this.#b=0,this.#v=d,this.#T=g=>{this.#b-=d[g],d[g]=0},this.#U=(g,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,g),!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=(g,y,w)=>{if(d[g]=y,this.#h){let m=this.#h-d[g];for(;this.#b>m;)this.#R(!0)}this.#b+=d[g],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=d=>{};#M=(d,g,y)=>{};#U=(d,g,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:d=this.allowStale}={}){if(this.#i)for(let g=this.#o;!(!this.#B(g)||((d||!this.#p(g))&&(yield g),g===this.#a));)g=this.#d[g]}*#x({allowStale:d=this.allowStale}={}){if(this.#i)for(let g=this.#a;!(!this.#B(g)||((d||!this.#p(g))&&(yield g),g===this.#o));)g=this.#c[g]}#B(d){return d!==void 0&&this.#n.get(this.#r[d])===d}*entries(){for(let d of this.#k())this.#e[d]!==void 0&&this.#r[d]!==void 0&&!this.#t(this.#e[d])&&(yield[this.#r[d],this.#e[d]])}*rentries(){for(let d of this.#x())this.#e[d]!==void 0&&this.#r[d]!==void 0&&!this.#t(this.#e[d])&&(yield[this.#r[d],this.#e[d]])}*keys(){for(let d of this.#k()){let g=this.#r[d];g!==void 0&&!this.#t(this.#e[d])&&(yield g)}}*rkeys(){for(let d of this.#x()){let g=this.#r[d];g!==void 0&&!this.#t(this.#e[d])&&(yield g)}}*values(){for(let d of this.#k())this.#e[d]!==void 0&&!this.#t(this.#e[d])&&(yield this.#e[d])}*rvalues(){for(let d of this.#x())this.#e[d]!==void 0&&!this.#t(this.#e[d])&&(yield this.#e[d])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(d,g={}){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&d(m,this.#r[y],this))return this.get(this.#r[y],g)}}forEach(d,g=this){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&d.call(g,m,this.#r[y],this)}}rforEach(d,g=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&d.call(g,m,this.#r[y],this)}}purgeStale(){let d=!1;for(let g of this.#x({allowStale:!0}))this.#p(g)&&(this.#S(this.#r[g],"expire"),d=!0);return d}info(d){let g=this.#n.get(d);if(g===void 0)return;let y=this.#e[g],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let _=this.#f[g],x=this.#w[g];if(_&&x){let v=_-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[g]),m}dump(){let d=[];for(let g of this.#k({allowStale:!0})){let y=this.#r[g],w=this.#e[g],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||y===void 0)continue;let _={value:m};if(this.#f&&this.#w){_.ttl=this.#f[g];let x=e.now()-this.#w[g];_.start=Math.floor(Date.now()-x)}this.#v&&(_.size=this.#v[g]),d.unshift([y,_])}return d}load(d){this.clear();for(let[g,y]of d){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(g,y.value,y)}}set(d,g,y={}){if(g===void 0)return this.delete(d),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:_=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=y,{noUpdateTTL:E=this.noUpdateTTL}=y,S=this.#U(d,g,y.size||0,x);if(this.maxEntrySize&&S>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(d,"set"),this;let I=this.#i===0?void 0:this.#n.get(d);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]=d,this.#e[I]=g,this.#n.set(d,I),this.#c[this.#o]=I,this.#d[I]=this.#o,this.#o=I,this.#i++,this.#M(I,S,v),v&&(v.set="add"),E=!1;else{this.#C(I);let O=this.#e[I];if(g!==O){if(this.#A&&this.#t(O)){O.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:P}=O;P!==void 0&&!_&&(this.#_&&this.#m?.(P,d,"set"),this.#u&&this.#s?.push([P,d,"set"]))}else _||(this.#_&&this.#m?.(O,d,"set"),this.#u&&this.#s?.push([O,d,"set"]));if(this.#T(I),this.#M(I,S,v),this.#e[I]=g,v){v.set="replace";let P=O&&this.#t(O)?O.__staleWhileFetching:O;P!==void 0&&(v.oldValue=P)}}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)),!_&&this.#u&&this.#s){let O=this.#s,P;for(;P=O?.shift();)this.#g?.(...P)}return this}pop(){try{for(;this.#i;){let d=this.#e[this.#a];if(this.#R(!0),this.#t(d)){if(d.__staleWhileFetching)return d.__staleWhileFetching}else if(d!==void 0)return d}}finally{if(this.#u&&this.#s){let d=this.#s,g;for(;g=d?.shift();)this.#g?.(...g)}}}#R(d){let g=this.#a,y=this.#r[g],w=this.#e[g];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(g),d&&(this.#r[g]=void 0,this.#e[g]=void 0,this.#y.push(g)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[g],this.#n.delete(y),this.#i--,g}has(d,g={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=g,m=this.#n.get(d);if(m!==void 0){let _=this.#e[m];if(this.#t(_)&&_.__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(d,g={}){let{allowStale:y=this.allowStale}=g,w=this.#n.get(d);if(w===void 0||!y&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#L(d,g,y,w){let m=g===void 0?void 0:this.#e[g];if(this.#t(m))return m;let _=new n,{signal:x}=y;x?.addEventListener("abort",()=>_.abort(x.reason),{signal:_.signal});let v={signal:_.signal,options:y,context:w},E=(T,q=!1)=>{let{aborted:D}=_.signal,U=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(D&&!q?(y.status.fetchAborted=!0,y.status.fetchError=_.signal.reason,U&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),D&&!U&&!q)return I(_.signal.reason);let ae=P;return this.#e[g]===P&&(T===void 0?ae.__staleWhileFetching?this.#e[g]=ae.__staleWhileFetching:this.#S(d,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(d,T,v.options))),T},S=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:q}=_.signal,D=q&&y.allowStaleOnFetchAbort,U=D||y.allowStaleOnFetchRejection,ae=U||y.noDeleteOnFetchRejection,Y=P;if(this.#e[g]===P&&(!ae||Y.__staleWhileFetching===void 0?this.#S(d,"fetch"):D||(this.#e[g]=Y.__staleWhileFetching)),U)return y.status&&Y.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},O=(T,q)=>{let D=this.#O?.(d,m,v);D&&D instanceof Promise&&D.then(U=>T(U===void 0?void 0:U),q),_.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=U=>E(U,!0)))})};y.status&&(y.status.fetchDispatched=!0);let P=new Promise(O).then(E,S),j=Object.assign(P,{__abortController:_,__staleWhileFetching:m,__returned:void 0});return g===void 0?(this.set(d,j,{...v.options,status:void 0}),g=this.#n.get(d)):this.#e[g]=j,j}#t(d){if(!this.#A)return!1;let g=d;return!!g&&g instanceof Promise&&g.hasOwnProperty("__staleWhileFetching")&&g.__abortController instanceof n}async fetch(d,g={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:_=this.ttl,noDisposeOnSet:x=this.noDisposeOnSet,size:v=0,sizeCalculation:E=this.sizeCalculation,noUpdateTTL:S=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:O=this.allowStaleOnFetchRejection,ignoreFetchAbort:P=this.ignoreFetchAbort,allowStaleOnFetchAbort:j=this.allowStaleOnFetchAbort,context:T,forceRefresh:q=!1,status:D,signal:U}=g;if(!this.#A)return D&&(D.fetch="get"),this.get(d,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:D});let ae={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:_,noDisposeOnSet:x,size:v,sizeCalculation:E,noUpdateTTL:S,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:O,allowStaleOnFetchAbort:j,ignoreFetchAbort:P,status:D,signal:U},Y=this.#n.get(d);if(Y===void 0){D&&(D.fetch="miss");let V=this.#L(d,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(d,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(d,g={}){let y=await this.fetch(d,g);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(d,g={}){let y=this.#P;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,..._}=g,x=this.get(d,_);if(!m&&x!==void 0)return x;let v=y(d,x,{options:_,context:w});return this.set(d,v,_),v}get(d,g={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:_}=g,x=this.#n.get(d);if(x!==void 0){let v=this.#e[x],E=this.#t(v);return _&&this.#E(_,x),this.#p(x)?(_&&(_.get="stale"),E?(_&&y&&v.__staleWhileFetching!==void 0&&(_.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(d,"expire"),_&&y&&(_.returnedStale=!0),y?v:void 0)):(_&&(_.get="hit"),E?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else _&&(_.get="miss")}#D(d,g){this.#d[g]=d,this.#c[d]=g}#C(d){d!==this.#o&&(d===this.#a?this.#a=this.#c[d]:this.#D(this.#d[d],this.#c[d]),this.#D(this.#o,d),this.#o=d)}delete(d){return this.#S(d,"delete")}#S(d,g){let y=!1;if(this.#i!==0){let w=this.#n.get(d);if(w!==void 0)if(y=!0,this.#i===1)this.#$(g);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(m,d,g),this.#u&&this.#s?.push([m,d,g])),this.#n.delete(d),this.#r[w]=void 0,this.#e[w]=void 0,w===this.#o)this.#o=this.#d[w];else if(w===this.#a)this.#a=this.#c[w];else{let _=this.#d[w];this.#c[_]=this.#c[w];let x=this.#c[w];this.#d[x]=this.#d[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")}#$(d){for(let g of this.#x({allowStale:!0})){let y=this.#e[g];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let w=this.#r[g];this.#_&&this.#m?.(y,w,d),this.#u&&this.#s?.push([y,w,d])}}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 g=this.#s,y;for(;y=g?.shift();)this.#g?.(...y)}}};s.LRUCache=p}),gt=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}),vu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=gt(),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}),wu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=gt(),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}),_u=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=gt(),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}),_o=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=gt(),t=class extends e.Container{},r=t;s.default=r}),bt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),$a=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.RandomIterator=void 0;var e=gt(),t=bt(),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}),ku=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=r(_o()),t=$a();function r(a){return a&&a.t?a:{default:a}}var o=class Fa extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Fa(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}),xu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(_o()),t=gt(),r=bt();function o(l){return l&&l.t?l:{default:l}}var n=class qa extends t.ContainerIterator{constructor(c,u,h,p){super(p),this.o=c,this.h=u,this.container=h,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 qa(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,h={l,L:c,B:u};c.B=h,u.L=h,c===this.h&&(this.p=h),u===this.h&&(this._=h),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 h=this.p;for(let b=1;b<l;++b)h=h.B;let p=h.B;for(this.i+=u;u--;)h.B={l:c,L:h},h.B.L=h,h=h.B;h.B=p,p.L=h}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 h=l.l;l.l=c.l,c.l=h,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(h){c.push(h)}),c.sort(l);let u=this.p;c.forEach(function(h){u.l=h,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(h){for(;u!==c.h&&u.l<=h;)u=u.B;c.G(h,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}),Su=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=r(_o()),t=$a();function r(a){return a&&a.t?a:{default:a}}var o=class Ha extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Ha(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 p=0;p<this.P;++p)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 h=this;a.forEach(function(p){h.pushBack(p)})}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,h=this.j+(l-c)/this.F;return c===0&&(h-=1),h%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:h,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 h=a;h<this.i;++h)u.push(this.getElementByPos(h));this.cut(a-1);for(let h=0;h<c;++h)this.pushBack(l);for(let h=0;h<u.length;++h)this.pushBack(u[h])}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 h=this.getElementByPos(u);h!==a&&l.push(h)}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}),Eu=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}),Wa=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=Eu(),t=gt(),r=bt(),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 h=this.ne(l,c,u);if(h){let p=h.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let b=this.he(h);if(b){let{parentNode:d,grandParent:g,curNode:y}=b;d.ie(),g.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 h=this.ne(l,c,u);return h&&this.he(h),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,h=this.v(u.u,i);if(h===0){u.l=a;return}else if(h>0)u.U=new this.re(i,a),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,b=this.v(p.u,i);if(b===0){p.l=a;return}else if(b<0)p.W=new this.re(i,a),p.W.tt=p,c=p.W,this.h.W=c;else{if(l!==void 0){let d=l.o;if(d!==this.h){let g=this.v(d.u,i);if(g===0){d.l=a;return}else if(g>0){let y=d.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):(d.U=c,c.tt=d))}}}if(c===void 0)for(c=this.Y;;){let d=this.v(c.u,i);if(d>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(d<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}),za=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=gt(),t=bt(),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}),Au=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(Wa()),t=o(za()),r=bt();function o(l){return l&&l.t?l:{default:l}}var n=class Va extends t.default{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new Va(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(l=[],c,u){super(c,u);let h=this;l.forEach(function(p){h.insert(p)})}*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}),Iu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(Wa()),t=o(za()),r=bt();function o(l){return l&&l.t?l:{default:l}}var n=class Ka extends t.default{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,h){if(h==="0")return c.o.u;if(h==="1")return c.o.l},set(u,h,p){if(h!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new Ka(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(l=[],c,u){super(c,u);let h=this;l.forEach(function(p){h.setElement(p[0],p[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}),Ga=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"}}),Ya=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.HashContainerIterator=s.HashContainer=void 0;var e=gt(),t=o(Ga()),r=bt();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 h=a[this.HASH_TAG];if(h!==void 0)return this.H[h].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 h=this.g[a];if(h)return h.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}),Tu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=Ya(),t=bt(),r=class Ja 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 Ja(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}),Cu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=Ya(),t=o(Ga()),r=bt();function o(l){return l&&l.t?l:{default:l}}var n=class Qa extends e.HashContainerIterator{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,h){if(h==="0")return c.o.u;if(h==="1")return c.o.l},set(u,h,p){if(h!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new Qa(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 h=l[this.HASH_TAG];return h!==void 0?this.H[h].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}),Ou=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=h(vu()),t=h(wu()),r=h(_u()),o=h(ku()),n=h(xu()),i=h(Su()),a=h(Au()),l=h(Iu()),c=h(Tu()),u=h(Cu());function h(p){return p&&p.t?p:{default:p}}}),Pu=pe((s,e)=>{le(),ue(),ce();var t=Ou().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,h=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,h)),r("use():"+a),!0):h===a?(this.ss.updateKeyByIterator(c,new n(u,h-1)),r("use():"+a),!0):(this.ss.updateKeyByIterator(c,new n(a+1,h)),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,h=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,h))):this.ss.updateKeyByIterator(c,new n(p,a)):a+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(a,h))):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}),Xa=pe((s,e)=>{le(),ue(),ce();var t=Pu();e.exports.NumberAllocator=t}),Mu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=yu(),t=Xa(),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}),Ru=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=Jr(),r=e(Mu()),o=Jt(),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}),Lu=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}),Nu=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(mu()),r=e(bu()),o=e(Ru()),n=e(Jr()),i=e(Lu()),a=(l,c,u)=>{let{options:h}=l;if(h.protocolVersion===5&&h.properties&&h.properties.maximumPacketSize&&h.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}),Za=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}),ju=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}),Uu=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((jt(),Re(St))),r=Jt(),o=class{};s.TypedEventEmitter=o,(0,r.applyMixin)(o,t.default)}),Qr=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}),Bu=pe((s,e)=>{le(),ue(),ce();var t=Qr().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}),Du=pe((s,e)=>{le(),ue(),ce();var t=Qr().default,r=Bu();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}),$u=pe((s,e)=>{le(),ue(),ce();var t=Du();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}),Fu=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}),qu=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=[],h=!0,p=!1;try{if(l=(n=n.call(r)).next,o===0){if(Object(n)!==n)return;h=!1}else for(;!(h=(i=l.call(n)).done)&&(u.push(i.value),u.length!==o);h=!0);}catch(b){p=!0,a=b}finally{try{if(!h&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Hu=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}),Wu=pe((s,e)=>{le(),ue(),ce();var t=Hu();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}),zu=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}),Vu=pe((s,e)=>{le(),ue(),ce();var t=Fu(),r=qu(),o=Wu(),n=zu();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}),el=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(b){return function(d){var g=b(d);return d.add(g),g}},o=function(b){return function(d,g){return b.set(d,g),g}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,a=i*2,l=function(b,d){return function(g){var y=d.get(g),w=y===void 0?g.size:y<a?y+1:0;if(!g.has(w))return b(g,w);if(g.size<i){for(;g.has(w);)w=Math.floor(Math.random()*a);return b(g,w)}if(g.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;g.has(w);)w=Math.floor(Math.random()*n);return b(g,w)}},c=new WeakMap,u=o(c),h=l(u,c),p=r(h);t.addUniqueNumber=p,t.generateUniqueNumber=h})}),Ku=pe((s,e)=>{le(),ue(),ce();function t(o,n,i,a,l,c,u){try{var h=o[c](u),p=h.value}catch(b){return void i(b)}h.done?n(p):Promise.resolve(p).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(p){t(c,a,l,u,h,"next",p)}function h(p){t(c,a,l,u,h,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),tl=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}),rl=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,h){function p(b,d){t(l,b,function(g){return this._invoke(b,d,g)})}c?a?a(l,c,{value:u,enumerable:!h,configurable:!h,writable:!h}):l[c]=u:(p("next",0),p("throw",1),p("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}),nl=pe((s,e)=>{le(),ue(),ce();var t=rl();function r(){var o,n,i=typeof Symbol=="function"?Symbol:{},a=i.iterator||"@@iterator",l=i.toStringTag||"@@toStringTag";function c(w,m,_,x){var v=m&&m.prototype instanceof h?m:h,E=Object.create(v.prototype);return t(E,"_invoke",(function(S,I,O){var P,j,T,q=0,D=O||[],U=!1,ae={p:0,n:0,v:o,a:Y,f:Y.bind(o,4),d:function(V,re){return P=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;){P||(j?j<3?(j>1&&(ae.n=-1),Y(j,T)):ae.n=T:ae.v=T);try{if(q=2,P){if(j||(V="next"),n=P[V]){if(!(n=n.call(P,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=P.return)&&n.call(P),j<2&&(T=TypeError("The iterator does not provide a '"+V+"' method"),j=1);P=o}else if((n=(U=ae.n<0)?T:S.call(I,ae))!==u)break}catch(Z){P=o,j=1,T=Z}finally{q=1}}return{value:n,done:U}}})(w,_,x),!0),E}var u={};function h(){}function p(){}function b(){}n=Object.getPrototypeOf;var d=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),g=b.prototype=h.prototype=Object.create(d);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,b):(w.__proto__=b,t(w,l,"GeneratorFunction")),w.prototype=Object.create(g),w}return p.prototype=b,t(g,"constructor",b),t(b,"constructor",p),p.displayName="GeneratorFunction",t(b,l,"GeneratorFunction"),t(g),t(g,l,"Generator"),t(g,a,function(){return this}),t(g,"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}),il=pe((s,e)=>{le(),ue(),ce();var t=tl(),r=rl();function o(n,i){function a(c,u,h,p){try{var b=n[c](u),d=b.value;return d instanceof t?i.resolve(d.v).then(function(g){a("next",g,h,p)},function(g){a("throw",g,h,p)}):i.resolve(d).then(function(g){b.value=g,h(b)},function(g){return a("throw",g,h,p)})}catch(g){p(g)}}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,h){function p(){return new i(function(b,d){a(c,h,b,d)})}return l=l?l.then(p,p):p()},!0)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),ol=pe((s,e)=>{le(),ue(),ce();var t=nl(),r=il();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}),Gu=pe((s,e)=>{le(),ue(),ce();var t=ol();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}),Yu=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}),Ju=pe((s,e)=>{le(),ue(),ce();var t=Qr().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}),Qu=pe((s,e)=>{le(),ue(),ce();var t=tl(),r=nl(),o=Gu(),n=ol(),i=il(),a=Yu(),l=Ju();function c(){var u=r(),h=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(h):h.__proto__).constructor;function b(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var d={throw:1,return:2,break:3,continue:3};function g(y){var w,m;return function(_){w||(w={stop:function(){return m(_.a,2)},catch:function(){return _.v},abrupt:function(x,v){return m(_.a,d[x],v)},delegateYield:function(x,v,E){return w.resultName=v,m(_.d,l(x),E)},finish:function(x){return m(_.f,x)}},m=function(x,v,E){_.p=w.prev,_.n=w.next;try{return x(v,E)}finally{w.next=_.n}}),w.resultName&&(w[w.resultName]=_.v,w.resultName=void 0),w.sent=_.v,w.next=_.n;try{return y.call(this,w)}finally{_.p=w.prev,_.n=w.next}}}return(e.exports=c=function(){return{wrap:function(y,w,m,_){return u.w(g(y),w,m,_&&_.reverse())},isGeneratorFunction:b,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:i,async:function(y,w,m,_,x){return(b(w)?n:o)(g(y),w,m,_,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}),Xu=pe((s,e)=>{le(),ue(),ce();var t=Qu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),Zu=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,$u(),Vu(),el(),Ku(),Xu()):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,_){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);_&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function h(m){for(var _=1;_<arguments.length;_++){var x=arguments[_]!=null?arguments[_]:{};_%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 p=function(m){return h(h({},m),{},{connect:function(_){var x=_.call;return i(a.mark(function v(){var E,S,I,O;return a.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:return E=new MessageChannel,S=E.port1,I=E.port2,P.next=1,x("connect",{port:S},[S]);case 1:return O=P.sent,c.set(I,O),P.abrupt("return",I);case 2:case"end":return P.stop()}},v)}))},disconnect:function(_){var x=_.call;return(function(){var v=i(a.mark(function E(S){var I;return a.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:if(I=c.get(S),I!==void 0){O.next=1;break}throw new Error("The given port is not connected.");case 1:return O.next=2,x("disconnect",{portId:I});case 2:case"end":return O.stop()}},E)}));return function(E){return v.apply(this,arguments)}})()},isSupported:function(_){var x=_.call;return function(){return x("isSupported")}}})};function b(m,_){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);_&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function d(m){for(var _=1;_<arguments.length;_++){var x=arguments[_]!=null?arguments[_]:{};_%2?b(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):b(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var g=new WeakMap,y=function(m){if(g.has(m))return g.get(m);var _=new Map;return g.set(m,_),_},w=function(m){var _=p(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={},O=0,P=Object.entries(_);O<P.length;O++){var j=o(P[O],2),T=j[0],q=j[1];I=d(d({},I),{},r({},T,q({call:E,notify:S})))}return d({},I)}};t.createBroker=w})}),eh=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,Qr(),Zu(),el()):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 h=u.call;return function(p){r(i.get(p))==="symbol"&&(i.set(p,null),h("clear",{timerId:p,timerType:"interval"}).then(function(){i.delete(p)}))}},clearTimeout:function(u){var h=u.call;return function(p){r(a.get(p))==="symbol"&&(a.set(p,null),h("clear",{timerId:p,timerType:"timeout"}).then(function(){a.delete(p)}))}},setInterval:function(u){var h=u.call;return function(p){for(var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,d=arguments.length,g=new Array(d>2?d-2:0),y=2;y<d;y++)g[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(i);i.set(m,w);var _=function(){return h("set",{delay:b,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&&(p.apply(void 0,g),i.get(m)===w&&_())})};return _(),m}},setTimeout:function(u){var h=u.call;return function(p){for(var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,d=arguments.length,g=new Array(d>2?d-2:0),y=2;y<d;y++)g[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(a);return a.set(m,w),h("set",{delay:b,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var _=a.get(m);if(_===void 0)throw new Error("The timer is in an undefined state.");_===w&&(a.delete(m),p.apply(void 0,g))}),m}}}),c=function(u){var h=new Worker(u);return l(h)};t.load=c,t.wrap=l})}),th=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,eh()):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(h,p){var b=null;return function(){if(b!==null)return b;var d=new Blob([p],{type:"application/javascript; charset=utf-8"}),g=URL.createObjectURL(d);return b=h(g),setTimeout(function(){return URL.revokeObjectURL(g)}),b}},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(h){return i().clearInterval(h)},l=function(h){return i().clearTimeout(h)},c=function(){var h;return(h=i()).setInterval.apply(h,arguments)},u=function(){var h;return(h=i()).setTimeout.apply(h,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Xr=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}),rh=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(c,u,h,p){p===void 0&&(p=h);var b=Object.getOwnPropertyDescriptor(u,h);(!b||("get"in b?!u.__esModule:b.writable||b.configurable))&&(b={enumerable:!0,get:function(){return u[h]}}),Object.defineProperty(c,p,b)}:function(c,u,h,p){p===void 0&&(p=h),c[p]=u[h]}),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(h){var p=[];for(var b in h)Object.prototype.hasOwnProperty.call(h,b)&&(p[p.length]=b);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var h={};if(u!=null)for(var p=c(u),b=0;b<p.length;b++)p[b]!=="default"&&e(h,u,p[b]);return t(h,u),h}})();Object.defineProperty(s,"__esModule",{value:!0});var o=th(),n=r(Xr()),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}),sl=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(rh()),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}),xi=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(v,E,S,I){I===void 0&&(I=S);var O=Object.getOwnPropertyDescriptor(E,S);(!O||("get"in O?!E.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return E[S]}}),Object.defineProperty(v,I,O)}: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 O in S)Object.prototype.hasOwnProperty.call(S,O)&&(I[I.length]=O);return I},v(E)};return function(E){if(E&&E.__esModule)return E;var S={};if(E!=null)for(var I=v(E),O=0;O<I.length;O++)I[O]!=="default"&&e(S,E,I[O]);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(du()),i=Bt(),a=o(pu()),l=o(pt()),c=r(Na()),u=o(ja()),h=o(Nu()),p=o(Za()),b=o(ju()),d=Jt(),g=Uu(),y=o(sl()),w=r(Xr()),m=globalThis.setImmediate||((...v)=>{let E=v.shift();(0,d.nextTick)(()=>{E(...v)})}),_={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 Si extends g.TypedEventEmitter{static VERSION=d.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 _)typeof this.options[I]>"u"?this.options[I]=_[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:",Si.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:Si.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 p.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 b.default(S.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,O=()=>{let P=I.shift();this.log("deliver :: entry %o",P);let j=null;if(!P){this._resubscribe();return}j=P.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=>{P.cb&&P.cb(q),O()}):(this.log("messageId: %d has already used. The message is skipped and removed.",j.messageId),O())};this.log("connect :: sending queued packets"),O()}),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,O=[];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."),O.push(D)});let P=()=>{this.log("work :: getting next packet in queue");let D=O.shift();if(D)this.log("work :: packet pulled from queue"),(0,h.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(O.length)(0,d.nextTick)(P);else{let D=I;I=null,D()}};E._write=(D,U,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),S.parse(D),P()};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,O){this.log("publish :: message `%s` to topic `%s`",S,E);let{options:P}=this;typeof I=="function"&&(O=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(O))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(P.protocolVersion===5&&(V.properties=D),this.log("publish :: qos",j),j){case 1:case 2:this.outgoing[V.messageId]={volatile:!1,cb:O||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,O,U);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!ae())&&this._storeProcessingQueue.push({invoke:ae,cbStorePut:I.cbStorePut,callback:O}),this}publishAsync(E,S,I){return new Promise((O,P)=>{this.publish(E,S,I,(j,T)=>{j?P(j):O(T)})})}subscribe(E,S,I){let O=this.options.protocolVersion;typeof S=="function"&&(I=S),I=I||this.noop;let P=!1,j=[];typeof E=="string"?(E=[E],j=E):Array.isArray(E)?j=E:typeof E=="object"&&(P=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};O===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||P){let Z={topic:re,qos:$.qos};O===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};O===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 d.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,O)=>{this.subscribe(E,S,(P,j)=>{P?O(P):I(j)})})}unsubscribe(E,S,I){typeof E=="string"&&(E=[E]),typeof S=="function"&&(I=S),I=I||this.noop;let O=c.validateTopics(E);if(O!==null)return m(I,new Error(`Invalid topic ${O}`)),this;if(this._checkDisconnecting(I))return this;let P=()=>{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||!P())&&this._storeProcessingQueue.push({invoke:P,callback:I}),this}unsubscribeAsync(E,S){return new Promise((I,O)=>{this.unsubscribe(E,S,(P,j)=>{P?O(P):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 O=()=>{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)},P=()=>{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,d.nextTick)(O)},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,P,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),P()),this)}endAsync(E,S){return new Promise((I,O)=>{this.end(E,S,P=>{P?O(P):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 O={cmd:"disconnect",...I};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(O,()=>{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 O=E,P;if(O.cmd==="publish"&&(O=(0,a.default)(E),P=this._removeTopicAliasAndRecoverTopicName(O),P))return S&&S(P);this.outgoingStore.put(O,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,O){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,S=S||this.noop;let P=this._applyTopicAlias(E);if(P){S(P);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(O){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 O=E;if(O.cmd==="publish"){O=(0,a.default)(E);let j=this._removeTopicAliasAndRecoverTopicName(O);if(j)return S&&S(j)}let P=O.qos||0;P===0&&this.queueQoSZero||O.cmd!=="publish"?this.queue.push({packet:O,cb:S}):P>0?(S=this.outgoing[O.messageId]?this.outgoing[O.messageId].cb:null,this.outgoingStore.put(O,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(),O=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),P()},P=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",O),I.on("error",T=>{P(),this._flushStoreProcessingQueue(),this.removeListener("close",O),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",O),T?(P(),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,O)=>{S(I,O),this.messageIdProvider.deallocate(E),this._invokeStoreProcessingQueue()})}};s.default=x}),nh=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Xa(),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 ih(){if(Ei)return wr;Ei=!0;let s=2147483647,e=36,t=1,r=26,o=38,n=700,i=72,a=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,h=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},b=e-t,d=Math.floor,g=String.fromCharCode;function y(P){throw new RangeError(p[P])}function w(P,j){let T=[],q=P.length;for(;q--;)T[q]=j(P[q]);return T}function m(P,j){let T=P.split("@"),q="";T.length>1&&(q=T[0]+"@",P=T[1]),P=P.replace(h,".");let D=P.split("."),U=w(D,j).join(".");return q+U}function _(P){let j=[],T=0,q=P.length;for(;T<q;){let D=P.charCodeAt(T++);if(D>=55296&&D<=56319&&T<q){let U=P.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=P=>String.fromCodePoint(...P),v=function(P){return P>=48&&P<58?26+(P-48):P>=65&&P<91?P-65:P>=97&&P<123?P-97:e},E=function(P,j){return P+22+75*(P<26)-((j!=0)<<5)},S=function(P,j,T){let q=0;for(P=T?d(P/n):P>>1,P+=d(P/j);P>b*r>>1;q+=e)P=d(P/b);return d(q+(b+1)*P/(P+o))},I=function(P){let j=[],T=P.length,q=0,D=a,U=i,ae=P.lastIndexOf(l);ae<0&&(ae=0);for(let Y=0;Y<ae;++Y)P.charCodeAt(Y)>=128&&y("not-basic"),j.push(P.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(P.charCodeAt(Y++));M>=e&&y("invalid-input"),M>d((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;$>d(s/be)&&y("overflow"),$*=be}let re=j.length+1;U=S(q-V,re,V==0),d(q/re)>s-D&&y("overflow"),D+=d(q/re),q%=re,j.splice(q++,0,D)}return String.fromCodePoint(...j)},O=function(P){let j=[];P=_(P);let T=P.length,q=a,D=0,U=i;for(let V of P)V<128&&j.push(g(V));let ae=j.length,Y=ae;for(ae&&j.push(l);Y<T;){let V=s;for(let $ of P)$>=q&&$<V&&(V=$);let re=Y+1;V-q>d((s-D)/re)&&y("overflow"),D+=(V-q)*re,q=V;for(let $ of P)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(g(E(Q+be%te,0))),Z=d(be/te)}j.push(g(E(Z,0))),U=S(D,re,Y===ae),D=0,++Y}++D,++q}return j.join("")};return wr={version:"2.3.1",ucs2:{decode:_,encode:x},decode:I,encode:O,toASCII:function(P){return m(P,function(j){return u.test(j)?"xn--"+O(j):j})},toUnicode:function(P){return m(P,function(j){return c.test(j)?I(j.slice(4).toLowerCase()):j})}},wr}var wr,Ei,kt,oh=Je(()=>{le(),ue(),ce(),wr={},Ei=!1,kt=ih(),kt.decode,kt.encode,kt.toASCII,kt.toUnicode,kt.ucs2,kt.version});function sh(){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 ah(){return Ci||(Ci=!0,Ti=Error),Ti}function lh(){return Pi||(Pi=!0,Oi=EvalError),Oi}function ch(){return Ri||(Ri=!0,Mi=RangeError),Mi}function uh(){return Ni||(Ni=!0,Li=ReferenceError),Li}function al(){return Ui||(Ui=!0,ji=SyntaxError),ji}function hr(){return Di||(Di=!0,Bi=TypeError),Bi}function hh(){return Fi||(Fi=!0,$i=URIError),$i}function dh(){if(qi)return _r;qi=!0;var s=typeof Symbol<"u"&&Symbol,e=sh();return _r=function(){return typeof s!="function"||typeof Symbol!="function"||typeof s("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},_r}function fh(){if(Hi)return kr;Hi=!0;var s={__proto__:null,foo:{}},e=Object;return kr=function(){return{__proto__:s}.foo===s.foo&&!(s instanceof e)},kr}function ph(){if(Wi)return xr;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 h=0;h<l.length;h+=1)c[h+a.length]=l[h];return c},n=function(a,l){for(var c=[],u=l,h=0;u<a.length;u+=1,h+=1)c[h]=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 xr=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,h=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))},p=t(0,l.length-c.length),b=[],d=0;d<p;d++)b[d]="$"+d;if(u=Function("binder","return function ("+i(b,",")+"){ return binder.apply(this,arguments); }")(h),l.prototype){var g=function(){};g.prototype=l.prototype,u.prototype=new g,g.prototype=null}return u},xr}function ko(){if(zi)return Sr;zi=!0;var s=ph();return Sr=Function.prototype.bind||s,Sr}function mh(){if(Vi)return Er;Vi=!0;var s=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=ko();return Er=t.call(s,e),Er}function Qt(){if(Ki)return Ar;Ki=!0;var s,e=ah(),t=lh(),r=ch(),o=uh(),n=al(),i=hr(),a=hh(),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 h=function(){throw new i},p=u?(function(){try{return arguments.callee,h}catch{try{return u(arguments,"callee").get}catch{return h}}})():h,b=dh()(),d=fh()(),g=Object.getPrototypeOf||(d?function(Y){return Y.__proto__}:null),y={},w=typeof Uint8Array>"u"||!g?s:g(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?s:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?s:ArrayBuffer,"%ArrayIteratorPrototype%":b&&g?g([][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%":b&&g?g(g([][Symbol.iterator]())):s,"%JSON%":typeof JSON=="object"?JSON:s,"%Map%":typeof Map>"u"?s:Map,"%MapIteratorPrototype%":typeof Map>"u"||!b||!g?s:g(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"||!b||!g?s:g(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?s:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":b&&g?g(""[Symbol.iterator]()):s,"%Symbol%":b?Symbol:s,"%SyntaxError%":n,"%ThrowTypeError%":p,"%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(g)try{null.error}catch(Y){var _=g(g(Y));m["%Error.prototype%"]=_}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&&g&&(re=g(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=ko(),S=mh(),I=E.call(Function.call,Array.prototype.concat),O=E.call(Function.apply,Array.prototype.splice),P=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 P(Y,q,function(Z,M,Q,be){$[$.length]=Q?P(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 Ar=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],O(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},Ar}function xo(){if(Gi)return Ir;Gi=!0;var s=Qt(),e=s("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Ir=e,Ir}function ll(){if(Yi)return Tr;Yi=!0;var s=Qt(),e=s("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Tr=e,Tr}function gh(){if(Ji)return Cr;Ji=!0;var s=xo(),e=al(),t=hr(),r=ll();return Cr=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,h=!!r&&r(o,n);if(s)s(o,n,{configurable:c===null&&h?h.configurable:!c,enumerable:a===null&&h?h.enumerable:!a,value:i,writable:l===null&&h?h.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.")},Cr}function bh(){if(Qi)return Or;Qi=!0;var s=xo(),e=function(){return!!s};return e.hasArrayLengthDefineBug=function(){if(!s)return null;try{return s([],"length",{value:1}).length!==1}catch{return!0}},Or=e,Or}function yh(){if(Xi)return Pr;Xi=!0;var s=Qt(),e=gh(),t=bh()(),r=ll(),o=hr(),n=s("%Math.floor%");return Pr=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 h=r(i,"length");h&&!h.configurable&&(c=!1),h&&!h.writable&&(u=!1)}return(c||u||!l)&&(t?e(i,"length",a,!0,!0):e(i,"length",a)),i},Pr}function vh(){if(Zi)return Wt;Zi=!0;var s=ko(),e=Qt(),t=yh(),r=hr(),o=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||s.call(n,o),a=xo(),l=e("%Math.max%");Wt=function(u){if(typeof u!="function")throw new r("a function is required");var h=i(s,n,arguments);return t(h,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 wh(){if(eo)return Mr;eo=!0;var s=Qt(),e=vh(),t=e(s("String.prototype.indexOf"));return Mr=function(r,o){var n=s(r,!!o);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Mr}var Ai,Ii,Ti,Ci,Oi,Pi,Mi,Ri,Li,Ni,ji,Ui,Bi,Di,$i,Fi,_r,qi,kr,Hi,xr,Wi,Sr,zi,Er,Vi,Ar,Ki,Ir,Gi,Tr,Yi,Cr,Ji,Or,Qi,Pr,Xi,Wt,Zi,Mr,eo,_h=Je(()=>{le(),ue(),ce(),Ai={},Ii=!1,Ti={},Ci=!1,Oi={},Pi=!1,Mi={},Ri=!1,Li={},Ni=!1,ji={},Ui=!1,Bi={},Di=!1,$i={},Fi=!1,_r={},qi=!1,kr={},Hi=!1,xr={},Wi=!1,Sr={},zi=!1,Er={},Vi=!1,Ar={},Ki=!1,Ir={},Gi=!1,Tr={},Yi=!1,Cr={},Ji=!1,Or={},Qi=!1,Pr={},Xi=!1,Wt={},Zi=!1,Mr={},eo=!1});function So(s){throw new Error("Node.js process "+s+" is not supported by JSPM core outside of Node.js")}function kh(){!Lt||!Mt||(Lt=!1,Mt.length?at=Mt.concat(at):lr=-1,at.length&&cl())}function cl(){if(!Lt){var s=setTimeout(kh,0);Lt=!0;for(var e=at.length;e;){for(Mt=at,at=[];++lr<e;)Mt&&Mt[lr].run();lr=-1,e=at.length}Mt=null,Lt=!1,clearTimeout(s)}}function xh(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];at.push(new ul(s,e)),at.length===1&&!Lt&&setTimeout(cl,0)}function ul(s,e){this.fun=s,this.array=e}function We(){}function Sh(s){So("_linkedBinding")}function Eh(s){So("dlopen")}function Ah(){return[]}function Ih(){return[]}function Th(s,e){if(!s)throw new Error(e||"assertion error")}function Ch(){return!1}function Oh(){return dt.now()/1e3}function rn(s){var e=Math.floor((Date.now()-dt.now())*.001),t=dt.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+=Rr)),[r,o]}function vt(){return Eo}function Ph(s){return[]}var at,Lt,Mt,lr,Bo,Do,$o,Fo,qo,Ho,Wo,zo,Vo,Ko,Go,Yo,Jo,Qo,Xo,Zo,es,ts,rs,ns,is,pr,os,ss,as,ls,cs,us,hs,ds,fs,ps,ms,gs,bs,ys,vs,ws,_s,ks,xs,Ss,Es,As,Is,Ts,Cs,dt,nn,Rr,Os,Ps,Ms,Rs,Ls,Ns,js,Us,Bs,Ds,$s,Eo,hl=Je(()=>{le(),ue(),ce(),at=[],Lt=!1,lr=-1,ul.prototype.run=function(){this.fun.apply(null,this.array)},Bo="browser",Do="x64",$o="browser",Fo={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},qo=["/usr/bin/node"],Ho=[],Wo="v16.8.0",zo={},Vo=function(s,e){console.warn((e?e+": ":"")+s)},Ko=function(s){So("binding")},Go=function(s){return 0},Yo=function(){return"/"},Jo=function(s){},Qo={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Xo=We,Zo=[],es={},ts=!1,rs={},ns=We,is=We,pr=function(){return{}},os=pr,ss=pr,as=We,ls=We,cs=We,us={},hs={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},ds=We,fs=We,ps=We,ms=We,gs=We,bs=We,ys=We,vs=void 0,ws=void 0,_s=void 0,ks=We,xs=2,Ss=1,Es="/bin/usr/node",As=9229,Is="node",Ts=[],Cs=We,dt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},dt.now===void 0&&(nn=Date.now(),dt.timing&&dt.timing.navigationStart&&(nn=dt.timing.navigationStart),dt.now=()=>Date.now()-nn),Rr=1e9,rn.bigint=function(s){var e=rn(s);return typeof BigInt>"u"?e[0]*Rr+e[1]:BigInt(e[0]*Rr)+BigInt(e[1])},Os=10,Ps={},Ms=0,Rs=vt,Ls=vt,Ns=vt,js=vt,Us=vt,Bs=We,Ds=vt,$s=vt,Eo={version:Wo,versions:zo,arch:Do,platform:$o,release:Qo,_rawDebug:Xo,moduleLoadList:Zo,binding:Ko,_linkedBinding:Sh,_events:Ps,_eventsCount:Ms,_maxListeners:Os,on:vt,addListener:Rs,once:Ls,off:Ns,removeListener:js,removeAllListeners:Us,emit:Bs,prependListener:Ds,prependOnceListener:$s,listeners:Ph,domain:es,_exiting:ts,config:rs,dlopen:Eh,uptime:Oh,_getActiveRequests:Ah,_getActiveHandles:Ih,reallyExit:ns,_kill:is,cpuUsage:pr,resourceUsage:os,memoryUsage:ss,kill:as,exit:ls,openStdin:cs,allowedNodeEnvironmentFlags:us,assert:Th,features:hs,_fatalExceptions:ds,setUncaughtExceptionCaptureCallback:fs,hasUncaughtExceptionCaptureCallback:Ch,emitWarning:Vo,nextTick:xh,_tickCallback:ps,_debugProcess:ms,_debugEnd:gs,_startProfilerIdleNotifier:bs,_stopProfilerIdleNotifier:ys,stdout:vs,stdin:_s,stderr:ws,abort:ks,umask:Go,chdir:Jo,cwd:Yo,env:Fo,title:Bo,argv:qo,execArgv:Ho,pid:xs,ppid:Ss,execPath:Es,debugPort:As,hrtime:rn,argv0:Is,_preload_modules:Ts,setSourceMapsEnabled:Cs}});function Mh(){if(to)return Lr;to=!0;var s=Eo;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,h,p=0;p<=n.length;++p){if(p<n.length)h=n.charCodeAt(p);else{if(h===47)break;h=47}if(h===47){if(!(c===p-1||u===1))if(c!==p-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 b=a.lastIndexOf("/");if(b!==a.length-1){b===-1?(a="",l=0):(a=a.slice(0,b),l=a.length-1-a.lastIndexOf("/")),c=p,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=p,u=0;continue}}i&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,p):a=n.slice(c+1,p),l=p-c-1;c=p,u=0}else h===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 h=i.length,p=h-u,b=c<p?c:p,d=-1,g=0;g<=b;++g){if(g===b){if(p>b){if(i.charCodeAt(u+g)===47)return i.slice(u+g+1);if(g===0)return i.slice(u+g)}else c>b&&(n.charCodeAt(a+g)===47?d=g:g===0&&(d=0));break}var y=n.charCodeAt(a+g),w=i.charCodeAt(u+g);if(y!==w)break;y===47&&(d=g)}var m="";for(g=a+d+1;g<=l;++g)(g===l||n.charCodeAt(g)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+i.slice(u+d):(u+=d,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 h=i.length-1,p=-1;for(u=n.length-1;u>=0;--u){var b=n.charCodeAt(u);if(b===47){if(!c){a=u+1;break}}else p===-1&&(c=!1,p=u+1),h>=0&&(b===i.charCodeAt(h)?--h===-1&&(l=u):(h=-1,l=p))}return a===l?l=p: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,h=n.length-1;h>=0;--h){var p=n.charCodeAt(h);if(p===47){if(!c){a=h+1;break}continue}l===-1&&(c=!1,l=h+1),p===46?i===-1?i=h: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,h=0,p=-1,b=!0,d=n.length-1,g=0;d>=c;--d){if(a=n.charCodeAt(d),a===47){if(!b){h=d+1;break}continue}p===-1&&(b=!1,p=d+1),a===46?u===-1?u=d:g!==1&&(g=1):u!==-1&&(g=-1)}return u===-1||p===-1||g===0||g===1&&u===p-1&&u===h+1?p!==-1&&(h===0&&l?i.base=i.name=n.slice(1,p):i.base=i.name=n.slice(h,p)):(h===0&&l?(i.name=n.slice(1,u),i.base=n.slice(1,p)):(i.name=n.slice(h,u),i.base=n.slice(h,p)),i.ext=n.slice(u,p)),h>0?i.dir=n.slice(0,h-1):l&&(i.dir="/"),i},sep:"/",delimiter:":",win32:null,posix:null};return o.posix=o,Lr=o,Lr}var Lr,to,ro,Rh=Je(()=>{le(),ue(),ce(),hl(),Lr={},to=!1,ro=Mh()}),dl={};Gt(dl,{URL:()=>kl,Url:()=>bl,default:()=>ze,fileURLToPath:()=>pl,format:()=>yl,parse:()=>_l,pathToFileURL:()=>ml,resolve:()=>vl,resolveObject:()=>wl});function Lh(){if(no)return Nr;no=!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,h=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,b=p?WeakRef.prototype.deref:null,d=Boolean.prototype.valueOf,g=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,_=String.prototype.replace,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,E=RegExp.prototype.test,S=Array.prototype.concat,I=Array.prototype.join,O=Array.prototype.slice,P=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 Ae=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof z=="number"){var Ie=z<0?-P(-z):P(z);if(Ie!==z){var Ce=String(Ie),Pe=m.call(ie,Ce.length+1);return _.call(Ce,Ae,"$&_")+"."+_.call(_.call(Pe,/([0-9]{3})/g,"$&_"),/_$/,"")}}return _.call(ie,Ae,"$&_")}var re=gl,$=re.custom,Z=G($)?$:null;Nr=function z(ie,Ae,Ie,Ce){var Pe=Ae||{};if(oe(Pe,"quoteStyle")&&Pe.quoteStyle!=="single"&&Pe.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oe(Pe,"maxStringLength")&&(typeof Pe.maxStringLength=="number"?Pe.maxStringLength<0&&Pe.maxStringLength!==1/0:Pe.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var et=oe(Pe,"customInspect")?Pe.customInspect:!0;if(typeof et!="boolean"&&et!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oe(Pe,"indent")&&Pe.indent!==null&&Pe.indent!==" "&&!(parseInt(Pe.indent,10)===Pe.indent&&Pe.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oe(Pe,"numericSeparator")&&typeof Pe.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var tt=Pe.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,Pe);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var qe=String(ie);return tt?V(ie,qe):qe}if(typeof ie=="bigint"){var rt=String(ie)+"n";return tt?V(ie,rt):rt}var $t=typeof Pe.depth>"u"?5:Pe.depth;if(typeof Ie>"u"&&(Ie=0),Ie>=$t&&$t>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var nt=X(Pe,Ie);if(typeof Ce>"u")Ce=[];else if(ee(Ce,ie)>=0)return"[Circular]";function Qe(it,yt,Tt){if(yt&&(Ce=O.call(Ce),Ce.push(yt)),Tt){var ot={depth:Pe.depth};return oe(Pe,"quoteStyle")&&(ot.quoteStyle=Pe.quoteStyle),z(it,ot,Ie+1,Ce)}return z(it,Pe,Ie+1,Ce)}if(typeof ie=="function"&&!we(ie)){var dr=F(ie),Ft=ke(ie,Qe);return"[Function"+(dr?": "+dr:" (anonymous)")+"]"+(Ft.length>0?" { "+I.call(Ft,", ")+" }":"")}if(G(ie)){var Xt=D?_.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):q.call(ie);return typeof ie=="object"&&!D?f(Xt):Xt}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),L=ie.attributes||[],_e=0;_e<L.length;_e++)C+=" "+L[_e].name+"="+M(Q(L[_e].value),"double",Pe);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=ke(ie,Qe);return nt&&!B(xe)?"["+he(xe,nt)+"]":"[ "+I.call(xe,", ")+" ]"}if(K(ie)){var Se=ke(ie,Qe);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(S.call("[cause]: "+Qe(ie.cause),Se),", ")+" }":Se.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Se,", ")+" }"}if(typeof ie=="object"&&et){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:$t-Ie});if(et!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(de(ie)){var Be=[];return r&&r.call(ie,function(it,yt){Be.push(Qe(yt,ie,!0)+" => "+Qe(it,ie))}),A("Map",t.call(ie),Be,nt)}if(H(ie)){var Ve=[];return a&&a.call(ie,function(it){Ve.push(Qe(it,ie))}),A("Set",i.call(ie),Ve,nt)}if(fe(ie))return k("WeakMap");if(me(ie))return k("WeakSet");if(ye(ie))return k("WeakRef");if(ne(ie))return f(Qe(Number(ie)));if(J(ie))return f(Qe(j.call(ie)));if(W(ie))return f(d.call(ie));if(N(ie))return f(Qe(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof jr<"u"&&ie===jr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var Ze=ke(ie,Qe),Zt=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,er=ie instanceof Object?"":"null prototype",tr=!Zt&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):er?"Object":"",fr=Zt||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",It=fr+(tr||er?"["+I.call(S.call([],tr||[],er||[]),": ")+"] ":"");return Ze.length===0?It+"{}":nt?It+"{"+he(Ze,nt)+"}":It+"{ "+I.call(Ze,", ")+" }"}return String(ie)};function M(z,ie,Ae){var Ie=(Ae.quoteStyle||ie)==="double"?'"':"'";return Ie+z+Ie}function Q(z){return _.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||jr)};function oe(z,ie){return ge.call(z,ie)}function R(z){return g.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 Ae=0,Ie=z.length;Ae<Ie;Ae++)if(z[Ae]===ie)return Ae;return-1}function de(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{h.call(z,h)}catch{return!0}return z instanceof WeakMap}catch{}return!1}function ye(z){if(!b||!z||typeof z!="object")return!1;try{return b.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(!h||!z||typeof z!="object")return!1;try{h.call(z,h);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 Ae=z.length-ie.maxStringLength,Ie="... "+Ae+" more character"+(Ae>1?"s":"");return se(m.call(z,0,ie.maxStringLength),ie)+Ie}var Ce=_.call(_.call(z,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Oe);return M(Ce,"single",ie)}function Oe(z){var ie=z.charCodeAt(0),Ae={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ae?"\\"+Ae:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function f(z){return"Object("+z+")"}function k(z){return z+" { ? }"}function A(z,ie,Ae,Ie){var Ce=Ie?he(Ae,Ie):I.call(Ae,", ");return z+" ("+ie+") {"+Ce+"}"}function B(z){for(var ie=0;ie<z.length;ie++)if(ee(z[ie],`
|
|
4
|
-
`)>=0)return!1;return!0}function X(
|
|
5
|
-
`+ie.prev+ie.base;return Ae+
|
|
6
|
-
`+ie.prev}function ke(z,ie){var Ae=be(z),Ie=[];if(Ae){Ie.length=z.length;for(var Ce=0;Ce<z.length;Ce++)Ie[Ce]=oe(z,Ce)?ie(z[Ce],z):""}var Pe=typeof T=="function"?T(z):[],et;if(D){et={};for(var tt=0;tt<Pe.length;tt++)et["$"+Pe[tt]]=Pe[tt]}for(var qe in z)oe(z,qe)&&(Ae&&String(Number(qe))===qe&&qe<z.length||D&&et["$"+qe]instanceof Symbol||(E.call(/[^\w$]/,qe)?Ie.push(ie(qe,z)+": "+ie(z[qe],z)):Ie.push(qe+": "+ie(z[qe],z))));if(typeof T=="function")for(var rt=0;rt<Pe.length;rt++)ae.call(z,Pe[rt])&&Ie.push("["+ie(Pe[rt])+"]: "+ie(z[Pe[rt]],z));return Ie}return Nr}function Nh(){if(io)return Ur;io=!0;var s=Qt(),e=wh(),t=Lh(),r=hr(),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),h=e("Map.prototype.has",!0),p=function(y,w){for(var m=y,_;(_=m.next)!==null;m=_)if(_.key===w)return m.next=_.next,_.next=y.next,y.next=_,_},b=function(y,w){var m=p(y,w);return m&&m.value},d=function(y,w,m){var _=p(y,w);_?_.value=m:y.next={key:w,next:y.next,value:m}},g=function(y,w){return!!p(y,w)};return Ur=function(){var y,w,m,_={assert:function(x){if(!_.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 b(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 h(w,x)}else if(m)return g(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}),d(m,x,v))}};return _},Ur}function Ao(){if(oo)return Br;oo=!0;var s=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Br={default:t.RFC3986,formatters:{RFC1738:function(r){return s.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Br}function fl(){if(so)return Dr;so=!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 _=[],x=0;x<m.length;++x)typeof m[x]<"u"&&_.push(m[x]);w.obj[w.prop]=_}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},_=0;_<y.length;++_)typeof y[_]<"u"&&(m[_]=y[_]);return m},i=function y(w,m,_){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(_&&(_.plainObjects||_.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,_)),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,_):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,_):v[E]=S,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,_){return m[_]=w[_],m},y)},l=function(y,w,m){var _=y.replace(/\+/g," ");if(m==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},c=1024,u=function(y,w,m,_,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,O=[],P=0;P<I.length;++P){var j=I.charCodeAt(P);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)){O[O.length]=I.charAt(P);continue}if(j<128){O[O.length]=r[j];continue}if(j<2048){O[O.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){O[O.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}P+=1,j=65536+((j&1023)<<10|I.charCodeAt(P)&1023),O[O.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}E+=O.join("")}return E},h=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],_=0;_<w.length;++_)for(var x=w[_],v=x.obj[x.prop],E=Object.keys(v),S=0;S<E.length;++S){var I=E[S],O=v[I];typeof O=="object"&&O!==null&&m.indexOf(O)===-1&&(w.push({obj:v,prop:I}),m.push(O))}return o(w),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},b=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},d=function(y,w){return[].concat(y,w)},g=function(y,w){if(t(y)){for(var m=[],_=0;_<y.length;_+=1)m.push(w(y[_]));return m}return w(y)};return Dr={arrayToObject:n,assign:a,combine:d,compact:h,decode:l,encode:u,isBuffer:b,isRegExp:p,maybeMap:g,merge:i},Dr}function jh(){if(ao)return $r;ao=!0;var s=Nh(),e=fl(),t=Ao(),r=Object.prototype.hasOwnProperty,o={brackets:function(g){return g+"[]"},comma:"comma",indices:function(g,y){return g+"["+y+"]"},repeat:function(g){return g}},n=Array.isArray,i=Array.prototype.push,a=function(g,y){i.apply(g,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(g){return l.call(g)},skipNulls:!1,strictNullHandling:!1},h=function(g){return typeof g=="string"||typeof g=="number"||typeof g=="boolean"||typeof g=="symbol"||typeof g=="bigint"},p={},b=function g(y,w,m,_,x,v,E,S,I,O,P,j,T,q,D,U,ae,Y){for(var V=y,re=Y,$=0,Z=!1;(re=re.get(p))!==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(p)>"u"&&($=0)}if(typeof O=="function"?V=O(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(h(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(O))te=O;else{var we=Object.keys(V);te=P?we.sort(P):we}var K=S?w.replace(/\./g,"%2E"):w,N=_&&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(p,Y),a(be,g(G,ge,m,_,x,v,E,S,m==="comma"&&U&&n(V)?null:I,O,P,j,T,q,D,U,ae,oe))}}return be},d=function(g){if(!g)return u;if(typeof g.allowEmptyArrays<"u"&&typeof g.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof g.encodeDotInKeys<"u"&&typeof g.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(g.encoder!==null&&typeof g.encoder<"u"&&typeof g.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=g.charset||u.charset;if(typeof g.charset<"u"&&g.charset!=="utf-8"&&g.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 g.format<"u"){if(!r.call(t.formatters,g.format))throw new TypeError("Unknown format option provided.");w=g.format}var m=t.formatters[w],_=u.filter;(typeof g.filter=="function"||n(g.filter))&&(_=g.filter);var x;if(g.arrayFormat in o?x=g.arrayFormat:"indices"in g?x=g.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in g&&typeof g.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof g.allowDots>"u"?g.encodeDotInKeys===!0?!0:u.allowDots:!!g.allowDots;return{addQueryPrefix:typeof g.addQueryPrefix=="boolean"?g.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof g.allowEmptyArrays=="boolean"?!!g.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof g.charsetSentinel=="boolean"?g.charsetSentinel:u.charsetSentinel,commaRoundTrip:g.commaRoundTrip,delimiter:typeof g.delimiter>"u"?u.delimiter:g.delimiter,encode:typeof g.encode=="boolean"?g.encode:u.encode,encodeDotInKeys:typeof g.encodeDotInKeys=="boolean"?g.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof g.encoder=="function"?g.encoder:u.encoder,encodeValuesOnly:typeof g.encodeValuesOnly=="boolean"?g.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:w,formatter:m,serializeDate:typeof g.serializeDate=="function"?g.serializeDate:u.serializeDate,skipNulls:typeof g.skipNulls=="boolean"?g.skipNulls:u.skipNulls,sort:typeof g.sort=="function"?g.sort:null,strictNullHandling:typeof g.strictNullHandling=="boolean"?g.strictNullHandling:u.strictNullHandling}};return $r=function(g,y){var w=g,m=d(y),_,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,_=x);var v=[];if(typeof w!="object"||w===null)return"";var E=o[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;_||(_=Object.keys(w)),m.sort&&_.sort(m.sort);for(var I=s(),O=0;O<_.length;++O){var P=_[O];m.skipNulls&&w[P]===null||a(v,b(w[P],P,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:""},$r}function Uh(){if(lo)return Fr;lo=!0;var s=fl(),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(p){return p.replace(/&#(\d+);/g,function(b,d){return String.fromCharCode(parseInt(d,10))})},n=function(p,b){return p&&typeof p=="string"&&b.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,b){var d={__proto__:null},g=b.ignoreQueryPrefix?p.replace(/^\?/,""):p;g=g.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=b.parameterLimit===1/0?void 0:b.parameterLimit,w=g.split(b.delimiter,y),m=-1,_,x=b.charset;if(b.charsetSentinel)for(_=0;_<w.length;++_)w[_].indexOf("utf8=")===0&&(w[_]===a?x="utf-8":w[_]===i&&(x="iso-8859-1"),m=_,_=w.length);for(_=0;_<w.length;++_)if(_!==m){var v=w[_],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,O;S===-1?(I=b.decoder(v,r.decoder,x,"key"),O=b.strictNullHandling?null:""):(I=b.decoder(v.slice(0,S),r.decoder,x,"key"),O=s.maybeMap(n(v.slice(S+1),b),function(j){return b.decoder(j,r.decoder,x,"value")})),O&&b.interpretNumericEntities&&x==="iso-8859-1"&&(O=o(O)),v.indexOf("[]=")>-1&&(O=t(O)?[O]:O);var P=e.call(d,I);P&&b.duplicates==="combine"?d[I]=s.combine(d[I],O):(!P||b.duplicates==="last")&&(d[I]=O)}return d},c=function(p,b,d,g){for(var y=g?b:n(b,d),w=p.length-1;w>=0;--w){var m,_=p[w];if(_==="[]"&&d.parseArrays)m=d.allowEmptyArrays&&(y===""||d.strictNullHandling&&y===null)?[]:[].concat(y);else{m=d.plainObjects?Object.create(null):{};var x=_.charAt(0)==="["&&_.charAt(_.length-1)==="]"?_.slice(1,-1):_,v=d.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!d.parseArrays&&v===""?m={0:y}:!isNaN(E)&&_!==v&&String(E)===v&&E>=0&&d.parseArrays&&E<=d.arrayLimit?(m=[],m[E]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,b,d,g){if(p){var y=d.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,_=d.depth>0&&w.exec(y),x=_?y.slice(0,_.index):y,v=[];if(x){if(!d.plainObjects&&e.call(Object.prototype,x)&&!d.allowPrototypes)return;v.push(x)}for(var E=0;d.depth>0&&(_=m.exec(y))!==null&&E<d.depth;){if(E+=1,!d.plainObjects&&e.call(Object.prototype,_[1].slice(1,-1))&&!d.allowPrototypes)return;v.push(_[1])}if(_){if(d.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+d.depth+" and strictDepth is true");v.push("["+y.slice(_.index)+"]")}return c(v,b,d,g)}},h=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var b=typeof p.charset>"u"?r.charset:p.charset,d=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(d!=="combine"&&d!=="first"&&d!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var g=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:g,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:b,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||s.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:d,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:r.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:r.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:r.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:r.strictNullHandling}};return Fr=function(p,b){var d=h(b);if(p===""||p===null||typeof p>"u")return d.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?l(p,d):p,y=d.plainObjects?Object.create(null):{},w=Object.keys(g),m=0;m<w.length;++m){var _=w[m],x=u(_,g[_],d,typeof p=="string");y=s.merge(y,x,d)}return d.allowSparse===!0?y:s.compact(y)},Fr}function Bh(){if(co)return qr;co=!0;var s=jh(),e=Uh(),t=Ao();return qr={formats:t,parse:e,stringify:s},qr}function Dh(){if(uo)return xt;uo=!0;var s=kt;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,
|
|
8
|
-
`)&&(e=e.replace(Ol,"%0A")),e.includes("\r")&&(e=e.replace(Pl,"%0D")),e.includes(" ")&&(e=e.replace(Ml,"%09")),r.pathname=e,r}var gl,Nr,no,jr,Ur,io,Br,oo,Dr,so,$r,ao,Fr,lo,qr,co,xt,uo,ze,Fs,bl,yl,vl,wl,_l,kl,xl,Sl,El,Al,zr,Il,Tl,Cl,Ol,Pl,Ml,qh=Je(()=>{le(),ue(),ce(),oh(),_h(),Rh(),hl(),gl=Object.freeze(Object.create(null)),Nr={},no=!1,jr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Ur={},io=!1,Br={},oo=!1,Dr={},so=!1,$r={},ao=!1,Fr={},lo=!1,qr={},co=!1,xt={},uo=!1,ze=Dh(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Fs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=ml,ze.fileURLToPath=pl,bl=ze.Url,yl=ze.format,vl=ze.resolve,wl=ze.resolveObject,_l=ze.parse,kl=ze.URL,xl=92,Sl=47,El=97,Al=122,zr=Fs==="win32",Il=/\//g,Tl=/%/g,Cl=/\\/g,Ol=/\n/g,Pl=/\r/g,Ml=/\t/g}),Hh=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")}}),Io=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=Bt(),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}),mr=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(Hh()),o=e(pt()),n=Bt(),i=e(Xr()),a=Io(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let _=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(_=w.transformWsUrl(_,w,m)),_}function h(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(_=>{Object.prototype.hasOwnProperty.call(w,_)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,_)&&(m.wsOptions[_]=w[_])}),m}function p(w){let m=h(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 _=new URL(document.URL);m.hostname=_.hostname,m.port||(m.port=Number(_.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function b(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function d(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var g=(w,m)=>{l("streamBuilder");let _=h(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=b(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=g;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=d(w,m),I=P(m,U,ae);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{S.close()});let O=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=I,_.socket=S):(_=new a.BufferedDuplex(m,I,S),O?S.addEventListener("open",j):S.onopen=j),O?(S.addEventListener("close",T),S.addEventListener("error",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function P(Y,V,re){let $=new n.Transform({objectMode:Y.objectMode});return $._write=V,$._flush=re,$}function j(){l("WebSocket onOpen"),_ instanceof a.BufferedDuplex&&_.socketReady()}function T(Y){l("WebSocket onClose",Y),_.end(),_.destroy()}function q(Y){l("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,_.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 _};s.browserStreamBuilder=y}),To={};Gt(To,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>Rl,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 Rl,Ll=Je(()=>{le(),ue(),ce(),Rl={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),Nl=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),qs=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((Ll(),Re(To))),r=e(pt()),o=e(Nl()),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,h=l.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};s.default=i}),jl={};Gt(jl,{default:()=>Ul});var Ul,Wh=Je(()=>{le(),ue(),ce(),Ul={}}),Hs=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=(Wh(),Re(jl)),r=e((Ll(),Re(To))),o=e(pt()),n=e(Nl()),i=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:h,socksProxy:p,...b}=c;if(p!==void 0){let d=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...b,socket:d})}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 h=a(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(b){u.rejectUnauthorized&&c.emit("error",b),h.end()}return h.on("error",p),h};s.default=l}),Ws=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(Fe(),Re($e)),t=Bt(),r=Io(),o,n,i;function a(){let p=new t.Transform;return p._write=(b,d,g)=>{o.send({data:b.buffer,success(){g()},fail(y){g(new Error(y))}})},p._flush=b=>{o.close({success(){b()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,b){let d=p.protocol==="wxs"?"wss":"ws",g=`${d}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${d}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,b)),g}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(p=>{let{data:b}=p;b instanceof ArrayBuffer?b=e.Buffer.from(b):b=e.Buffer.from(b,"utf8"),n.push(b)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(p=>{let b=new Error(p.errMsg);i.destroy(b)})}var h=(p,b)=>{if(b.hostname=b.hostname||b.host,!b.hostname)throw new Error("Could not determine host. Specify host manually.");let d=b.protocolId==="MQIsdp"&&b.protocolVersion===3?"mqttv3.1":"mqtt";l(b);let g=c(b,p);o=wx.connectSocket({url:g,protocols:[d]}),n=a(),i=new r.BufferedDuplex(b,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=h}),zs=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(Fe(),Re($e)),t=Bt(),r=Io(),o,n,i,a=!1;function l(){let b=new t.Transform;return b._write=(d,g,y)=>{o.sendSocketMessage({data:d.buffer,success(){y()},fail(){y(new Error)}})},b._flush=d=>{o.closeSocket({success(){d()}})},b}function c(b){b.hostname||(b.hostname="localhost"),b.path||(b.path="/"),b.wsOptions||(b.wsOptions={})}function u(b,d){let g=b.protocol==="alis"?"wss":"ws",y=`${g}://${b.hostname}${b.path}`;return b.port&&b.port!==80&&b.port!==443&&(y=`${g}://${b.hostname}:${b.port}${b.path}`),typeof b.transformWsUrl=="function"&&(y=b.transformWsUrl(y,b,d)),y}function h(){a||(a=!0,o.onSocketOpen(()=>{i.socketReady()}),o.onSocketMessage(b=>{if(typeof b.data=="string"){let d=e.Buffer.from(b.data,"base64");n.push(d)}else{let d=new FileReader;d.addEventListener("load",()=>{if(d.result instanceof ArrayBuffer){n.push(e.Buffer.from(d.result));return}n.push(e.Buffer.from(d.result,"utf-8"))}),d.readAsArrayBuffer(b.data)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(b=>{i.destroy(b)}))}var p=(b,d)=>{if(d.hostname=d.hostname||d.host,!d.hostname)throw new Error("Could not determine host. Specify host manually.");let g=d.protocolId==="MQIsdp"&&d.protocolVersion===3?"mqttv3.1":"mqtt";c(d);let y=u(d,b);return o=d.my,o.connectSocket({url:y,protocols:g}),n=l(),i=new r.BufferedDuplex(d,n,o),h(),i};s.default=p}),zh=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(s,"__esModule",{value:!0}),s.connectAsync=u;var t=e(pt()),r=e((qh(),Re(dl))),o=e(xi()),n=e(Xr());typeof Ne?.nextTick!="function"&&(Ne.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),a=null;function l(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,b,d]=p;h.username=b,h.password=d}else h.username=h.auth}function c(h,p){if(i("connecting to an MQTT broker..."),typeof h=="object"&&!p&&(p=h,h=""),p=p||{},h&&typeof h=="string"){let g=r.default.parse(h,!0),y={};if(g.port!=null&&(y.port=Number(g.port)),y.host=g.hostname,y.query=g.query,y.auth=g.auth,y.protocol=g.protocol,y.path=g.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Ne<"u"&&(p.socksProxy=Ne.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=mr().streamBuilder,a.wss=mr().streamBuilder,a.mqtt=qs().default,a.tcp=qs().default,a.ssl=Hs().default,a.tls=a.ssl,a.mqtts=Hs().default):(a.ws=mr().browserStreamBuilder,a.wss=mr().browserStreamBuilder,a.wx=Ws().default,a.wxs=Ws().default,a.ali=zs().default,a.alis=zs().default)),!a[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>g&&w%2===0?!1:typeof a[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function b(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),a[p.protocol](g,p)}let d=new o.default(b,p);return d.on("error",()=>{}),d}function u(h,p,b=!0){return new Promise((d,g)=>{let y=c(h,p),w={connect:_=>{m(),d(y)},end:()=>{m(),d(y)},error:_=>{m(),y.end(),g(_)}};b===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}s.default=c}),Vs=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(b,d,g,y){y===void 0&&(y=g);var w=Object.getOwnPropertyDescriptor(d,g);(!w||("get"in w?!d.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return d[g]}}),Object.defineProperty(b,y,w)}:function(b,d,g,y){y===void 0&&(y=g),b[y]=d[g]}),t=s&&s.__setModuleDefault||(Object.create?function(b,d){Object.defineProperty(b,"default",{enumerable:!0,value:d})}:function(b,d){b.default=d}),r=s&&s.__importStar||(function(){var b=function(d){return b=Object.getOwnPropertyNames||function(g){var y=[];for(var w in g)Object.prototype.hasOwnProperty.call(g,w)&&(y[y.length]=w);return y},b(d)};return function(d){if(d&&d.__esModule)return d;var g={};if(d!=null)for(var y=b(d),w=0;w<y.length;w++)y[w]!=="default"&&e(g,d,y[w]);return t(g,d),g}})(),o=s&&s.__exportStar||function(b,d){for(var g in b)g!=="default"&&!Object.prototype.hasOwnProperty.call(d,g)&&e(d,b,g)},n=s&&s.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};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(xi());s.MqttClient=i.default;var a=n(Za());s.DefaultMessageIdProvider=a.default;var l=n(nh());s.UniqueMessageIdProvider=l.default;var c=n(ja());s.Store=c.default;var u=r(zh());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(sl());s.KeepaliveManager=h.default,s.Client=i.default,o(xi(),s),o(Jt(),s),o(Na(),s);var p=Jr();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Vh=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(Vs());s.default=n,o(Vs(),s)});const Kh=Vh();const Gh={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}/#"},Yh=300,Jh={templateId:"7",type:"link",isDeepLink:!0},Qh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Bl{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={...Gh,...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=h=>{a||(a=!0,clearTimeout(u),h())},c=(h,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),l(()=>i(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Kh.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 h=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(h),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:h})}}),this.client.on("message",(h,p)=>{this.dispatchInbound(h,p)}),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",h=>{this.debugLog("ERROR",{message:h.message}),a||c("mqtt-error",h)}),this.client.on("disconnect",h=>{this.debugLog("DISCONNECT",{reasonCode:h?.reasonCode,properties:h?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",h=>{(h.cmd==="subscribe"||h.cmd==="unsubscribe"||h.cmd==="pingreq")&&this.debugLog(h.cmd.toUpperCase(),{topic:h.topic,packetId:h.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={...Jh,...this.config.fileTemplate??{},...Xh(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=Yh){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??"",h=typeof o.status=="number"?o.status:Number(o.status??0),p={conversationId:c,messageId:u,status:h,raw:o};this.statusUpdateHandlers.forEach(b=>b(p)),this.messageHandlers.forEach(b=>b(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={...Qh,...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 Xh(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function Dl(s,e){return(s.sender??"").toString()===e}function $l(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 Co(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 Fl(s){const e=Co(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 Ks(s,e,t){const r=$l(s,t),o=Co(s),n=Fl(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"?Zh(s.status):"delivered",h={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&&(h.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(h.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:h,template:o}}function Zh(s){return s<0?"error":s>=250?"read":s>=150?"delivered":"sent"}class ql extends po{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 na(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new ia,this.conversationManager=new sa(e.conversationId),this.usesAikaara()&&(this.connection=new ra(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 Bl({...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=>Ks(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(h){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",h)}}}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}=Ks(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(Dl(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}}}const Gs={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 ed(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function td(s,e,t){const r=ed(s.name||"");if(r&&e&&e[r])return e[r];const o=s.type;return o&&o.trim().length>0?o:r&&Gs[r]?Gs[r]:t}function on(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function rd(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 Hl(s){const e=s.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=td(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=on(c,i),h=await fetch(u,{method:s.signMethod??"GET",headers:l});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),b=rd(p,e);if(!b)throw new Error(`Sign response missing path "${e}"`);const d=s.s3HostRewrite?b.replace(/^https:\/\/[^/]+/i,s.s3HostRewrite):b,g=await fetch(d,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const w=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${w.slice(0,200)}`)}if(s.registerEndpoint){const w=JSON.parse(on(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 _=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${_.slice(0,200)}`)}}return{url:s.viewerTemplate?on(s.viewerTemplate,i):b.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Oo(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[p,b]of Object.entries(n))r.append(p,b);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,h=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:h,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 nd="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Wl(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??nd;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 p=await s.getToken();p&&(l.authorization=p)}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 h=u;if(h&&Array.isArray(h.result))return h.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const id="^[A-Z]{4}[0-9]{5}[A-Z]$",od="^[A-Z]{4}0[A-Z0-9]{6}$",sd={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"},ad={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:id,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"},ld={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"},cd={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"},ud={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"},hd={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:od,maxLength:11}]}],submitLabel:"Save"},dd=[ad,ud,ld,cd,sd,hd];function fd(s,e){const t=s||{},r={userId:At(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Te(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:Sd()};r.us80cAmount=Ee(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Ee(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Ee(t.us80dForParentsAmount),r.hasParentOverSixty=Vr(t.hasParentOverSixty),r.preventiveHealthCheckUp=Ee(t.preventiveHealthCheckUp),r.medicalExpenditure=Ee(t.medicalExpenditure),r.savingBankInterest=Ee(t.savingBankInterest),r.fdInterest=Ee(t.fdInterest),r.dividend=Ee(t.dividend),r.anyOtherIncome=Ee(t.anyOtherIncome),r.cryptoSellValue=Ee(t.cryptoSellPrice),r.cryptoPurchaseAmount=Ee(t.cryptoPurchasePrice),r.vdaPurchaseCost=Ee(t.cryptoPurchasePrice);const o=(Ee(t.bizReceiptsBank)??0)+(Ee(t.bizReceiptsCash)??0),n=(Ee(t.profReceiptsBank)??0)+(Ee(t.profReceiptsCash)??0),i=Te(t.bizName)!==void 0||o>0;r.businessName=Te(i?t.bizName:t.profName),r.businessAnnualTurnOver=i?o||void 0:n||void 0,r.agricultureDetails={income:Ee(t.agricultureIncome)},r.exemptIncomeAmount=Ee(t.exemptIncome),r.exemptIncomeNature=Te(t.exemptIncomeNature),Ee(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Te(t.exemptIncomeNature)??"Exempt income",value:String(Ee(t.exemptIncome))}]),r.bankAccountNumber=Te(t.bankAccountNumber),r.bankIfscCode=Te(t.bankIfscCode),(Te(t.bankAccountNumber)||Te(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Te(t.bankAccountNumber),bankIfscCode:Te(t.bankIfscCode)}]);const a={description:Te(t.immovableAssetDescription),flatNo:Te(t.immovableAssetFlatNo),area:Te(t.immovableAssetArea),pinCode:Te(t.immovableAssetPincode),amount:Ee(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=sn(t.hpDetails,pd);l.length&&(r.hpDetails=l);const c=sn(t.salaryDetails,md);if(c.length){r.salaryIncome=c;const u=sn(t.salaryDetails,p=>({grossSalary:Ee(p.grossSalary),employerName:Te(p.employerName)}));u.length&&(r.salary=u);const h=Zr(t.salaryDetails)[0]??{};r.hraAmount=Ee(h.hraReceived),r.leaveTravelAllowanceAmount=Ee(h.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Ee(h.leaveEncashment),r.anyOtherAllowanceAmount=Ee(h.anyOtherAllowance),r.salaryIncomeFlag=!0}return Nt(r)}function pd(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Te(s.loanTakenFrom),bankOrInstituteName:Te(s.lenderName),loanAccountNo:Te(s.loanAccountNumber),loanSanctionDate:Vl(s.sanctionDate),totalLoanAmount:Ee(s.totalLoanAmount),loanOutstandingAmount:Ee(s.outstandingAmount),interest:Ee(s.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Te(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:Vr(s.hasRentalIncome),homeLoanInterest:Ee(s.homeLoanInterest),homeLoanPrinciple:Ee(s.homeLoanPrinciple),housePropertyAddress:Te(s.housePropertyAddress),housePropertyPincode:Te(s.housePropertyPincode),rentalIncome:Ee(s.rentalIncome),nameOfTenant:Te(s.nameOfTenant),propertyTax:Ee(s.propertyTax),hasCoOwnedProperty:Vr(s.hasCoOwnedProperty),coOwnerName:Te(s.coOwnerName),coOwnerPan:Te(s.coOwnerPan),coOwnerShare:Te(s.coOwnerShare),loanDetails:t?[e]:void 0}}function md(s){return{grossSalaryIncome:Ee(s.grossSalary),salary:Ee(s.basicSalary),employer:{employerName:Te(s.employerName),employerTan:Te(s.employerTan)},allowance:{hraAmount:Ee(s.hraReceived),leaveTravelAllowanceAmount:Ee(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Ee(s.leaveEncashment),anyOtherAllowanceAmount:Ee(s.anyOtherAllowance)}}}function gd(s,e){const t=[];for(const r of s){const o=Te(r.employerName),n=Te(r.employerTan),i=Ee(r.grossSalary),a=Ee(r.basicSalary),l=Ee(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:At(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function bd(s,e){const t=Te(s.aadhaarNumber),r=Te(s.bankAccountNumber),o=Te(s.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:At(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function yd(s,e){return{userId:At(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Ee(s.savingBankInterest)??0,fdInterest:Ee(s.fdInterest)??0,dividend:Ee(s.dividend)??0,anyOtherIncome:Ee(s.anyOtherIncome)??0,familyPension:Ee(s.familyPension)??0}}function vd(s,e){const t=Ee(s.cryptoSellPrice),r=Ee(s.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:At(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function wd(s,e){const t=(o,n,i,a)=>{const l=Te(s[o]),c=Te(s[n]),u=Ee(s[i]),h=Ee(s[a]);return l===void 0&&c===void 0&&u===void 0&&h===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:h??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:At(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function _d(s){return Te(s.lenderName)!==void 0||Te(s.loanAccountNumber)!==void 0||Ee(s.totalLoanAmount)!==void 0||Ee(s.outstandingAmount)!==void 0||Ee(s.homeLoanInterest)!==void 0}function zl(s){const e=Te(s.typeOfHouseProperty)?.toUpperCase();return Ee(s.rentalIncome)!==void 0||Te(s.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function kd(s,e){const t=Zr(s.hpDetails).filter(_d).map(r=>{const o=Nt({loanType:"HOMELOAN",bankOrInstituteName:Te(r.lenderName),loanAccountNo:Te(r.loanAccountNumber),loanSanctionDate:Vl(r.sanctionDate),totalLoanAmount:Ee(r.totalLoanAmount),loanOutstandingAmount:Ee(r.outstandingAmount),interest:Ee(r.homeLoanInterest)});return Nt({typeOfHouseProperty:Te(r.typeOfHouseProperty),housePropertyAddress:Te(r.housePropertyAddress),housePropertyPincode:Te(r.housePropertyPincode),homeLoanInterest:Ee(r.homeLoanInterest),homeLoanPrinciple:Ee(r.homeLoanPrinciple),propertyTax:Ee(r.propertyTax),eligible80EEAAmount:Ee(r.eligible80EEAAmount),eligible80EEAmount:Ee(r.eligible80EEAmount),hasCoOwnedProperty:Vr(r.hasCoOwnedProperty)??!1,hasRentalIncome:zl(r),loanDetails:[o]})});return t.length?{userId:At(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function xd(s,e){const t=Zr(s.hpDetails).filter(zl).map(r=>Nt({typeOfHouseProperty:Te(r.typeOfHouseProperty),housePropertyAddress:Te(r.housePropertyAddress),housePropertyPincode:Te(r.housePropertyPincode),rentalIncome:Ee(r.rentalIncome),propertyTax:Ee(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Te(r.nameOfTenant),tenantPanNumber:Te(r.tenantPanNumber),homeLoanInterest:Ee(r.homeLoanInterest)}));return t.length?{userId:At(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function At(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Ee(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Te(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function Vr(s){return s===!0||s===!1?s:void 0}function Sd(){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 Vl(s){const e=Te(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Zr(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function sn(s,e){return Zr(s).map(t=>Nt(e(t))).filter(t=>t!==void 0)}function Nt(s){if(Array.isArray(s)){const e=s.map(Nt).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=Nt(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return s}function Ed(s){const e=s&&typeof s=="object"?s:{},t={},r=De(e.employers),o=De(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(h=>{const p=an(h.salary),b=an(h.perquisites),d=an(h.profitsInLieuOfSalaryType),g=p+b+d,y=Td(h.allowance);return{employerName:Me(h.employerName),employerTan:Me(h.employerTAN),basicSalary:p||void 0,grossSalary:g||void 0,hraReceived:y.hra,leaveTravelAllowance:y.lta,leaveEncashment:y.leaveEncashment,anyOtherAllowance:y.other,totalTdsDeposited:Id(h,o,r)??Le(h.totalTdsDeposited)}}));const n=De(e.houseProperties);n.length&&(t.hpDetails=n.map(h=>{const p=De(h.loanDetails),b=p.length?p[0]:void 0,d=Le(h.grossAnnualRentReceived),g=p.length?p.reduce((x,v)=>x+(Le(v.interest)??0),0):void 0,y=De(h.tenant),w=De(h.coOwners),m=y[0],_=w[0];return{typeOfHouseProperty:Me(h.propertyType),loanTakenFrom:Me(b?.loanTakenFrom),lenderName:Me(b?.bankOrInstituteName),loanAccountNumber:Me(b?.loanAccountNo),sanctionDate:Ad(b?.loanSanctionDate),totalLoanAmount:Le(b?.totalLoanAmount),outstandingAmount:Le(b?.loanOutstandingAmount),homeLoanInterest:g,homeLoanPrinciple:void 0,housePropertyAddress:Me(h.address),housePropertyPincode:Me(h.pinCode),rentalIncome:d,nameOfTenant:Me(m?.name),tenantPanNumber:Me(m?.panNumber),eligible80EEAmount:Le(h.eligible80EEAmount),eligible80EEAAmount:Le(h.eligible80EEAAmount),propertyTax:Le(h.propertyTax),hasCoOwnedProperty:w.length>0,coOwnerName:Me(_?.name),coOwnerPan:Me(_?.panNumber),coOwnerShare:Le(_?.share)?.toString()}})),t.us80cAmount=Ct(De(e.deductionUS80CDetails).map(h=>Le(h.amount))),t.us80dForSelfAndFamilyAmount=Ct(De(e.deductionUS80DDetails).map(h=>Le(h.healthInsuranceAmount)));const i=De(e.incomes),a=h=>Ct(i.filter(p=>Me(p.incomeType)===h).map(p=>Le(p.amount)));t.savingBankInterest=a("SAVING_INTEREST"),t.fdInterest=a("FD_RD_INTEREST"),t.anyOtherIncome=a("ANY_OTHER"),t.familyPension=a("FAMILY_PENSION"),t.dividend=Ct(De(e.dividendIncomes).map(h=>Le(h.income)));const l=e.business;if(l){const h=De(l.presumptiveIncomes),p=g=>{const y=De(g.incomes),w=m=>Le(y.find(_=>Me(_.incomeType)===m)?.receipts)??0;return w("ANY_OTHER")>0?!0:w("BANK")>0||w("CASH")>0?!1:!!Me(g.businessType)?.toUpperCase().includes("PROFESSION")},b=g=>h.find(y=>p(y)===g),d=(g,y)=>{if(!g)return;const w=De(g.incomes),m=x=>Le(w.find(v=>Me(v.incomeType)===x)?.receipts),_=m("BANK")||m("ANY_OTHER");t[y.name]=Me(g.businessType),t[y.nature]=Me(g.natureOfBusiness),t[y.bank]=_||void 0,t[y.cash]=m("CASH")||void 0,t[y.net]=Ct(w.map(x=>Le(x.presumptiveIncome)))||void 0};d(b(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),d(b(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const c=De(e.capitalGain).filter(h=>Me(h.assetType)?.toUpperCase()==="VDA").flatMap(h=>De(h.assetDetails));c.length&&(t.cryptoSellPrice=Ct(c.map(h=>Le(h.sellValue))),t.cryptoPurchasePrice=Ct(c.map(h=>Le(h.purchaseCost)))),t.agricultureIncome=Le(e.agriculturalDetails?.income),t.aadhaarNumber=Me(e.aadharNumber);const u=De(e.bankDetails)[0];return u&&(t.bankAccountNumber=Me(u.accountNumber),t.bankIfscCode=Me(u.ifsCode)),Kl(t)}function Ad(s){const e=Me(s);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function an(s){return De(s).reduce((e,t)=>e+(Le(t.taxableAmount)??0),0)}function Id(s,e,t){if(!e.length)return;const r=Me(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Me(n.deductorTAN)?.trim().toUpperCase()===r)return Le(n.totalTdsDeposited)}const o=Me(s.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Me(n.deductorName)?.trim().toLowerCase()===o)return Le(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Le(e[0].totalTdsDeposited)}function Td(s){const e=De(s);if(!e.length)return{};let t,r,o,n;for(const i of e){const a=Le(i.exemptAmount)??Le(i.allowanceAmount);switch(Me(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)+(Le(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Ct(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function De(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Le(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Me(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function Kl(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"?Kl(o):o):e[t]=r);return e}function ln(){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=Bd(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=Dd(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):Fd(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:$d(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||qd(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function Cd(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 Ed(Po(await r.json().catch(()=>({}))))}async function Od(s,e){const t=await s.getToken(),r=s.userId,o={...fd(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 Po(await a.json().catch(()=>({})))}async function Pd(s,e){return Dt(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function Md(s,e){return Dt(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Rd(s,e){return Dt(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function Ld(s,e){return Dt(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function Nd(s,e){return Dt(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function jd(s,e){return Dt(s,`${s.baseUrl}/itr/v1/automation/hp-income`,e)}async function Ud(s,e){return Dt(s,`${s.baseUrl}/itr/v1/automation/vda`,e)}async function Dt(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 Po(await n.json().catch(()=>({})))}function Bd(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 Dd(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 $d(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 Fd(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function Po(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function qd(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class Hd{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new ql(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:dd,data:{}});const t=ln();if(!(!t||!t.baseUrl))try{const r=await Cd(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=ln();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=gd(n,o);i&&await Pd(r,i)}else if(e==="bank-details"){const n=bd(t,o);n&&await Md(r,n)}else if(e==="other-sources")await Rd(r,yd(t,o));else if(e==="business-profession"){const n=wd(t,o);n&&await Ld(r,n)}else if(e==="crypto-income"){const n=vd(t,o);n&&await Ud(r,n)}else if(e==="house-property"){const n=kd(t,o);n&&await Nd(r,n);const i=xd(t,o);i&&await jd(r,i)}}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=ln();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Od(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 Gl 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||Bc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Ro,position:this.getAttribute("position")||this._config.position||Uc,width:Number(this.getAttribute("width"))||this._config.width||Rc,height:Number(this.getAttribute("height"))||this._config.height||Lc,fontFamily:this._config.fontFamily||jc,borderRadius:this._config.borderRadius??Nc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Lo,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||Dc,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(`
|
|
1
|
+
"use strict";class ra{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 fn{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 ra(t,s=>{this.send({command:"message",identifier:t,data:JSON.stringify(s)})});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((s,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>s(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 po{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(s){console.error(`Error in event handler for "${e}":`,s)}})}removeAllListeners(){this.handlers.clear()}}const Mc=1e3,Rc=10,Lc=400,Nc=600,Ro="#6366f1",jc=12,Uc="system-ui, -apple-system, sans-serif",Lo="Type a message...",Bc="bottom-right",Dc="light",Fc={x:20,y:20},en="aikaara_conversation_id";class na extends po{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 fn(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,s){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...s&&{source:s}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??Rc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Mc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const s=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new fn(s),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const s=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${s}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class ia{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,s){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=s}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 s=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(s,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(s,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 s={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(s["X-Api-Key"]=this.apiKey),this.authToken&&(s.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:s};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class oa{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const s={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(s),s}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(s=>s.status==="sending"&&s.role===e.role&&s.content===e.content&&s.conversationId===e.conversationId&&Date.now()-new Date(s.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 s=No(this._messages,e);return s?(Object.assign(s,e,{id:s.id}),{message:s,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(s=>s.externalId===e||s.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 s=No(t,r);if(s){const n=Hr(s),i=Hr(r);!n&&i&&Object.assign(s,r,{id:s.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function No(o,e,t=15e3){const r=e.attachments&&e.attachments[0],s=(e.metadata??{}).attributes;if(!(!!r||!!(s&&s.fileMessage)))return null;const i=Hr(e),a=jo(e),l=Uo(e);if(!i&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=o.length-1;u>=0;u--){const d=o[u],p=d.attachments&&d.attachments[0],b=(d.metadata??{}).attributes;if(!(!!p||!!(b&&b.fileMessage)))continue;const g=(d.content||"").trim().toLowerCase();if(g==="file_uploaded"||g==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const y=Hr(d);if(i&&y&&i===y)return d;const w=jo(d);if(a&&w&&a===w)return d;const m=Uo(d);if(l&&m&&l===m)return d}return null}function jo(o){const e=o.attachments&&o.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=sa(o);if(t)return t}function Uo(o){const e=o.attachments&&o.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(o.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=o.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function Hr(o){const e=o.attachments&&o.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(o.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=sa(o);if(r){const s=/[?&]cloudFileId=([^&]+)/.exec(r);if(s)return decodeURIComponent(s[1])}}function sa(o){const e=o.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class aa{_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(en)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(en)}catch{return null}}saveToStorage(e){try{localStorage.setItem(en,e)}catch{}}}var mo=Object.defineProperty,$c=Object.getOwnPropertyDescriptor,qc=Object.getOwnPropertyNames,Hc=Object.prototype.hasOwnProperty,Je=(o,e)=>()=>(o&&(e=o(o=0)),e),pe=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Gt=(o,e)=>{for(var t in e)mo(o,t,{get:e[t],enumerable:!0})},Wc=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of qc(e))!Hc.call(o,s)&&s!==t&&mo(o,s,{get:()=>e[s],enumerable:!(r=$c(e,s))||r.enumerable});return o},Le=o=>Wc(mo({},"__esModule",{value:!0}),o),le=Je(()=>{}),Ne={};Gt(Ne,{_debugEnd:()=>Kn,_debugProcess:()=>Vn,_events:()=>li,_eventsCount:()=>ci,_exiting:()=>Mn,_fatalExceptions:()=>Hn,_getActiveHandles:()=>pa,_getActiveRequests:()=>fa,_kill:()=>Nn,_linkedBinding:()=>da,_maxListeners:()=>ai,_preload_modules:()=>oi,_rawDebug:()=>Cn,_startProfilerIdleNotifier:()=>Gn,_stopProfilerIdleNotifier:()=>Yn,_tickCallback:()=>zn,abort:()=>Zn,addListener:()=>ui,allowedNodeEnvironmentFlags:()=>$n,arch:()=>mn,argv:()=>yn,argv0:()=>ii,assert:()=>ma,binding:()=>xn,browser:()=>Tn,chdir:()=>An,config:()=>Rn,cpuUsage:()=>nr,cwd:()=>En,debugPort:()=>ni,default:()=>bo,dlopen:()=>ha,domain:()=>On,emit:()=>mi,emitWarning:()=>kn,env:()=>bn,execArgv:()=>vn,execPath:()=>ri,exit:()=>Dn,features:()=>qn,hasUncaughtExceptionCaptureCallback:()=>ga,hrtime:()=>yr,kill:()=>Bn,listeners:()=>ya,memoryUsage:()=>Un,moduleLoadList:()=>Pn,nextTick:()=>ca,off:()=>hi,on:()=>ct,once:()=>di,openStdin:()=>Fn,pid:()=>ei,platform:()=>gn,ppid:()=>ti,prependListener:()=>gi,prependOnceListener:()=>bi,reallyExit:()=>Ln,release:()=>In,removeAllListeners:()=>pi,removeListener:()=>fi,resourceUsage:()=>jn,setSourceMapsEnabled:()=>si,setUncaughtExceptionCaptureCallback:()=>Wn,stderr:()=>Qn,stdin:()=>Xn,stdout:()=>Jn,title:()=>pn,umask:()=>Sn,uptime:()=>ba,version:()=>wn,versions:()=>_n});function go(o){throw new Error("Node.js process "+o+" is not supported by JSPM core outside of Node.js")}function zc(){!Rt||!Ot||(Rt=!1,Ot.length?st=Ot.concat(st):ar=-1,st.length&&la())}function la(){if(!Rt){var o=setTimeout(zc,0);Rt=!0;for(var e=st.length;e;){for(Ot=st,st=[];++ar<e;)Ot&&Ot[ar].run();ar=-1,e=st.length}Ot=null,Rt=!1,clearTimeout(o)}}function ca(o){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];st.push(new ua(o,e)),st.length===1&&!Rt&&setTimeout(la,0)}function ua(o,e){this.fun=o,this.array=e}function He(){}function da(o){go("_linkedBinding")}function ha(o){go("dlopen")}function fa(){return[]}function pa(){return[]}function ma(o,e){if(!o)throw new Error(e||"assertion error")}function ga(){return!1}function ba(){return dt.now()/1e3}function yr(o){var e=Math.floor((Date.now()-dt.now())*.001),t=dt.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return o&&(r=r-o[0],s=s-o[1],s<0&&(r--,s+=vr)),[r,s]}function ct(){return bo}function ya(o){return[]}var st,Rt,Ot,ar,pn,mn,gn,bn,yn,vn,wn,_n,kn,xn,Sn,En,An,In,Tn,Cn,Pn,On,Mn,Rn,Ln,Nn,nr,jn,Un,Bn,Dn,Fn,$n,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ni,ii,oi,si,dt,tn,vr,ai,li,ci,ui,di,hi,fi,pi,mi,gi,bi,bo,Vc=Je(()=>{le(),ue(),ce(),st=[],Rt=!1,ar=-1,ua.prototype.run=function(){this.fun.apply(null,this.array)},pn="browser",mn="x64",gn="browser",bn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},yn=["/usr/bin/node"],vn=[],wn="v16.8.0",_n={},kn=function(o,e){console.warn((e?e+": ":"")+o)},xn=function(o){go("binding")},Sn=function(o){return 0},En=function(){return"/"},An=function(o){},In={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Tn=!0,Cn=He,Pn=[],On={},Mn=!1,Rn={},Ln=He,Nn=He,nr=function(){return{}},jn=nr,Un=nr,Bn=He,Dn=He,Fn=He,$n={},qn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Hn=He,Wn=He,zn=He,Vn=He,Kn=He,Gn=He,Yn=He,Jn=void 0,Qn=void 0,Xn=void 0,Zn=He,ei=2,ti=1,ri="/bin/usr/node",ni=9229,ii="node",oi=[],si=He,dt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},dt.now===void 0&&(tn=Date.now(),dt.timing&&dt.timing.navigationStart&&(tn=dt.timing.navigationStart),dt.now=()=>Date.now()-tn),vr=1e9,yr.bigint=function(o){var e=yr(o);return typeof BigInt>"u"?e[0]*vr+e[1]:BigInt(e[0]*vr)+BigInt(e[1])},ai=10,li={},ci=0,ui=ct,di=ct,hi=ct,fi=ct,pi=ct,mi=He,gi=ct,bi=ct,bo={version:wn,versions:_n,arch:mn,platform:gn,browser:Tn,release:In,_rawDebug:Cn,moduleLoadList:Pn,binding:xn,_linkedBinding:da,_events:li,_eventsCount:ci,_maxListeners:ai,on:ct,addListener:ui,once:di,off:hi,removeListener:fi,removeAllListeners:pi,emit:mi,prependListener:gi,prependOnceListener:bi,listeners:ya,domain:On,_exiting:Mn,config:Rn,dlopen:ha,uptime:ba,_getActiveRequests:fa,_getActiveHandles:pa,reallyExit:Ln,_kill:Nn,cpuUsage:nr,resourceUsage:jn,memoryUsage:Un,kill:Bn,exit:Dn,openStdin:Fn,allowedNodeEnvironmentFlags:$n,assert:ma,features:qn,_fatalExceptions:Hn,setUncaughtExceptionCaptureCallback:Wn,hasUncaughtExceptionCaptureCallback:ga,emitWarning:kn,nextTick:ca,_tickCallback:zn,_debugProcess:Vn,_debugEnd:Kn,_startProfilerIdleNotifier:Gn,_stopProfilerIdleNotifier:Yn,stdout:Jn,stdin:Xn,stderr:Qn,abort:Zn,umask:Sn,chdir:An,cwd:En,env:bn,title:pn,argv:yn,execArgv:vn,pid:ei,ppid:ti,execPath:ri,debugPort:ni,hrtime:yr,argv0:ii,_preload_modules:oi,setSourceMapsEnabled:si}}),ce=Je(()=>{Vc()});function Kc(){if(yi)return qt;yi=!0,qt.byteLength=a,qt.toByteArray=c,qt.fromByteArray=p;for(var o=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,n=r.length;s<n;++s)o[s]=r[s],e[r.charCodeAt(s)]=s;e[45]=62,e[95]=63;function i(b){var f=b.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var g=b.indexOf("=");g===-1&&(g=f);var y=g===f?0:4-g%4;return[g,y]}function a(b){var f=i(b),g=f[0],y=f[1];return(g+y)*3/4-y}function l(b,f,g){return(f+g)*3/4-g}function c(b){var f,g=i(b),y=g[0],w=g[1],m=new t(l(b,y,w)),_=0,x=w>0?y-4:y,v;for(v=0;v<x;v+=4)f=e[b.charCodeAt(v)]<<18|e[b.charCodeAt(v+1)]<<12|e[b.charCodeAt(v+2)]<<6|e[b.charCodeAt(v+3)],m[_++]=f>>16&255,m[_++]=f>>8&255,m[_++]=f&255;return w===2&&(f=e[b.charCodeAt(v)]<<2|e[b.charCodeAt(v+1)]>>4,m[_++]=f&255),w===1&&(f=e[b.charCodeAt(v)]<<10|e[b.charCodeAt(v+1)]<<4|e[b.charCodeAt(v+2)]>>2,m[_++]=f>>8&255,m[_++]=f&255),m}function u(b){return o[b>>18&63]+o[b>>12&63]+o[b>>6&63]+o[b&63]}function d(b,f,g){for(var y,w=[],m=f;m<g;m+=3)y=(b[m]<<16&16711680)+(b[m+1]<<8&65280)+(b[m+2]&255),w.push(u(y));return w.join("")}function p(b){for(var f,g=b.length,y=g%3,w=[],m=16383,_=0,x=g-y;_<x;_+=m)w.push(d(b,_,_+m>x?x:_+m));return y===1?(f=b[g-1],w.push(o[f>>2]+o[f<<4&63]+"==")):y===2&&(f=(b[g-2]<<8)+b[g-1],w.push(o[f>>10]+o[f>>4&63]+o[f<<2&63]+"=")),w.join("")}return qt}function Gc(){return vi?ir:(vi=!0,ir.read=function(o,e,t,r,s){var n,i,a=s*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?s-1:0,p=t?-1:1,b=o[e+d];for(d+=p,n=b&(1<<-u)-1,b>>=-u,u+=a;u>0;n=n*256+o[e+d],d+=p,u-=8);for(i=n&(1<<-u)-1,n>>=-u,u+=r;u>0;i=i*256+o[e+d],d+=p,u-=8);if(n===0)n=1-c;else{if(n===l)return i?NaN:(b?-1:1)*(1/0);i=i+Math.pow(2,r),n=n-c}return(b?-1:1)*i*Math.pow(2,n-r)},ir.write=function(o,e,t,r,s,n){var i,a,l,c=n*8-s-1,u=(1<<c)-1,d=u>>1,p=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,b=r?0:n-1,f=r?1:-1,g=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+=p/l:e+=p*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,s),i=i+d):(a=e*Math.pow(2,d-1)*Math.pow(2,s),i=0));s>=8;o[t+b]=a&255,b+=f,a/=256,s-=8);for(i=i<<s|a,c+=s;c>0;o[t+b]=i&255,b+=f,i/=256,c-=8);o[t+b-f]|=g*128},ir)}function Yc(){if(wi)return kt;wi=!0;let o=Kc(),e=Gc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;kt.Buffer=i,kt.SlowBuffer=w,kt.INSPECT_MAX_BYTES=50;let r=2147483647;kt.kMaxLength=r,i.TYPED_ARRAY_SUPPORT=s(),!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 s(){try{let h=new Uint8Array(1),k={foo:function(){return 42}};return Object.setPrototypeOf(k,Uint8Array.prototype),Object.setPrototypeOf(h,k),h.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(h){if(h>r)throw new RangeError('The value "'+h+'" is invalid for option "size"');let k=new Uint8Array(h);return Object.setPrototypeOf(k,i.prototype),k}function i(h,k,I){if(typeof h=="number"){if(typeof k=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(h)}return a(h,k,I)}i.poolSize=8192;function a(h,k,I){if(typeof h=="string")return d(h,k);if(ArrayBuffer.isView(h))return b(h);if(h==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h);if(H(h,ArrayBuffer)||h&&H(h.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(h,SharedArrayBuffer)||h&&H(h.buffer,SharedArrayBuffer)))return f(h,k,I);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let F=h.valueOf&&h.valueOf();if(F!=null&&F!==h)return i.from(F,k,I);let X=g(h);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return i.from(h[Symbol.toPrimitive]("string"),k,I);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h)}i.from=function(h,k,I){return a(h,k,I)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function l(h){if(typeof h!="number")throw new TypeError('"size" argument must be of type number');if(h<0)throw new RangeError('The value "'+h+'" is invalid for option "size"')}function c(h,k,I){return l(h),h<=0?n(h):k!==void 0?typeof I=="string"?n(h).fill(k,I):n(h).fill(k):n(h)}i.alloc=function(h,k,I){return c(h,k,I)};function u(h){return l(h),n(h<0?0:y(h)|0)}i.allocUnsafe=function(h){return u(h)},i.allocUnsafeSlow=function(h){return u(h)};function d(h,k){if((typeof k!="string"||k==="")&&(k="utf8"),!i.isEncoding(k))throw new TypeError("Unknown encoding: "+k);let I=m(h,k)|0,F=n(I),X=F.write(h,k);return X!==I&&(F=F.slice(0,X)),F}function p(h){let k=h.length<0?0:y(h.length)|0,I=n(k);for(let F=0;F<k;F+=1)I[F]=h[F]&255;return I}function b(h){if(H(h,Uint8Array)){let k=new Uint8Array(h);return f(k.buffer,k.byteOffset,k.byteLength)}return p(h)}function f(h,k,I){if(k<0||h.byteLength<k)throw new RangeError('"offset" is outside of buffer bounds');if(h.byteLength<k+(I||0))throw new RangeError('"length" is outside of buffer bounds');let F;return k===void 0&&I===void 0?F=new Uint8Array(h):I===void 0?F=new Uint8Array(h,k):F=new Uint8Array(h,k,I),Object.setPrototypeOf(F,i.prototype),F}function g(h){if(i.isBuffer(h)){let k=y(h.length)|0,I=n(k);return I.length===0||h.copy(I,0,0,k),I}if(h.length!==void 0)return typeof h.length!="number"||me(h.length)?n(0):p(h);if(h.type==="Buffer"&&Array.isArray(h.data))return p(h.data)}function y(h){if(h>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return h|0}function w(h){return+h!=h&&(h=0),i.alloc(+h)}i.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==i.prototype},i.compare=function(h,k){if(H(h,Uint8Array)&&(h=i.from(h,h.offset,h.byteLength)),H(k,Uint8Array)&&(k=i.from(k,k.offset,k.byteLength)),!i.isBuffer(h)||!i.isBuffer(k))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===k)return 0;let I=h.length,F=k.length;for(let X=0,de=Math.min(I,F);X<de;++X)if(h[X]!==k[X]){I=h[X],F=k[X];break}return I<F?-1:F<I?1:0},i.isEncoding=function(h){switch(String(h).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(h,k){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return i.alloc(0);let I;if(k===void 0)for(k=0,I=0;I<h.length;++I)k+=h[I].length;let F=i.allocUnsafe(k),X=0;for(I=0;I<h.length;++I){let de=h[I];if(H(de,Uint8Array))X+de.length>F.length?(i.isBuffer(de)||(de=i.from(de)),de.copy(F,X)):Uint8Array.prototype.set.call(F,de,X);else if(i.isBuffer(de))de.copy(F,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=de.length}return F};function m(h,k){if(i.isBuffer(h))return h.length;if(ArrayBuffer.isView(h)||H(h,ArrayBuffer))return h.byteLength;if(typeof h!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof h);let I=h.length,F=arguments.length>2&&arguments[2]===!0;if(!F&&I===0)return 0;let X=!1;for(;;)switch(k){case"ascii":case"latin1":case"binary":return I;case"utf8":case"utf-8":return q(h).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I*2;case"hex":return I>>>1;case"base64":return fe(h).length;default:if(X)return F?-1:q(h).length;k=(""+k).toLowerCase(),X=!0}}i.byteLength=m;function _(h,k,I){let F=!1;if((k===void 0||k<0)&&(k=0),k>this.length||((I===void 0||I>this.length)&&(I=this.length),I<=0)||(I>>>=0,k>>>=0,I<=k))return"";for(h||(h="utf8");;)switch(h){case"hex":return W(this,k,I);case"utf8":case"utf-8":return B(this,k,I);case"ascii":return oe(this,k,I);case"latin1":case"binary":return Y(this,k,I);case"base64":return T(this,k,I);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,k,I);default:if(F)throw new TypeError("Unknown encoding: "+h);h=(h+"").toLowerCase(),F=!0}}i.prototype._isBuffer=!0;function x(h,k,I){let F=h[k];h[k]=h[I],h[I]=F}i.prototype.swap16=function(){let h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let k=0;k<h;k+=2)x(this,k,k+1);return this},i.prototype.swap32=function(){let h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let k=0;k<h;k+=4)x(this,k,k+3),x(this,k+1,k+2);return this},i.prototype.swap64=function(){let h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let k=0;k<h;k+=8)x(this,k,k+7),x(this,k+1,k+6),x(this,k+2,k+5),x(this,k+3,k+4);return this},i.prototype.toString=function(){let h=this.length;return h===0?"":arguments.length===0?B(this,0,h):_.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(h){if(!i.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:i.compare(this,h)===0},i.prototype.inspect=function(){let h="",k=kt.INSPECT_MAX_BYTES;return h=this.toString("hex",0,k).replace(/(.{2})/g,"$1 ").trim(),this.length>k&&(h+=" ... "),"<Buffer "+h+">"},t&&(i.prototype[t]=i.prototype.inspect),i.prototype.compare=function(h,k,I,F,X){if(H(h,Uint8Array)&&(h=i.from(h,h.offset,h.byteLength)),!i.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(k===void 0&&(k=0),I===void 0&&(I=h?h.length:0),F===void 0&&(F=0),X===void 0&&(X=this.length),k<0||I>h.length||F<0||X>this.length)throw new RangeError("out of range index");if(F>=X&&k>=I)return 0;if(F>=X)return-1;if(k>=I)return 1;if(k>>>=0,I>>>=0,F>>>=0,X>>>=0,this===h)return 0;let de=X-F,ke=I-k,V=Math.min(de,ke),ie=this.slice(F,X),Ae=h.slice(k,I);for(let Ie=0;Ie<V;++Ie)if(ie[Ie]!==Ae[Ie]){de=ie[Ie],ke=Ae[Ie];break}return de<ke?-1:ke<de?1:0};function v(h,k,I,F,X){if(h.length===0)return-1;if(typeof I=="string"?(F=I,I=0):I>2147483647?I=2147483647:I<-2147483648&&(I=-2147483648),I=+I,me(I)&&(I=X?0:h.length-1),I<0&&(I=h.length+I),I>=h.length){if(X)return-1;I=h.length-1}else if(I<0)if(X)I=0;else return-1;if(typeof k=="string"&&(k=i.from(k,F)),i.isBuffer(k))return k.length===0?-1:E(h,k,I,F,X);if(typeof k=="number")return k=k&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(h,k,I):Uint8Array.prototype.lastIndexOf.call(h,k,I):E(h,[k],I,F,X);throw new TypeError("val must be string, number or Buffer")}function E(h,k,I,F,X){let de=1,ke=h.length,V=k.length;if(F!==void 0&&(F=String(F).toLowerCase(),F==="ucs2"||F==="ucs-2"||F==="utf16le"||F==="utf-16le")){if(h.length<2||k.length<2)return-1;de=2,ke/=2,V/=2,I/=2}function ie(Ie,Pe){return de===1?Ie[Pe]:Ie.readUInt16BE(Pe*de)}let Ae;if(X){let Ie=-1;for(Ae=I;Ae<ke;Ae++)if(ie(h,Ae)===ie(k,Ie===-1?0:Ae-Ie)){if(Ie===-1&&(Ie=Ae),Ae-Ie+1===V)return Ie*de}else Ie!==-1&&(Ae-=Ae-Ie),Ie=-1}else for(I+V>ke&&(I=ke-V),Ae=I;Ae>=0;Ae--){let Ie=!0;for(let Pe=0;Pe<V;Pe++)if(ie(h,Ae+Pe)!==ie(k,Pe)){Ie=!1;break}if(Ie)return Ae}return-1}i.prototype.includes=function(h,k,I){return this.indexOf(h,k,I)!==-1},i.prototype.indexOf=function(h,k,I){return v(this,h,k,I,!0)},i.prototype.lastIndexOf=function(h,k,I){return v(this,h,k,I,!1)};function S(h,k,I,F){I=Number(I)||0;let X=h.length-I;F?(F=Number(F),F>X&&(F=X)):F=X;let de=k.length;F>de/2&&(F=de/2);let ke;for(ke=0;ke<F;++ke){let V=parseInt(k.substr(ke*2,2),16);if(me(V))return ke;h[I+ke]=V}return ke}function A(h,k,I,F){return ye(q(k,h.length-I),h,I,F)}function C(h,k,I,F){return ye(ee(k),h,I,F)}function O(h,k,I,F){return ye(fe(k),h,I,F)}function j(h,k,I,F){return ye(he(k,h.length-I),h,I,F)}i.prototype.write=function(h,k,I,F){if(k===void 0)F="utf8",I=this.length,k=0;else if(I===void 0&&typeof k=="string")F=k,I=this.length,k=0;else if(isFinite(k))k=k>>>0,isFinite(I)?(I=I>>>0,F===void 0&&(F="utf8")):(F=I,I=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let X=this.length-k;if((I===void 0||I>X)&&(I=X),h.length>0&&(I<0||k<0)||k>this.length)throw new RangeError("Attempt to write outside buffer bounds");F||(F="utf8");let de=!1;for(;;)switch(F){case"hex":return S(this,h,k,I);case"utf8":case"utf-8":return A(this,h,k,I);case"ascii":case"latin1":case"binary":return C(this,h,k,I);case"base64":return O(this,h,k,I);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,h,k,I);default:if(de)throw new TypeError("Unknown encoding: "+F);F=(""+F).toLowerCase(),de=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(h,k,I){return k===0&&I===h.length?o.fromByteArray(h):o.fromByteArray(h.slice(k,I))}function B(h,k,I){I=Math.min(h.length,I);let F=[],X=k;for(;X<I;){let de=h[X],ke=null,V=de>239?4:de>223?3:de>191?2:1;if(X+V<=I){let ie,Ae,Ie,Pe;switch(V){case 1:de<128&&(ke=de);break;case 2:ie=h[X+1],(ie&192)===128&&(Pe=(de&31)<<6|ie&63,Pe>127&&(ke=Pe));break;case 3:ie=h[X+1],Ae=h[X+2],(ie&192)===128&&(Ae&192)===128&&(Pe=(de&15)<<12|(ie&63)<<6|Ae&63,Pe>2047&&(Pe<55296||Pe>57343)&&(ke=Pe));break;case 4:ie=h[X+1],Ae=h[X+2],Ie=h[X+3],(ie&192)===128&&(Ae&192)===128&&(Ie&192)===128&&(Pe=(de&15)<<18|(ie&63)<<12|(Ae&63)<<6|Ie&63,Pe>65535&&Pe<1114112&&(ke=Pe))}}ke===null?(ke=65533,V=1):ke>65535&&(ke-=65536,F.push(ke>>>10&1023|55296),ke=56320|ke&1023),F.push(ke),X+=V}return U(F)}let D=4096;function U(h){let k=h.length;if(k<=D)return String.fromCharCode.apply(String,h);let I="",F=0;for(;F<k;)I+=String.fromCharCode.apply(String,h.slice(F,F+=D));return I}function oe(h,k,I){let F="";I=Math.min(h.length,I);for(let X=k;X<I;++X)F+=String.fromCharCode(h[X]&127);return F}function Y(h,k,I){let F="";I=Math.min(h.length,I);for(let X=k;X<I;++X)F+=String.fromCharCode(h[X]);return F}function W(h,k,I){let F=h.length;(!k||k<0)&&(k=0),(!I||I<0||I>F)&&(I=F);let X="";for(let de=k;de<I;++de)X+=ve[h[de]];return X}function re(h,k,I){let F=h.slice(k,I),X="";for(let de=0;de<F.length-1;de+=2)X+=String.fromCharCode(F[de]+F[de+1]*256);return X}i.prototype.slice=function(h,k){let I=this.length;h=~~h,k=k===void 0?I:~~k,h<0?(h+=I,h<0&&(h=0)):h>I&&(h=I),k<0?(k+=I,k<0&&(k=0)):k>I&&(k=I),k<h&&(k=h);let F=this.subarray(h,k);return Object.setPrototypeOf(F,i.prototype),F};function $(h,k,I){if(h%1!==0||h<0)throw new RangeError("offset is not uint");if(h+k>I)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(h,k,I){h=h>>>0,k=k>>>0,I||$(h,k,this.length);let F=this[h],X=1,de=0;for(;++de<k&&(X*=256);)F+=this[h+de]*X;return F},i.prototype.readUintBE=i.prototype.readUIntBE=function(h,k,I){h=h>>>0,k=k>>>0,I||$(h,k,this.length);let F=this[h+--k],X=1;for(;k>0&&(X*=256);)F+=this[h+--k]*X;return F},i.prototype.readUint8=i.prototype.readUInt8=function(h,k){return h=h>>>0,k||$(h,1,this.length),this[h]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(h,k){return h=h>>>0,k||$(h,2,this.length),this[h]|this[h+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(h,k){return h=h>>>0,k||$(h,2,this.length),this[h]<<8|this[h+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(h,k){return h=h>>>0,k||$(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(h,k){return h=h>>>0,k||$(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},i.prototype.readBigUInt64LE=ae(function(h){h=h>>>0,J(h,"offset");let k=this[h],I=this[h+7];(k===void 0||I===void 0)&&ge(h,this.length-8);let F=k+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,X=this[++h]+this[++h]*2**8+this[++h]*2**16+I*2**24;return BigInt(F)+(BigInt(X)<<BigInt(32))}),i.prototype.readBigUInt64BE=ae(function(h){h=h>>>0,J(h,"offset");let k=this[h],I=this[h+7];(k===void 0||I===void 0)&&ge(h,this.length-8);let F=k*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],X=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+I;return(BigInt(F)<<BigInt(32))+BigInt(X)}),i.prototype.readIntLE=function(h,k,I){h=h>>>0,k=k>>>0,I||$(h,k,this.length);let F=this[h],X=1,de=0;for(;++de<k&&(X*=256);)F+=this[h+de]*X;return X*=128,F>=X&&(F-=Math.pow(2,8*k)),F},i.prototype.readIntBE=function(h,k,I){h=h>>>0,k=k>>>0,I||$(h,k,this.length);let F=k,X=1,de=this[h+--F];for(;F>0&&(X*=256);)de+=this[h+--F]*X;return X*=128,de>=X&&(de-=Math.pow(2,8*k)),de},i.prototype.readInt8=function(h,k){return h=h>>>0,k||$(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},i.prototype.readInt16LE=function(h,k){h=h>>>0,k||$(h,2,this.length);let I=this[h]|this[h+1]<<8;return I&32768?I|4294901760:I},i.prototype.readInt16BE=function(h,k){h=h>>>0,k||$(h,2,this.length);let I=this[h+1]|this[h]<<8;return I&32768?I|4294901760:I},i.prototype.readInt32LE=function(h,k){return h=h>>>0,k||$(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},i.prototype.readInt32BE=function(h,k){return h=h>>>0,k||$(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},i.prototype.readBigInt64LE=ae(function(h){h=h>>>0,J(h,"offset");let k=this[h],I=this[h+7];(k===void 0||I===void 0)&&ge(h,this.length-8);let F=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(I<<24);return(BigInt(F)<<BigInt(32))+BigInt(k+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24)}),i.prototype.readBigInt64BE=ae(function(h){h=h>>>0,J(h,"offset");let k=this[h],I=this[h+7];(k===void 0||I===void 0)&&ge(h,this.length-8);let F=(k<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(F)<<BigInt(32))+BigInt(this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+I)}),i.prototype.readFloatLE=function(h,k){return h=h>>>0,k||$(h,4,this.length),e.read(this,h,!0,23,4)},i.prototype.readFloatBE=function(h,k){return h=h>>>0,k||$(h,4,this.length),e.read(this,h,!1,23,4)},i.prototype.readDoubleLE=function(h,k){return h=h>>>0,k||$(h,8,this.length),e.read(this,h,!0,52,8)},i.prototype.readDoubleBE=function(h,k){return h=h>>>0,k||$(h,8,this.length),e.read(this,h,!1,52,8)};function Z(h,k,I,F,X,de){if(!i.isBuffer(h))throw new TypeError('"buffer" argument must be a Buffer instance');if(k>X||k<de)throw new RangeError('"value" argument is out of bounds');if(I+F>h.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(h,k,I,F){if(h=+h,k=k>>>0,I=I>>>0,!F){let ke=Math.pow(2,8*I)-1;Z(this,h,k,I,ke,0)}let X=1,de=0;for(this[k]=h&255;++de<I&&(X*=256);)this[k+de]=h/X&255;return k+I},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(h,k,I,F){if(h=+h,k=k>>>0,I=I>>>0,!F){let ke=Math.pow(2,8*I)-1;Z(this,h,k,I,ke,0)}let X=I-1,de=1;for(this[k+X]=h&255;--X>=0&&(de*=256);)this[k+X]=h/de&255;return k+I},i.prototype.writeUint8=i.prototype.writeUInt8=function(h,k,I){return h=+h,k=k>>>0,I||Z(this,h,k,1,255,0),this[k]=h&255,k+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(h,k,I){return h=+h,k=k>>>0,I||Z(this,h,k,2,65535,0),this[k]=h&255,this[k+1]=h>>>8,k+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(h,k,I){return h=+h,k=k>>>0,I||Z(this,h,k,2,65535,0),this[k]=h>>>8,this[k+1]=h&255,k+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(h,k,I){return h=+h,k=k>>>0,I||Z(this,h,k,4,4294967295,0),this[k+3]=h>>>24,this[k+2]=h>>>16,this[k+1]=h>>>8,this[k]=h&255,k+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(h,k,I){return h=+h,k=k>>>0,I||Z(this,h,k,4,4294967295,0),this[k]=h>>>24,this[k+1]=h>>>16,this[k+2]=h>>>8,this[k+3]=h&255,k+4};function M(h,k,I,F,X){G(k,F,X,h,I,7);let de=Number(k&BigInt(4294967295));h[I++]=de,de=de>>8,h[I++]=de,de=de>>8,h[I++]=de,de=de>>8,h[I++]=de;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return h[I++]=ke,ke=ke>>8,h[I++]=ke,ke=ke>>8,h[I++]=ke,ke=ke>>8,h[I++]=ke,I}function Q(h,k,I,F,X){G(k,F,X,h,I,7);let de=Number(k&BigInt(4294967295));h[I+7]=de,de=de>>8,h[I+6]=de,de=de>>8,h[I+5]=de,de=de>>8,h[I+4]=de;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return h[I+3]=ke,ke=ke>>8,h[I+2]=ke,ke=ke>>8,h[I+1]=ke,ke=ke>>8,h[I]=ke,I+8}i.prototype.writeBigUInt64LE=ae(function(h,k=0){return M(this,h,k,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=ae(function(h,k=0){return Q(this,h,k,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(h,k,I,F){if(h=+h,k=k>>>0,!F){let V=Math.pow(2,8*I-1);Z(this,h,k,I,V-1,-V)}let X=0,de=1,ke=0;for(this[k]=h&255;++X<I&&(de*=256);)h<0&&ke===0&&this[k+X-1]!==0&&(ke=1),this[k+X]=(h/de>>0)-ke&255;return k+I},i.prototype.writeIntBE=function(h,k,I,F){if(h=+h,k=k>>>0,!F){let V=Math.pow(2,8*I-1);Z(this,h,k,I,V-1,-V)}let X=I-1,de=1,ke=0;for(this[k+X]=h&255;--X>=0&&(de*=256);)h<0&&ke===0&&this[k+X+1]!==0&&(ke=1),this[k+X]=(h/de>>0)-ke&255;return k+I},i.prototype.writeInt8=function(h,k,I){return h=+h,k=k>>>0,I||Z(this,h,k,1,127,-128),h<0&&(h=255+h+1),this[k]=h&255,k+1},i.prototype.writeInt16LE=function(h,k,I){return h=+h,k=k>>>0,I||Z(this,h,k,2,32767,-32768),this[k]=h&255,this[k+1]=h>>>8,k+2},i.prototype.writeInt16BE=function(h,k,I){return h=+h,k=k>>>0,I||Z(this,h,k,2,32767,-32768),this[k]=h>>>8,this[k+1]=h&255,k+2},i.prototype.writeInt32LE=function(h,k,I){return h=+h,k=k>>>0,I||Z(this,h,k,4,2147483647,-2147483648),this[k]=h&255,this[k+1]=h>>>8,this[k+2]=h>>>16,this[k+3]=h>>>24,k+4},i.prototype.writeInt32BE=function(h,k,I){return h=+h,k=k>>>0,I||Z(this,h,k,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[k]=h>>>24,this[k+1]=h>>>16,this[k+2]=h>>>8,this[k+3]=h&255,k+4},i.prototype.writeBigInt64LE=ae(function(h,k=0){return M(this,h,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=ae(function(h,k=0){return Q(this,h,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(h,k,I,F,X,de){if(I+F>h.length)throw new RangeError("Index out of range");if(I<0)throw new RangeError("Index out of range")}function te(h,k,I,F,X){return k=+k,I=I>>>0,X||be(h,k,I,4),e.write(h,k,I,F,23,4),I+4}i.prototype.writeFloatLE=function(h,k,I){return te(this,h,k,!0,I)},i.prototype.writeFloatBE=function(h,k,I){return te(this,h,k,!1,I)};function we(h,k,I,F,X){return k=+k,I=I>>>0,X||be(h,k,I,8),e.write(h,k,I,F,52,8),I+8}i.prototype.writeDoubleLE=function(h,k,I){return we(this,h,k,!0,I)},i.prototype.writeDoubleBE=function(h,k,I){return we(this,h,k,!1,I)},i.prototype.copy=function(h,k,I,F){if(!i.isBuffer(h))throw new TypeError("argument should be a Buffer");if(I||(I=0),!F&&F!==0&&(F=this.length),k>=h.length&&(k=h.length),k||(k=0),F>0&&F<I&&(F=I),F===I||h.length===0||this.length===0)return 0;if(k<0)throw new RangeError("targetStart out of bounds");if(I<0||I>=this.length)throw new RangeError("Index out of range");if(F<0)throw new RangeError("sourceEnd out of bounds");F>this.length&&(F=this.length),h.length-k<F-I&&(F=h.length-k+I);let X=F-I;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(k,I,F):Uint8Array.prototype.set.call(h,this.subarray(I,F),k),X},i.prototype.fill=function(h,k,I,F){if(typeof h=="string"){if(typeof k=="string"?(F=k,k=0,I=this.length):typeof I=="string"&&(F=I,I=this.length),F!==void 0&&typeof F!="string")throw new TypeError("encoding must be a string");if(typeof F=="string"&&!i.isEncoding(F))throw new TypeError("Unknown encoding: "+F);if(h.length===1){let de=h.charCodeAt(0);(F==="utf8"&&de<128||F==="latin1")&&(h=de)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(k<0||this.length<k||this.length<I)throw new RangeError("Out of range index");if(I<=k)return this;k=k>>>0,I=I===void 0?this.length:I>>>0,h||(h=0);let X;if(typeof h=="number")for(X=k;X<I;++X)this[X]=h;else{let de=i.isBuffer(h)?h:i.from(h,F),ke=de.length;if(ke===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(X=0;X<I-k;++X)this[X+k]=de[X%ke]}return this};let K={};function N(h,k,I){K[h]=class extends I{constructor(){super(),Object.defineProperty(this,"message",{value:k.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${h}]`,this.stack,delete this.name}get code(){return h}set code(F){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:F,writable:!0})}toString(){return`${this.name} [${h}]: ${this.message}`}}}N("ERR_BUFFER_OUT_OF_BOUNDS",function(h){return h?`${h} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),N("ERR_INVALID_ARG_TYPE",function(h,k){return`The "${h}" argument must be of type number. Received type ${typeof k}`},TypeError),N("ERR_OUT_OF_RANGE",function(h,k,I){let F=`The value of "${h}" is out of range.`,X=I;return Number.isInteger(I)&&Math.abs(I)>2**32?X=ne(String(I)):typeof I=="bigint"&&(X=String(I),(I>BigInt(2)**BigInt(32)||I<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),F+=` It must be ${k}. Received ${X}`,F},RangeError);function ne(h){let k="",I=h.length,F=h[0]==="-"?1:0;for(;I>=F+4;I-=3)k=`_${h.slice(I-3,I)}${k}`;return`${h.slice(0,I)}${k}`}function z(h,k,I){J(k,"offset"),(h[k]===void 0||h[k+I]===void 0)&&ge(k,h.length-(I+1))}function G(h,k,I,F,X,de){if(h>I||h<k){let ke=typeof k=="bigint"?"n":"",V;throw k===0||k===BigInt(0)?V=`>= 0${ke} and < 2${ke} ** ${(de+1)*8}${ke}`:V=`>= -(2${ke} ** ${(de+1)*8-1}${ke}) and < 2 ** ${(de+1)*8-1}${ke}`,new K.ERR_OUT_OF_RANGE("value",V,h)}z(F,X,de)}function J(h,k){if(typeof h!="number")throw new K.ERR_INVALID_ARG_TYPE(k,"number",h)}function ge(h,k,I){throw Math.floor(h)!==h?(J(h,I),new K.ERR_OUT_OF_RANGE("offset","an integer",h)):k<0?new K.ERR_BUFFER_OUT_OF_BOUNDS:new K.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${k}`,h)}let se=/[^+/0-9A-Za-z-_]/g;function R(h){if(h=h.split("=")[0],h=h.trim().replace(se,""),h.length<2)return"";for(;h.length%4!==0;)h=h+"=";return h}function q(h,k){k=k||1/0;let I,F=h.length,X=null,de=[];for(let ke=0;ke<F;++ke){if(I=h.charCodeAt(ke),I>55295&&I<57344){if(!X){if(I>56319){(k-=3)>-1&&de.push(239,191,189);continue}else if(ke+1===F){(k-=3)>-1&&de.push(239,191,189);continue}X=I;continue}if(I<56320){(k-=3)>-1&&de.push(239,191,189),X=I;continue}I=(X-55296<<10|I-56320)+65536}else X&&(k-=3)>-1&&de.push(239,191,189);if(X=null,I<128){if((k-=1)<0)break;de.push(I)}else if(I<2048){if((k-=2)<0)break;de.push(I>>6|192,I&63|128)}else if(I<65536){if((k-=3)<0)break;de.push(I>>12|224,I>>6&63|128,I&63|128)}else if(I<1114112){if((k-=4)<0)break;de.push(I>>18|240,I>>12&63|128,I>>6&63|128,I&63|128)}else throw new Error("Invalid code point")}return de}function ee(h){let k=[];for(let I=0;I<h.length;++I)k.push(h.charCodeAt(I)&255);return k}function he(h,k){let I,F,X,de=[];for(let ke=0;ke<h.length&&!((k-=2)<0);++ke)I=h.charCodeAt(ke),F=I>>8,X=I%256,de.push(X),de.push(F);return de}function fe(h){return o.toByteArray(R(h))}function ye(h,k,I,F){let X;for(X=0;X<F&&!(X+I>=k.length||X>=h.length);++X)k[X+I]=h[X];return X}function H(h,k){return h instanceof k||h!=null&&h.constructor!=null&&h.constructor.name!=null&&h.constructor.name===k.name}function me(h){return h!==h}let ve=(function(){let h="0123456789abcdef",k=new Array(256);for(let I=0;I<16;++I){let F=I*16;for(let X=0;X<16;++X)k[F+X]=h[I]+h[X]}return k})();function ae(h){return typeof BigInt>"u"?Oe:h}function Oe(){throw new Error("BigInt not supported")}return kt}var qt,yi,ir,vi,kt,wi,Jc=Je(()=>{le(),ue(),ce(),qt={},yi=!1,ir={},vi=!1,kt={},wi=!1}),Fe={};Gt(Fe,{Buffer:()=>Wr,INSPECT_MAX_BYTES:()=>va,default:()=>ut,kMaxLength:()=>wa});var ut,Wr,va,wa,$e=Je(()=>{le(),ue(),ce(),Jc(),ut=Yc(),ut.Buffer,ut.SlowBuffer,ut.INSPECT_MAX_BYTES,ut.kMaxLength,Wr=ut.Buffer,va=ut.INSPECT_MAX_BYTES,wa=ut.kMaxLength}),ue=Je(()=>{$e()}),Be=pe((o,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 s="";for(let n=0;n<r.length;n++)s+=` ${r[n].stack}
|
|
2
|
+
`;super(s),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,s){return r.includes(s)},ArrayPrototypeIndexOf(r,s){return r.indexOf(s)},ArrayPrototypeJoin(r,s){return r.join(s)},ArrayPrototypeMap(r,s){return r.map(s)},ArrayPrototypePop(r,s){return r.pop(s)},ArrayPrototypePush(r,s){return r.push(s)},ArrayPrototypeSlice(r,s,n){return r.slice(s,n)},Error,FunctionPrototypeCall(r,s,...n){return r.call(s,...n)},FunctionPrototypeSymbolHasInstance(r,s){return Function.prototype[Symbol.hasInstance].call(r,s)},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,s){return Object.defineProperties(r,s)},ObjectDefineProperty(r,s,n){return Object.defineProperty(r,s,n)},ObjectGetOwnPropertyDescriptor(r,s){return Object.getOwnPropertyDescriptor(r,s)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,s){return Object.setPrototypeOf(r,s)},Promise,PromisePrototypeCatch(r,s){return r.catch(s)},PromisePrototypeThen(r,s,n){return r.then(s,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,s){return r.test(s)},SafeSet:Set,String,StringPrototypeSlice(r,s,n){return r.slice(s,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,s,n){return r.set(s,n)},Boolean,Uint8Array}}),_a=pe((o,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[s,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((o,e)=>{le(),ue(),ce();var{format:t,inspect:r}=_a(),{AggregateError:s}=Be(),n=globalThis.AggregateError||s,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,_){if(!m)throw new u.ERR_INTERNAL_ASSERTION(_)}function p(m){let _="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)_=`_${m.slice(x-3,x)}${_}`;return`${m.slice(0,x)}${_}`}function b(m,_,x){if(typeof _=="function")return d(_.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${_.length}).`),_(...x);let v=(_.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?_:t(_,...x)}function f(m,_,x){x||(x=Error);class v extends x{constructor(...S){super(b(m,_,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 g(m){let _=c+m.name;return Object.defineProperty(m,"name",{value:_}),m}function y(m,_){if(m&&_&&m!==_){if(Array.isArray(_.errors))return _.errors.push(m),_;let x=new n([_,m],_.message);return x.code=_.code,x}return m||_}var w=class extends Error{constructor(m="The operation was aborted",_=void 0){if(_!==void 0&&typeof _!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",_);super(m,_),this.code="ABORT_ERR",this.name="AbortError"}};f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(m,_,x)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(_)||(_=[_]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let E=[],S=[],A=[];for(let O of _)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"'),A.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||A.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}`}}A.length>0&&(v+=" or ")}switch(A.length){case 0:break;case 1:A[0].toLowerCase()!==A[0]&&(v+="an "),v+=`${A[0]}`;break;case 2:v+=`one of ${A[0]} or ${A[1]}`;break;default:{let O=A.pop();v+=`one of ${A.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 C;if((C=x.constructor)!==null&&C!==void 0&&C.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),f("ERR_INVALID_ARG_VALUE",(m,_,x="is invalid")=>{let v=r(_);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${x}. Received ${v}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(m,_,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 "${_}" function but got ${E}.`},TypeError),f("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let _,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:_+=`The ${m[0]} argument`;break;case 2:_+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();_+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${_} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(m,_,x)=>{d(_,'Missing "range" argument');let v;if(Number.isInteger(x)&&Math.abs(x)>2**32)v=p(String(x));else if(typeof x=="bigint"){v=String(x);let E=BigInt(2)**BigInt(32);(x>E||x<-E)&&(v=p(v)),v+="n"}else v=r(x);return`The value of "${m}" is out of range. It must be ${_}. Received ${v}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:g(y),hideStackFrames:g,codes:u}}),cr=pe((o,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}),Et={};Gt(Et,{EventEmitter:()=>ka,default:()=>Ht,defaultMaxListeners:()=>xa,init:()=>Sa,listenerCount:()=>Ea,on:()=>Aa,once:()=>Ia});function Qc(){if(_i)return or;_i=!0;var o=typeof Reflect=="object"?Reflect:null,e=o&&typeof o.apply=="function"?o.apply:function(x,v,E){return Function.prototype.apply.call(x,v,E)},t;o&&typeof o.ownKeys=="function"?t=o.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 s=Number.isNaN||function(x){return x!==x};function n(){n.init.call(this)}or=n,or.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||s(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||s(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",A=this._events;if(A!==void 0)S=S&&A.error===void 0;else if(!S)return!1;if(S){var C;if(v.length>0&&(C=v[0]),C instanceof Error)throw C;var O=new Error("Unhandled error."+(C?" ("+C.message+")":""));throw O.context=C,O}var j=A[x];if(j===void 0)return!1;if(typeof j=="function")e(j,this,v);else for(var T=j.length,B=f(j,T),E=0;E<T;++E)e(B[E],this,v);return!0};function c(x,v,E,S){var A,C,O;if(a(E),C=x._events,C===void 0?(C=x._events=Object.create(null),x._eventsCount=0):(C.newListener!==void 0&&(x.emit("newListener",v,E.listener?E.listener:E),C=x._events),O=C[v]),O===void 0)O=C[v]=E,++x._eventsCount;else if(typeof O=="function"?O=C[v]=S?[E,O]:[O,E]:S?O.unshift(E):O.push(E),A=l(x),A>0&&O.length>A&&!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},A=u.bind(S);return A.listener=E,S.wrapFn=A,A}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,A,C,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(A=-1,C=E.length-1;C>=0;C--)if(E[C]===v||E[C].listener===v){O=E[C].listener,A=C;break}if(A<0)return this;A===0?E.shift():g(E,A),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 A=Object.keys(E),C;for(S=0;S<A.length;++S)C=A[S],C!=="removeListener"&&this.removeAllListeners(C);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 p(x,v,E){var S=x._events;if(S===void 0)return[];var A=S[v];return A===void 0?[]:typeof A=="function"?E?[A.listener||A]:[A]:E?y(A):f(A,A.length)}n.prototype.listeners=function(x){return p(this,x,!0)},n.prototype.rawListeners=function(x){return p(this,x,!1)},n.listenerCount=function(x,v){return typeof x.listenerCount=="function"?x.listenerCount(v):b.call(x,v)},n.prototype.listenerCount=b;function b(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 f(x,v){for(var E=new Array(v),S=0;S<v;++S)E[S]=x[S];return E}function g(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 A(O){x.removeListener(v,C),S(O)}function C(){typeof x.removeListener=="function"&&x.removeListener("error",A),E([].slice.call(arguments))}_(x,v,C,{once:!0}),v!=="error"&&m(x,A,{once:!0})})}function m(x,v,E){typeof x.on=="function"&&_(x,"error",v,E)}function _(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 A(C){S.once&&x.removeEventListener(v,A),E(C)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return or}var or,_i,Ht,ka,xa,Sa,Ea,Aa,Ia,jt=Je(()=>{le(),ue(),ce(),or={},_i=!1,Ht=Qc(),Ht.once,Ht.once=function(o,e){return new Promise((t,r)=>{function s(...i){n!==void 0&&o.removeListener("error",n),t(i)}let n;e!=="error"&&(n=i=>{o.removeListener(name,s),r(i)},o.once("error",n)),o.once(e,s)})},Ht.on=function(o,e){let t=[],r=[],s=null,n=!1,i={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(s){let u=Promise.reject(s);return s=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){o.removeListener(e,a),o.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){s=c,o.removeListener(e,a),o.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return o.on(e,a),o.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):s=c,i.return()}},{EventEmitter:ka,defaultMaxListeners:xa,init:Sa,listenerCount:Ea,on:Aa,once:Ia}=Ht}),Ye=pe((o,e)=>{le(),ue(),ce();var t=($e(),Le(Fe)),{format:r,inspect:s}=_a(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ke(),{kResistStopPropagation:i,AggregateError:a,SymbolDispose:l}=Be(),c=globalThis.AbortSignal||cr().AbortSignal,u=globalThis.AbortController||cr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,b=typeof p<"u"?function(y){return y instanceof p}:function(y){return!1},f=(y,w)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new n(w,"AbortSignal",y)},g=(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,_)=>{y=m,w=_}),resolve:y,reject:w}},promisify(y){return new Promise((w,m)=>{y((_,...x)=>_?m(_):w(...x))})},debuglog(){return function(){}},format:r,inspect:s,types:{isAsyncFunction(y){return y instanceof d},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:b,deprecate(y,w){return y},addAbortListener:(jt(),Le(Et)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);f(y,"signal"),g(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 _;(_=m)===null||_===void 0||_()}}},AbortSignalAny:c.any||function(y){if(y.length===1)return y[0];let w=new u,m=()=>w.abort();return y.forEach(_=>{f(_,"signals"),_.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{y.forEach(_=>_.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),ur=pe((o,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:s,ArrayPrototypeMap:n,NumberIsInteger:i,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:b,StringPrototypeToUpperCase:f,StringPrototypeTrim:g}=Be(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:_,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ke(),{normalizeEncoding:E}=Ye(),{isAsyncFunction:S,isArrayBufferView:A}=Ye().types,C={};function O(H){return H===(H|0)}function j(H){return H===H>>>0}var T=/^[0-7]+$/,B="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(p(T,H)===null)throw new _(me,H,B);H=u(H,8)}return Y(H,me),H}var U=y((H,me,ve=c,ae=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>ae)throw new x(me,`>= ${ve} && <= ${ae}`,H)}),oe=y((H,me,ve=-2147483648,ae=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>ae)throw new x(me,`>= ${ve} && <= ${ae}`,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 ae=ve?1:0,Oe=4294967295;if(H<ae||H>Oe)throw new x(me,`>= ${ae} && <= ${Oe}`,H)});function W(H,me){if(typeof H!="string")throw new m(me,"string",H)}function re(H,me,ve=void 0,ae){if(typeof H!="number")throw new m(me,"number",H);if(ve!=null&&H<ve||ae!=null&&H>ae||(ve!=null||ae!=null)&&a(H))throw new x(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&ae!=null?" && ":""}${ae!=null?`<= ${ae}`:""}`,H)}var $=y((H,me,ve)=>{if(!r(ve,H)){let ae="must be one of: "+s(n(ve,Oe=>typeof Oe=="string"?`'${Oe}'`:b(Oe)),", ");throw new _(me,H,ae)}});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 ae=M(ve,"allowArray",!1),Oe=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!ae&&t(H)||typeof H!="object"&&(!Oe||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 ae=`must be longer than ${ve}`;throw new _(me,H,ae)}});function we(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)W(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 ae=H[ve],Oe=`${me}[${ve}]`;if(ae==null)throw new m(Oe,"AbortSignal",ae);ge(ae,Oe)}}function ne(H,me="signal"){if(W(H,me),C[H]===void 0)throw C[f(H)]!==void 0?new v(H+" (signals must use all capital letters)"):new v(H)}var z=y((H,me="buffer")=>{if(!A(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function G(H,me){let ve=E(me),ae=H.length;if(ve==="hex"&&ae%2!==0)throw new _("encoding",me,`is invalid for data of length ${ae}`)}function J(H,me="Port",ve=!0){if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&g(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)}),se=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)}),q=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,`('${s(ve,"|")}')`,H)}var he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!p(he,H))throw new _(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 ae=0;ae<me;ae++){let Oe=H[ae];fe(Oe,"hints"),ve+=Oe,ae!==me-1&&(ve+=", ")}return ve}throw new _("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:z,validateDictionary:be,validateEncoding:G,validateFunction:se,validateInt32:oe,validateInteger:U,validateNumber:re,validateObject:Q,validateOneOf:$,validatePlainFunction:R,validatePort:J,validateSignalName:ne,validateString:W,validateUint32:Y,validateUndefined:q,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:ye}}),Ut=pe((o,e)=>{le(),ue(),ce();var t=e.exports={},r,s;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"?s=clearTimeout:s=i}catch{s=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(s===clearTimeout)return clearTimeout(w);if((s===i||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(w);try{return s(w)}catch{try{return s.call(null,w)}catch{return s.call(this,w)}}}var c=[],u=!1,d,p=-1;function b(){!u||!d||(u=!1,d.length?c=d.concat(c):p=-1,c.length&&f())}function f(){if(!u){var w=a(b);u=!0;for(var m=c.length;m;){for(d=c,c=[];++p<m;)d&&d[p].run();p=-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 _=1;_<arguments.length;_++)m[_-1]=arguments[_];c.push(new g(w,m)),c.length===1&&!u&&a(f)};function g(w,m){this.fun=w,this.array=m}g.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}}),mt=pe((o,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:s}=Be(),n=s("nodejs.stream.destroyed"),i=s("nodejs.stream.errored"),a=s("nodejs.stream.readable"),l=s("nodejs.stream.writable"),c=s("nodejs.stream.disturbed"),u=s("nodejs.webstream.isClosedPromise"),d=s("nodejs.webstream.controllerErrorFunction");function p(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 b(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 f(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function g(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&&!g(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function w(M){return!!(M&&!g(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!g(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function _(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(!g(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(!b(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(!b(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 A(M){if(!p(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 C(M,Q){if(!p(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:p(M)&&M.readable&&!C(M)}function j(M){return M&&M[l]!=null?M[l]:typeof M?.writable!="boolean"?null:v(M)?!1:b(M)&&M.writable&&!E(M)}function T(M,Q){return g(M)?v(M)?!0:!(Q?.readable!==!1&&O(M)||Q?.writable!==!1&&j(M)):null}function B(M){var Q,be;return g(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 g(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(!g(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"&&oe(M)?M._closed:null}function oe(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"&&oe(M)}function W(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(!g(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,z,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:(z=M._writableState)===null||z===void 0?void 0:z.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:f,isFinished:T,isIterable:x,isReadableNodeStream:p,isReadableStream:y,isReadableEnded:A,isReadableFinished:C,isReadableErrored:D,isNodeStream:g,isWebStream:_,isWritable:j,isWritableNodeStream:b,isWritableStream:w,isWritableEnded:E,isWritableFinished:S,isWritableErrored:B,isServerRequest:W,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),At=pe((o,e)=>{le(),ue(),ce();var t=Ut(),{AbortError:r,codes:s}=Ke(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=s,{kEmptyObject:a,once:l}=Ye(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:p}=ur(),{Promise:b,PromisePrototypeThen:f,SymbolDispose:g}=Be(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:_,isReadableFinished:x,isReadableErrored:v,isWritable:E,isWritableNodeStream:S,isWritableStream:A,isWritableFinished:C,isWritableErrored:O,isNodeStream:j,willEmitClose:T,kIsClosedPromise:B}=mt(),D;function U($){return $.setHeader&&typeof $.abort=="function"}var oe=()=>{};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),_($)||A($))return W($,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()},z=T($)&&m($)===te&&S($)===we,G=C($,!1),J=()=>{G=!0,$.destroyed&&(z=!1),!(z&&(!$.readable||te))&&(!te||ge)&&M.call($)},ge=x($,!1),se=()=>{ge=!0,$.destroyed&&(z=!1),!(z&&(!$.writable||we))&&(!we||G)&&M.call($)},R=H=>{M.call($,H)},q=y($),ee=()=>{q=!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&&!C($,!1))return M.call($,new i);M.call($)},he=()=>{q=!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),z||$.on("abort",ee),$.req?fe():$.on("request",fe)):we&&!K&&($.on("end",ne),$.on("close",ne)),!z&&typeof $.aborted=="boolean"&&$.on("aborted",ee),$.on("end",se),$.on("finish",J),Z.error!==!1&&$.on("error",R),$.on("close",ee),q?t.nextTick(ee):K!=null&&K.errorEmitted||N!=null&&N.errorEmitted?z||t.nextTick(he):(!te&&(!z||w($))&&(G||E($)===!1)||!we&&(!z||E($))&&(ge||w($)===!1)||N&&$.req&&$.aborted)&&t.nextTick(he);let ye=()=>{M=oe,$.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",se),$.removeListener("error",R),$.removeListener("close",ee)};if(Z.signal&&!q){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||Ye().addAbortListener;let me=D(Z.signal,H),ve=M;M=l((...ae)=>{me[g](),ve.apply($,ae)})}}return ye}function W($,Z,M){let Q=!1,be=oe;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||Ye().addAbortListener;let we=D(Z.signal,be),K=M;M=l((...N)=>{we[g](),K.apply($,N)})}let te=(...we)=>{Q||t.nextTick(()=>M.apply($,we))};return f($[B].promise,te,te),oe}function re($,Z){var M;let Q=!1;return Z===null&&(Z=a),(M=Z)!==null&&M!==void 0&&M.cleanup&&(p(Z.cleanup,"cleanup"),Q=Z.cleanup),new b((be,te)=>{let we=Y($,Z,K=>{Q&&we(),K?te(K):be()})})}e.exports=Y,e.exports.finished=re}),Yt=pe((o,e)=>{le(),ue(),ce();var t=Ut(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:s},AbortError:n}=Ke(),{Symbol:i}=Be(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=mt(),d=i("kDestroy"),p=i("kConstruct");function b(T,B,D){T&&(T.stack,B&&!B.errored&&(B.errored=T),D&&!D.errored&&(D.errored=T))}function f(T,B){let D=this._readableState,U=this._writableState,oe=U||D;return U!=null&&U.destroyed||D!=null&&D.destroyed?(typeof B=="function"&&B(),this):(b(T,U,D),U&&(U.destroyed=!0),D&&(D.destroyed=!0),oe.constructed?g(this,T,B):this.once(d,function(Y){g(this,r(Y,T),B)}),this)}function g(T,B,D){let U=!1;function oe(Y){if(U)return;U=!0;let W=T._readableState,re=T._writableState;b(Y,re,W),re&&(re.closed=!0),W&&(W.closed=!0),typeof D=="function"&&D(Y),Y?t.nextTick(y,T,Y):t.nextTick(w,T)}try{T._destroy(B||null,oe)}catch(Y){oe(Y)}}function y(T,B){m(T,B),w(T)}function w(T){let B=T._readableState,D=T._writableState;D&&(D.closeEmitted=!0),B&&(B.closeEmitted=!0),(D!=null&&D.emitClose||B!=null&&B.emitClose)&&T.emit("close")}function m(T,B){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",B))}function _(){let T=this._readableState,B=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),B&&(B.constructed=!0,B.destroyed=!1,B.closed=!1,B.closeEmitted=!1,B.errored=null,B.errorEmitted=!1,B.finalCalled=!1,B.prefinished=!1,B.ended=B.writable===!1,B.ending=B.writable===!1,B.finished=B.writable===!1)}function x(T,B,D){let U=T._readableState,oe=T._writableState;if(oe!=null&&oe.destroyed||U!=null&&U.destroyed)return this;U!=null&&U.autoDestroy||oe!=null&&oe.autoDestroy?T.destroy(B):B&&(B.stack,oe&&!oe.errored&&(oe.errored=B),U&&!U.errored&&(U.errored=B),D?t.nextTick(m,T,B):m(T,B))}function v(T,B){if(typeof T._construct!="function")return;let D=T._readableState,U=T._writableState;D&&(D.constructed=!1),U&&(U.constructed=!1),T.once(p,B),!(T.listenerCount(p)>1)&&t.nextTick(E,T)}function E(T){let B=!1;function D(U){if(B){x(T,U??new s);return}B=!0;let oe=T._readableState,Y=T._writableState,W=Y||oe;oe&&(oe.constructed=!0),Y&&(Y.constructed=!0),W.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(p)}function A(T){return T?.setHeader&&typeof T.abort=="function"}function C(T){T.emit("close")}function O(T,B){T.emit("error",B),t.nextTick(C,T)}function j(T,B){!T||l(T)||(!B&&!c(T)&&(B=new n),u(T)?(T.socket=null,T.destroy(B)):A(T)?T.abort():A(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(B):typeof T.close=="function"?T.close():B?t.nextTick(O,T,B):t.nextTick(C,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:j,destroy:f,undestroy:_,errorOrDestroy:x}}),yo=pe((o,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Be(),{EventEmitter:s}=(jt(),Le(Et));function n(a){s.call(this,a)}r(n.prototype,s.prototype),r(n,s),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",b),c.on("close",f));let p=!1;function b(){p||(p=!0,a.end())}function f(){p||(p=!0,typeof a.destroy=="function"&&a.destroy())}function g(w){y(),s.listenerCount(this,"error")===0&&this.emit("error",w)}i(c,"error",g),i(a,"error",g);function y(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",b),c.removeListener("close",f),c.removeListener("error",g),a.removeListener("error",g),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}}),Kr=pe((o,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Be(),{AbortError:r,codes:s}=Ke(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:a}=mt(),l=At(),{ERR_INVALID_ARG_TYPE:c}=s,u,d=(p,b)=>{if(typeof p!="object"||!("aborted"in p))throw new c(b,"AbortSignal",p)};e.exports.addAbortSignal=function(p,b){if(d(p,"signal"),!n(b)&&!i(b))throw new c("stream",["ReadableStream","WritableStream","Stream"],b);return e.exports.addAbortSignalNoValidate(p,b)},e.exports.addAbortSignalNoValidate=function(p,b){if(typeof p!="object"||!("aborted"in p))return b;let f=n(b)?()=>{b.destroy(new r(void 0,{cause:p.reason}))}:()=>{b[a](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||Ye().addAbortListener;let g=u(p,f);l(b,g[t])}return b}}),Xc=pe((o,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:s,Uint8Array:n}=Be(),{Buffer:i}=($e(),Le(Fe)),{inspect:a}=Ye();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;)s(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 p=u.data;if(l>p.length)c+=p,l-=p.length;else{l===p.length?(c+=p,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,l),this.head=u,u.data=t(p,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,p=0;do{let b=d.data;if(l>b.length)s(c,b,u-l),l-=b.length;else{l===b.length?(s(c,b,u-l),++p,d.next?this.head=d.next:this.head=this.tail=null):(s(c,new n(b.buffer,b.byteOffset,l),u-l),this.head=d,d.data=b.slice(l));break}++p}while((d=d.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),Gr=pe((o,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Be(),{validateInteger:s}=ur(),{ERR_INVALID_ARG_VALUE:n}=Ke().codes,i=16*1024,a=16;function l(p,b,f){return p.highWaterMark!=null?p.highWaterMark:b?p[f]:null}function c(p){return p?a:i}function u(p,b){s(b,"value",0),p?a=b:i=b}function d(p,b,f,g){let y=l(b,g,f);if(y!=null){if(!r(y)||y<0){let w=g?`options.${f}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),Zc=pe((o,e)=>{le(),ue(),ce();var t=($e(),Le(Fe)),r=t.Buffer;function s(i,a){for(var l in i)a[l]=i[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(s(t,o),o.Buffer=n);function n(i,a,l){return r(i,a,l)}n.prototype=Object.create(r.prototype),s(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)}}),eu=pe(o=>{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 _;;)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(_)return;m=(""+m).toLowerCase(),_=!0}}function s(m){var _=r(m);if(typeof _!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return _||m}o.StringDecoder=n;function n(m){this.encoding=s(m);var _;switch(this.encoding){case"utf16le":this.text=p,this.end=b,_=4;break;case"utf8":this.fillLast=c,_=4;break;case"base64":this.text=f,this.end=g,_=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(_)}n.prototype.write=function(m){if(m.length===0)return"";var _,x;if(this.lastNeed){if(_=this.fillLast(m),_===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?_?_+this.text(m,x):this.text(m,x):_||""},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,_,x){var v=_.length-1;if(v<x)return 0;var E=i(_[v]);return E>=0?(E>0&&(m.lastNeed=E-1),E):--v<x||E===-2?0:(E=i(_[v]),E>=0?(E>0&&(m.lastNeed=E-2),E):--v<x||E===-2?0:(E=i(_[v]),E>=0?(E>0&&(E===2?E=0:m.lastNeed=E-3),E):0))}function l(m,_,x){if((_[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&_.length>1){if((_[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&_.length>2&&(_[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var _=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,_,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,_,0,m.length),this.lastNeed-=m.length}function u(m,_){var x=a(this,m,_);if(!this.lastNeed)return m.toString("utf8",_);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",_,v)}function d(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+"�":_}function p(m,_){if((m.length-_)%2===0){var x=m.toString("utf16le",_);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",_,m.length-1)}function b(m){var _=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return _+this.lastChar.toString("utf16le",0,x)}return _}function f(m,_){var x=(m.length-_)%3;return x===0?m.toString("base64",_):(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",_,m.length-x))}function g(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+this.lastChar.toString("base64",0,3-this.lastNeed):_}function y(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),Ta=pe((o,e)=>{le(),ue(),ce();var t=Ut(),{PromisePrototypeThen:r,SymbolAsyncIterator:s,SymbolIterator:n}=Be(),{Buffer:i}=($e(),Le(Fe)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ke().codes;function c(u,d,p){let b;if(typeof d=="string"||d instanceof i)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let f;if(d&&d[s])f=!0,b=d[s]();else if(d&&d[n])f=!1,b=d[n]();else throw new a("iterable",["Iterable"],d);let g=new u({objectMode:!0,highWaterMark:1,...p}),y=!1;g._read=function(){y||(y=!0,m())},g._destroy=function(_,x){r(w(_),()=>t.nextTick(x,_),v=>t.nextTick(x,v||_))};async function w(_){let x=_!=null,v=typeof b.throw=="function";if(x&&v){let{value:E,done:S}=await b.throw(_);if(await E,S)return}if(typeof b.return=="function"){let{value:E}=await b.return();await E}}async function m(){for(;;){try{let{value:_,done:x}=f?await b.next():b.next();if(x)g.push(null);else{let v=_&&typeof _.then=="function"?await _:_;if(v===null)throw y=!1,new l;if(g.push(v))continue;y=!1}}catch(_){g.destroy(_)}break}}return g}e.exports=c}),Yr=pe((o,e)=>{le(),ue(),ce();var t=Ut(),{ArrayPrototypeIndexOf:r,NumberIsInteger:s,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:b,Symbol:f}=Be();e.exports=ae,ae.ReadableState=ve;var{EventEmitter:g}=(jt(),Le(Et)),{Stream:y,prependListener:w}=yo(),{Buffer:m}=($e(),Le(Fe)),{addAbortSignal:_}=Kr(),x=At(),v=Ye().debuglog("stream",P=>{v=P}),E=Xc(),S=Yt(),{getHighWaterMark:A,getDefaultHighWaterMark:C}=Gr(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:j,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:B,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:oe}=Ke(),{validateObject:Y}=ur(),W=f("kPaused"),{StringDecoder:re}=eu(),$=Ta();c(ae.prototype,y.prototype),c(ae,y);var Z=()=>{},{errorOrDestroy:M}=S,Q=1,be=2,te=4,we=8,K=16,N=32,ne=64,z=128,G=256,J=512,ge=1024,se=2048,R=4096,q=8192,ee=16384,he=32768,fe=65536,ye=1<<17,H=1<<18;function me(P){return{enumerable:!1,get(){return(this.state&P)!==0},set(L){L?this.state|=P:this.state&=~P}}}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(z),readableListening:me(G),resumeScheduled:me(J),errorEmitted:me(ge),emitClose:me(se),autoDestroy:me(R),destroyed:me(q),closed:me(ee),closeEmitted:me(he),multiAwaitDrain:me(fe),readingMore:me(ye),dataEmitted:me(H)});function ve(P,L,_e){typeof _e!="boolean"&&(_e=L instanceof ft()),this.state=se|R|K|N,P&&P.objectMode&&(this.state|=Q),_e&&P&&P.readableObjectMode&&(this.state|=Q),this.highWaterMark=P?A(this,P,"readableHighWaterMark",_e):C(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[W]=null,P&&P.emitClose===!1&&(this.state&=~se),P&&P.autoDestroy===!1&&(this.state&=~R),this.errored=null,this.defaultEncoding=P&&P.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,P&&P.encoding&&(this.decoder=new re(P.encoding),this.encoding=P.encoding)}function ae(P){if(!(this instanceof ae))return new ae(P);let L=this instanceof ft();this._readableState=new ve(P,this,L),P&&(typeof P.read=="function"&&(this._read=P.read),typeof P.destroy=="function"&&(this._destroy=P.destroy),typeof P.construct=="function"&&(this._construct=P.construct),P.signal&&!L&&_(P.signal,this)),y.call(this,P),S.construct(this,()=>{this._readableState.needReadable&&V(this,this._readableState)})}ae.prototype.destroy=S.destroy,ae.prototype._undestroy=S.undestroy,ae.prototype._destroy=function(P,L){L(P)},ae.prototype[g.captureRejectionSymbol]=function(P){this.destroy(P)},ae.prototype[p]=function(){let P;return this.destroyed||(P=this.readableEnded?null:new oe,this.destroy(P)),new u((L,_e)=>x(this,xe=>xe&&xe!==P?_e(xe):L(null)))},ae.prototype.push=function(P,L){return Oe(this,P,L,!1)},ae.prototype.unshift=function(P,L){return Oe(this,P,L,!0)};function Oe(P,L,_e,xe){v("readableAddChunk",L);let Se=P._readableState,De;if((Se.state&Q)===0&&(typeof L=="string"?(_e=_e||Se.defaultEncoding,Se.encoding!==_e&&(xe&&Se.encoding?L=m.from(L,_e).toString(Se.encoding):(L=m.from(L,_e),_e=""))):L instanceof m?_e="":y._isUint8Array(L)?(L=y._uint8ArrayToBuffer(L),_e=""):L!=null&&(De=new j("chunk",["string","Buffer","Uint8Array"],L))),De)M(P,De);else if(L===null)Se.state&=~we,X(P,Se);else if((Se.state&Q)!==0||L&&L.length>0)if(xe)if((Se.state&te)!==0)M(P,new U);else{if(Se.destroyed||Se.errored)return!1;h(P,Se,L,!0)}else if(Se.ended)M(P,new D);else{if(Se.destroyed||Se.errored)return!1;Se.state&=~we,Se.decoder&&!_e?(L=Se.decoder.write(L),Se.objectMode||L.length!==0?h(P,Se,L,!1):V(P,Se)):h(P,Se,L,!1)}else xe||(Se.state&=~we,V(P,Se));return!Se.ended&&(Se.length<Se.highWaterMark||Se.length===0)}function h(P,L,_e,xe){L.flowing&&L.length===0&&!L.sync&&P.listenerCount("data")>0?((L.state&fe)!==0?L.awaitDrainWriters.clear():L.awaitDrainWriters=null,L.dataEmitted=!0,P.emit("data",_e)):(L.length+=L.objectMode?1:_e.length,xe?L.buffer.unshift(_e):L.buffer.push(_e),(L.state&ne)!==0&&de(P)),V(P,L)}ae.prototype.isPaused=function(){let P=this._readableState;return P[W]===!0||P.flowing===!1},ae.prototype.setEncoding=function(P){let L=new re(P);this._readableState.decoder=L,this._readableState.encoding=this._readableState.decoder.encoding;let _e=this._readableState.buffer,xe="";for(let Se of _e)xe+=L.write(Se);return _e.clear(),xe!==""&&_e.push(xe),this._readableState.length=xe.length,this};var k=1073741824;function I(P){if(P>k)throw new B("size","<= 1GiB",P);return P--,P|=P>>>1,P|=P>>>2,P|=P>>>4,P|=P>>>8,P|=P>>>16,P++,P}function F(P,L){return P<=0||L.length===0&&L.ended?0:(L.state&Q)!==0?1:n(P)?L.flowing&&L.length?L.buffer.first().length:L.length:P<=L.length?P:L.ended?L.length:0}ae.prototype.read=function(P){v("read",P),P===void 0?P=NaN:s(P)||(P=i(P,10));let L=this._readableState,_e=P;if(P>L.highWaterMark&&(L.highWaterMark=I(P)),P!==0&&(L.state&=~z),P===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?nt(this):de(this),null;if(P=F(P,L),P===0&&L.ended)return L.length===0&&nt(this),null;let xe=(L.state&ne)!==0;if(v("need readable",xe),(L.length===0||L.length-P<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||(P=F(_e,L))}let Se;return P>0?Se=Ft(P,L):Se=null,Se===null?(L.needReadable=L.length<=L.highWaterMark,P=0):(L.length-=P,L.multiAwaitDrain?L.awaitDrainWriters.clear():L.awaitDrainWriters=null),L.length===0&&(L.ended||(L.needReadable=!0),_e!==P&&L.ended&&nt(this)),Se!==null&&!L.errorEmitted&&!L.closeEmitted&&(L.dataEmitted=!0,this.emit("data",Se)),Se};function X(P,L){if(v("onEofChunk"),!L.ended){if(L.decoder){let _e=L.decoder.end();_e&&_e.length&&(L.buffer.push(_e),L.length+=L.objectMode?1:_e.length)}L.ended=!0,L.sync?de(P):(L.needReadable=!1,L.emittedReadable=!0,ke(P))}}function de(P){let L=P._readableState;v("emitReadable",L.needReadable,L.emittedReadable),L.needReadable=!1,L.emittedReadable||(v("emitReadable",L.flowing),L.emittedReadable=!0,t.nextTick(ke,P))}function ke(P){let L=P._readableState;v("emitReadable_",L.destroyed,L.length,L.ended),!L.destroyed&&!L.errored&&(L.length||L.ended)&&(P.emit("readable"),L.emittedReadable=!1),L.needReadable=!L.flowing&&!L.ended&&L.length<=L.highWaterMark,tt(P)}function V(P,L){!L.readingMore&&L.constructed&&(L.readingMore=!0,t.nextTick(ie,P,L))}function ie(P,L){for(;!L.reading&&!L.ended&&(L.length<L.highWaterMark||L.flowing&&L.length===0);){let _e=L.length;if(v("maybeReadMore read 0"),P.read(0),_e===L.length)break}L.readingMore=!1}ae.prototype._read=function(P){throw new T("_read()")},ae.prototype.pipe=function(P,L){let _e=this,xe=this._readableState;xe.pipes.length===1&&(xe.multiAwaitDrain||(xe.multiAwaitDrain=!0,xe.awaitDrainWriters=new d(xe.awaitDrainWriters?[xe.awaitDrainWriters]:[]))),xe.pipes.push(P),v("pipe count=%d opts=%j",xe.pipes.length,L);let Se=(!L||L.end!==!1)&&P!==t.stdout&&P!==t.stderr?Ve:Ct;xe.endEmitted?t.nextTick(Se):_e.once("end",Se),P.on("unpipe",De);function De(ot,lt){v("onunpipe"),ot===_e&<&<.hasUnpiped===!1&&(lt.hasUnpiped=!0,er())}function Ve(){v("onend"),P.end()}let Ze,Zt=!1;function er(){v("cleanup"),P.removeListener("close",it),P.removeListener("finish",yt),Ze&&P.removeListener("drain",Ze),P.removeListener("error",Tt),P.removeListener("unpipe",De),_e.removeListener("end",Ve),_e.removeListener("end",Ct),_e.removeListener("data",fr),Zt=!0,Ze&&xe.awaitDrainWriters&&(!P._writableState||P._writableState.needDrain)&&Ze()}function tr(){Zt||(xe.pipes.length===1&&xe.pipes[0]===P?(v("false write response, pause",0),xe.awaitDrainWriters=P,xe.multiAwaitDrain=!1):xe.pipes.length>1&&xe.pipes.includes(P)&&(v("false write response, pause",xe.awaitDrainWriters.size),xe.awaitDrainWriters.add(P)),_e.pause()),Ze||(Ze=Ae(_e,P),P.on("drain",Ze))}_e.on("data",fr);function fr(ot){v("ondata");let lt=P.write(ot);v("dest.write",lt),lt===!1&&tr()}function Tt(ot){if(v("onerror",ot),Ct(),P.removeListener("error",Tt),P.listenerCount("error")===0){let lt=P._writableState||P._readableState;lt&&!lt.errorEmitted?M(P,ot):P.emit("error",ot)}}w(P,"error",Tt);function it(){P.removeListener("finish",yt),Ct()}P.once("close",it);function yt(){v("onfinish"),P.removeListener("close",it),Ct()}P.once("finish",yt);function Ct(){v("unpipe"),_e.unpipe(P)}return P.emit("pipe",_e),P.writableNeedDrain===!0?tr():xe.flowing||(v("pipe resume"),_e.resume()),P};function Ae(P,L){return function(){let _e=P._readableState;_e.awaitDrainWriters===L?(v("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(v("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(L)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&P.listenerCount("data")&&P.resume()}}ae.prototype.unpipe=function(P){let L=this._readableState,_e={hasUnpiped:!1};if(L.pipes.length===0)return this;if(!P){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,P);return xe===-1?this:(L.pipes.splice(xe,1),L.pipes.length===0&&this.pause(),P.emit("unpipe",this,_e),this)},ae.prototype.on=function(P,L){let _e=y.prototype.on.call(this,P,L),xe=this._readableState;return P==="data"?(xe.readableListening=this.listenerCount("readable")>0,xe.flowing!==!1&&this.resume()):P==="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(Pe,this)),_e},ae.prototype.addListener=ae.prototype.on,ae.prototype.removeListener=function(P,L){let _e=y.prototype.removeListener.call(this,P,L);return P==="readable"&&t.nextTick(Ie,this),_e},ae.prototype.off=ae.prototype.removeListener,ae.prototype.removeAllListeners=function(P){let L=y.prototype.removeAllListeners.apply(this,arguments);return(P==="readable"||P===void 0)&&t.nextTick(Ie,this),L};function Ie(P){let L=P._readableState;L.readableListening=P.listenerCount("readable")>0,L.resumeScheduled&&L[W]===!1?L.flowing=!0:P.listenerCount("data")>0?P.resume():L.readableListening||(L.flowing=null)}function Pe(P){v("readable nexttick read 0"),P.read(0)}ae.prototype.resume=function(){let P=this._readableState;return P.flowing||(v("resume"),P.flowing=!P.readableListening,Me(this,P)),P[W]=!1,this};function Me(P,L){L.resumeScheduled||(L.resumeScheduled=!0,t.nextTick(et,P,L))}function et(P,L){v("resume",L.reading),L.reading||P.read(0),L.resumeScheduled=!1,P.emit("resume"),tt(P),L.flowing&&!L.reading&&P.read(0)}ae.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[W]=!0,this};function tt(P){let L=P._readableState;for(v("flow",L.flowing);L.flowing&&P.read()!==null;);}ae.prototype.wrap=function(P){let L=!1;P.on("data",xe=>{!this.push(xe)&&P.pause&&(L=!0,P.pause())}),P.on("end",()=>{this.push(null)}),P.on("error",xe=>{M(this,xe)}),P.on("close",()=>{this.destroy()}),P.on("destroy",()=>{this.destroy()}),this._read=()=>{L&&P.resume&&(L=!1,P.resume())};let _e=l(P);for(let xe=1;xe<_e.length;xe++){let Se=_e[xe];this[Se]===void 0&&typeof P[Se]=="function"&&(this[Se]=P[Se].bind(P))}return this},ae.prototype[b]=function(){return qe(this)},ae.prototype.iterator=function(P){return P!==void 0&&Y(P,"options"),qe(this,P)};function qe(P,L){typeof P.read!="function"&&(P=ae.wrap(P,{objectMode:!0}));let _e=rt(P,L);return _e.stream=P,_e}async function*rt(P,L){let _e=Z;function xe(Ve){this===P?(_e(),_e=Z):_e=Ve}P.on("readable",xe);let Se,De=x(P,{writable:!1},Ve=>{Se=Ve?O(Se,Ve):null,_e(),_e=Z});try{for(;;){let Ve=P.destroyed?null:P.read();if(Ve!==null)yield Ve;else{if(Se)throw Se;if(Se===null)return;await new u(xe)}}}catch(Ve){throw Se=O(Se,Ve),Se}finally{(Se||L?.destroyOnReturn!==!1)&&(Se===void 0||P._readableState.autoDestroy)?S.destroyer(P,null):(P.off("readable",xe),De())}}a(ae.prototype,{readable:{__proto__:null,get(){let P=this._readableState;return!!P&&P.readable!==!1&&!P.destroyed&&!P.errorEmitted&&!P.endEmitted},set(P){this._readableState&&(this._readableState.readable=!!P)}},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(P){this._readableState&&(this._readableState.flowing=P)}},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(P){this._readableState&&(this._readableState.destroyed=P)}},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[W]!==!1},set(P){this[W]=!!P}}}),ae._fromList=Ft;function Ft(P,L){if(L.length===0)return null;let _e;return L.objectMode?_e=L.buffer.shift():!P||P>=L.length?(L.decoder?_e=L.buffer.join(""):L.buffer.length===1?_e=L.buffer.first():_e=L.buffer.concat(L.length),L.buffer.clear()):_e=L.buffer.consume(P,L.decoder),_e}function nt(P){let L=P._readableState;v("endReadable",L.endEmitted),L.endEmitted||(L.ended=!0,t.nextTick(Qe,L,P))}function Qe(P,L){if(v("endReadableNT",P.endEmitted,P.length),!P.errored&&!P.closeEmitted&&!P.endEmitted&&P.length===0){if(P.endEmitted=!0,L.emit("end"),L.writable&&L.allowHalfOpen===!1)t.nextTick(hr,L);else if(P.autoDestroy){let _e=L._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&L.destroy()}}}function hr(P){P.writable&&!P.writableEnded&&!P.destroyed&&P.end()}ae.from=function(P,L){return $(ae,P,L)};var $t;function Xt(){return $t===void 0&&($t={}),$t}ae.fromWeb=function(P,L){return Xt().newStreamReadableFromReadableStream(P,L)},ae.toWeb=function(P,L){return Xt().newReadableStreamFromStreamReadable(P,L)},ae.wrap=function(P,L){var _e,xe;return new ae({objectMode:(_e=(xe=P.readableObjectMode)!==null&&xe!==void 0?xe:P.objectMode)!==null&&_e!==void 0?_e:!0,...L,destroy(Se,De){S.destroyer(P,Se),De(Se)}}).wrap(P)}}),vo=pe((o,e)=>{le(),ue(),ce();var t=Ut(),{ArrayPrototypeSlice:r,Error:s,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=Be();e.exports=Y,Y.WritableState=U;var{EventEmitter:p}=(jt(),Le(Et)),b=yo().Stream,{Buffer:f}=($e(),Le(Fe)),g=Yt(),{addAbortSignal:y}=Kr(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=Gr(),{ERR_INVALID_ARG_TYPE:_,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:E,ERR_STREAM_DESTROYED:S,ERR_STREAM_ALREADY_FINISHED:A,ERR_STREAM_NULL_VALUES:C,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:j}=Ke().codes,{errorOrDestroy:T}=g;l(Y.prototype,b.prototype),l(Y,b);function B(){}var D=u("kOnFinished");function U(R,q,ee){typeof ee!="boolean"&&(ee=q 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,q),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,oe(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 oe(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 q=this instanceof ft();if(!q&&!n(Y,this))return new Y(R);this._writableState=new U(R,this,q),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)),b.call(this,R),g.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),z(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 W(R,q,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"&&!f.isEncoding(ee))throw new j(ee);typeof he!="function"&&(he=B)}if(q===null)throw new C;if(!fe.objectMode)if(typeof q=="string")fe.decodeStrings!==!1&&(q=f.from(q,ee),ee="buffer");else if(q instanceof f)ee="buffer";else if(b._isUint8Array(q))q=b._uint8ArrayToBuffer(q),ee="buffer";else throw new _("chunk",["string","Buffer","Uint8Array"],q);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,q,ee,he))}Y.prototype.write=function(R,q,ee){return W(this,R,q,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)),!f.isEncoding(R))throw new j(R);return this._writableState.defaultEncoding=R,this};function re(R,q,ee,he,fe){let ye=q.objectMode?1:ee.length;q.length+=ye;let H=q.length<q.highWaterMark;return H||(q.needDrain=!0),q.writing||q.corked||q.errored||!q.constructed?(q.buffered.push({chunk:ee,encoding:he,callback:fe}),q.allBuffers&&he!=="buffer"&&(q.allBuffers=!1),q.allNoop&&fe!==B&&(q.allNoop=!1)):(q.writelen=ye,q.writecb=fe,q.writing=!0,q.sync=!0,R._write(ee,he,q.onwrite),q.sync=!1),H&&!q.errored&&!q.destroyed}function $(R,q,ee,he,fe,ye,H){q.writelen=he,q.writecb=H,q.writing=!0,q.sync=!0,q.destroyed?q.onwrite(new S("write")):ee?R._writev(fe,q.onwrite):R._write(fe,ye,q.onwrite),q.sync=!1}function Z(R,q,ee,he){--q.pendingcb,he(ee),te(q),T(R,ee)}function M(R,q){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,q?(q.stack,ee.errored||(ee.errored=q),R._readableState&&!R._readableState.errored&&(R._readableState.errored=q),he?t.nextTick(Z,R,ee,q,fe):Z(R,ee,q,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:q,count:ee,cb:he}){return q.afterWriteTickInfo=null,be(R,q,ee,he)}function be(R,q,ee,he){for(!q.ending&&!R.destroyed&&q.length===0&&q.needDrain&&(q.needDrain=!1,R.emit("drain"));ee-- >0;)q.pendingcb--,he();q.destroyed&&te(q),z(R,q)}function te(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var q;let{chunk:ye,callback:H}=R.buffered[fe],me=R.objectMode?1:ye.length;R.length-=me,H((q=R.errored)!==null&&q!==void 0?q: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"))}oe(R)}function we(R,q){if(q.corked||q.bufferProcessing||q.destroyed||!q.constructed)return;let{buffered:ee,bufferedIndex:he,objectMode:fe}=q,ye=ee.length-he;if(!ye)return;let H=he;if(q.bufferProcessing=!0,ye>1&&R._writev){q.pendingcb-=ye-1;let me=q.allNoop?B:ae=>{for(let Oe=H;Oe<ee.length;++Oe)ee[Oe].callback(ae)},ve=q.allNoop&&H===0?ee:r(ee,H);ve.allBuffers=q.allBuffers,$(R,q,!0,q.length,ve,"",me),oe(q)}else{do{let{chunk:me,encoding:ve,callback:ae}=ee[H];ee[H++]=null;let Oe=fe?1:me.length;$(R,q,!1,Oe,me,ve,ae)}while(H<ee.length&&!q.writing);H===ee.length?oe(q):H>256?(ee.splice(0,H),q.bufferedIndex=0):q.bufferedIndex=H}q.bufferProcessing=!1}Y.prototype._write=function(R,q,ee){if(this._writev)this._writev([{chunk:R,encoding:q}],ee);else throw new x("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,q,ee){let he=this._writableState;typeof R=="function"?(ee=R,R=null,q=null):typeof q=="function"&&(ee=q,q=null);let fe;if(R!=null){let ye=W(this,R,q);ye instanceof s&&(fe=ye)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,z(this,he,!0),he.ended=!0):he.finished?fe=new A("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,q){let ee=!1;function he(fe){if(ee){T(R,fe??v());return}if(ee=!0,q.pendingcb--,fe){let ye=q[D].splice(0);for(let H=0;H<ye.length;H++)ye[H](fe);T(R,fe,q.sync)}else K(q)&&(q.prefinished=!0,R.emit("prefinish"),q.pendingcb++,t.nextTick(G,R,q))}q.sync=!0,q.pendingcb++;try{R._final(he)}catch(fe){he(fe)}q.sync=!1}function ne(R,q){!q.prefinished&&!q.finalCalled&&(typeof R._final=="function"&&!q.destroyed?(q.finalCalled=!0,N(R,q)):(q.prefinished=!0,R.emit("prefinish")))}function z(R,q,ee){K(q)&&(ne(R,q),q.pendingcb===0&&(ee?(q.pendingcb++,t.nextTick((he,fe)=>{K(fe)?G(he,fe):fe.pendingcb--},R,q)):K(q)&&(q.pendingcb++,G(R,q))))}function G(R,q){q.pendingcb--,q.finished=!0;let ee=q[D].splice(0);for(let he=0;he<ee.length;he++)ee[he]();if(R.emit("finish"),q.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=g.destroy;Y.prototype.destroy=function(R,q){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[D].length)&&t.nextTick(te,ee),J.call(this,R,q),this},Y.prototype._undestroy=g.undestroy,Y.prototype._destroy=function(R,q){q(R)},Y.prototype[p.captureRejectionSymbol]=function(R){this.destroy(R)};var ge;function se(){return ge===void 0&&(ge={}),ge}Y.fromWeb=function(R,q){return se().newStreamWritableFromWritableStream(R,q)},Y.toWeb=function(R){return se().newWritableStreamFromStreamWritable(R)}}),tu=pe((o,e)=>{le(),ue(),ce();var t=Ut(),r=($e(),Le(Fe)),{isReadable:s,isWritable:n,isIterable:i,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=mt(),b=At(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:g,ERR_INVALID_RETURN_VALUE:y}}=Ke(),{destroyer:w}=Yt(),m=ft(),_=Yr(),x=vo(),{createDeferredPromise:v}=Ye(),E=Ta(),S=globalThis.Blob||r.Blob,A=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},C=globalThis.AbortController||cr().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,oe){if(u(U))return U;if(l(U))return B({readable:U});if(c(U))return B({writable:U});if(a(U))return B({writable:!1,readable:!1});if(d(U))return B({readable:_.fromWeb(U)});if(p(U))return B({writable:x.fromWeb(U)});if(typeof U=="function"){let{value:W,write:re,final:$,destroy:Z}=T(U);if(i(W))return E(j,W,{objectMode:!0,write:re,final:$,destroy:Z});let M=W?.then;if(typeof M=="function"){let Q,be=O(M,W,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",oe,W)}if(A(U))return D(U.arrayBuffer());if(i(U))return E(j,U,{objectMode:!0,writable:!1});if(d(U?.readable)&&p(U?.writable))return j.fromWeb(U);if(typeof U?.writable=="object"||typeof U?.readable=="object"){let W=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 B({readable:W,writable:re})}let Y=U?.then;if(typeof Y=="function"){let W;return O(Y,U,re=>{re!=null&&W.push(re),W.push(null)},re=>{w(W,re)}),W=new j({objectMode:!0,writable:!1,read(){}})}throw new g(oe,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(D){let{promise:U,resolve:oe}=v(),Y=new C,W=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(W.aborted)throw new f(void 0,{cause:W.reason});({promise:U,resolve:oe}=v()),yield $}})(),{signal:W}),write(re,$,Z){let M=oe;oe=null,M({chunk:re,done:!1,cb:Z})},final(re){let $=oe;oe=null,$({done:!0,cb:re})},destroy(re,$){Y.abort(),$(re)}}}function B(D){let U=D.readable&&typeof D.readable.read!="function"?_.wrap(D.readable):D.readable,oe=D.writable,Y=!!s(U),W=!!n(oe),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:!!(oe!=null&&oe.writableObjectMode),readable:Y,writable:W}),W&&(b(oe,te=>{W=!1,te&&w(U,te),be(te)}),Q._write=function(te,we,K){oe.write(te,we)?K():re=K},Q._final=function(te){oe.end(),$=te},oe.on("drain",function(){if(re){let te=re;re=null,te()}}),oe.on("finish",function(){if($){let te=$;$=null,te()}})),Y&&(b(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 f),Z=null,re=null,$=null,M===null?we(te):(M=we,w(oe,te),w(U,te))},Q}}),ft=pe((o,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:s,ObjectSetPrototypeOf:n}=Be();e.exports=l;var i=Yr(),a=vo();n(l.prototype,i.prototype),n(l,i);{let p=s(a.prototype);for(let b=0;b<p.length;b++){let f=p[b];l.prototype[f]||(l.prototype[f]=a.prototype[f])}}function l(p){if(!(this instanceof l))return new l(p);i.call(this,p),a.call(this,p),p?(this.allowHalfOpen=p.allowHalfOpen!==!1,p.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),p.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(p){this._readableState&&this._writableState&&(this._readableState.destroyed=p,this._writableState.destroyed=p)}}});var c;function u(){return c===void 0&&(c={}),c}l.fromWeb=function(p,b){return u().newStreamDuplexFromReadableWritablePair(p,b)},l.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var d;l.from=function(p){return d||(d=tu()),d(p,"body")}}),Ca=pe((o,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Be();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:s}=Ke().codes,n=ft(),{getHighWaterMark:i}=Gr();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(d){if(!(this instanceof l))return new l(d);let p=d?i(this,d,"readableHighWaterMark",!0):null;p===0&&(d={...d,highWaterMark:null,readableHighWaterMark:p,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((p,b)=>{if(p){d?d(p):this.destroy(p);return}b!=null&&this.push(b),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,p,b){throw new s("_transform()")},l.prototype._write=function(d,p,b){let f=this._readableState,g=this._writableState,y=f.length;this._transform(d,p,(w,m)=>{if(w){b(w);return}m!=null&&this.push(m),g.ended||y===f.length||f.length<f.highWaterMark?b():this[a]=b})},l.prototype._read=function(){if(this[a]){let d=this[a];this[a]=null,d()}}}),Pa=pe((o,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Be();e.exports=s;var r=Ca();t(s.prototype,r.prototype),t(s,r);function s(n){if(!(this instanceof s))return new s(n);r.call(this,n)}s.prototype._transform=function(n,i,a){a(null,n)}}),wo=pe((o,e)=>{le(),ue(),ce();var t=Ut(),{ArrayIsArray:r,Promise:s,SymbolAsyncIterator:n,SymbolDispose:i}=Be(),a=At(),{once:l}=Ye(),c=Yt(),u=ft(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:b,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:g,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ke(),{validateFunction:m,validateAbortSignal:_}=ur(),{isIterable:x,isReadable:v,isReadableNodeStream:E,isNodeStream:S,isTransformStream:A,isWebStream:C,isReadableStream:O,isReadableFinished:j}=mt(),T=globalThis.AbortController||cr().AbortController,B,D,U;function oe(te,we,K){let N=!1;te.on("close",()=>{N=!0});let ne=a(te,{readable:we,writable:K},z=>{N=!z});return{destroy:z=>{N||(N=!0,c.destroyer(te,z||new g("pipe")))},cleanup:ne}}function Y(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function W(te){if(x(te))return te;if(E(te))return re(te);throw new p("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){D||(D=Yr()),yield*D.prototype[n].call(te)}async function $(te,we,K,{end:N}){let ne,z=null,G=se=>{if(se&&(ne=se),z){let R=z;z=null,R()}},J=()=>new s((se,R)=>{ne?R(ne):z=()=>{ne?R(ne):se()}});we.on("drain",G);let ge=a(we,{readable:!1},G);try{we.writableNeedDrain&&await J();for await(let se of te)we.write(se)||await J();N&&(we.end(),await J()),K()}catch(se){K(ne!==se?d(ne,se):se)}finally{ge(),we.off("drain",G)}}async function Z(te,we,K,{end:N}){A(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let z of te)await ne.ready,ne.write(z).catch(()=>{});await ne.ready,N&&await ne.close(),K()}catch(z){try{await ne.abort(z),K(z)}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 f("streams");let N=new T,ne=N.signal,z=K?.signal,G=[];_(z,"options.signal");function J(){fe(new w)}U=U||Ye().addAbortListener;let ge;z&&(ge=U(z,J));let se,R,q=[],ee=0;function he(ve){fe(ve,--ee===0)}function fe(ve,ae){var Oe;if(ve&&(!se||se.code==="ERR_STREAM_PREMATURE_CLOSE")&&(se=ve),!(!se&&!ae)){for(;q.length;)q.shift()(se);(Oe=ge)===null||Oe===void 0||Oe[i](),N.abort(),ae&&(se||G.forEach(h=>h()),t.nextTick(we,se,R))}}let ye;for(let ve=0;ve<te.length;ve++){let ae=te[ve],Oe=ve<te.length-1,h=ve>0,k=Oe||K?.end!==!1,I=ve===te.length-1;if(S(ae)){let F=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(X)};if(k){let{destroy:X,cleanup:de}=oe(ae,Oe,h);q.push(X),v(ae)&&I&&G.push(de)}ae.on("error",F),v(ae)&&I&&G.push(()=>{ae.removeListener("error",F)})}if(ve===0)if(typeof ae=="function"){if(ye=ae({signal:ne}),!x(ye))throw new b("Iterable, AsyncIterable or Stream","source",ye)}else x(ae)||E(ae)||A(ae)?ye=ae:ye=u.from(ae);else if(typeof ae=="function"){if(A(ye)){var H;ye=W((H=ye)===null||H===void 0?void 0:H.readable)}else ye=W(ye);if(ye=ae(ye,{signal:ne}),Oe){if(!x(ye,!0))throw new b("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;B||(B=Pa());let F=new B({objectMode:!0}),X=(me=ye)===null||me===void 0?void 0:me.then;if(typeof X=="function")ee++,X.call(ye,V=>{R=V,V!=null&&F.write(V),k&&F.end(),t.nextTick(he)},V=>{F.destroy(V),t.nextTick(he,V)});else if(x(ye,!0))ee++,$(ye,F,he,{end:k});else if(O(ye)||A(ye)){let V=ye.readable||ye;ee++,$(V,F,he,{end:k})}else throw new b("AsyncIterable or Promise","destination",ye);ye=F;let{destroy:de,cleanup:ke}=oe(ye,!1,!0);q.push(de),I&&G.push(ke)}}else if(S(ae)){if(E(ye)){ee+=2;let F=be(ye,ae,he,{end:k});v(ae)&&I&&G.push(F)}else if(A(ye)||O(ye)){let F=ye.readable||ye;ee++,$(F,ae,he,{end:k})}else if(x(ye))ee++,$(ye,ae,he,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else if(C(ae)){if(E(ye))ee++,Z(W(ye),ae,he,{end:k});else if(O(ye)||x(ye))ee++,Z(ye,ae,he,{end:k});else if(A(ye))ee++,Z(ye.readable,ae,he,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else ye=u.from(ae)}return(ne!=null&&ne.aborted||z!=null&&z.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 z=function(){ne=!0,we.end()};j(te)?t.nextTick(z):te.once("end",z)}else K();return a(te,{readable:!0,writable:!1},z=>{let G=te._readableState;z&&z.code==="ERR_STREAM_PREMATURE_CLOSE"&&G&&G.ended&&!G.errored&&!G.errorEmitted?te.once("end",K).once("error",K):K(z)}),a(we,{readable:!1,writable:!0},K)}e.exports={pipelineImpl:Q,pipeline:M}}),Oa=pe((o,e)=>{le(),ue(),ce();var{pipeline:t}=wo(),r=ft(),{destroyer:s}=Yt(),{isNodeStream:n,isReadable:i,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=mt(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:b,ERR_MISSING_ARGS:f}}=Ke(),g=At();e.exports=function(...y){if(y.length===0)throw new f("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 b(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(y[T])||u(y[T])||c(y[T])))throw new b(`streams[${T}]`,w[T],"must be writable")}let m,_,x,v,E;function S(T){let B=v;v=null,B?B(T):T?E.destroy(T):!j&&!O&&E.destroy()}let A=y[0],C=t(y,S),O=!!(a(A)||u(A)||c(A)),j=!!(i(C)||d(C)||c(C));if(E=new r({writableObjectMode:!!(A!=null&&A.writableObjectMode),readableObjectMode:!!(C!=null&&C.readableObjectMode),writable:O,readable:j}),O){if(n(A))E._write=function(B,D,U){A.write(B,D)?U():m=U},E._final=function(B){A.end(),_=B},A.on("drain",function(){if(m){let B=m;m=null,B()}});else if(l(A)){let B=(c(A)?A.writable:A).getWriter();E._write=async function(D,U,oe){try{await B.ready,B.write(D).catch(()=>{}),oe()}catch(Y){oe(Y)}},E._final=async function(D){try{await B.ready,B.close().catch(()=>{}),_=D}catch(U){D(U)}}}let T=c(C)?C.readable:C;g(T,()=>{if(_){let B=_;_=null,B()}})}if(j){if(n(C))C.on("readable",function(){if(x){let T=x;x=null,T()}}),C.on("end",function(){E.push(null)}),E._read=function(){for(;;){let T=C.read();if(T===null){x=E._read;return}if(!E.push(T))return}};else if(l(C)){let T=(c(C)?C.readable:C).getReader();E._read=async function(){for(;;)try{let{value:B,done:D}=await T.read();if(!E.push(B))return;if(D){E.push(null);return}}catch{return}}}}return E._destroy=function(T,B){!T&&v!==null&&(T=new p),x=null,m=null,_=null,v===null?B(T):(v=B,n(C)&&s(C,T))},E}}),ru=pe((o,e)=>{le(),ue(),ce();var t=globalThis.AbortController||cr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:s,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:i},AbortError:a}=Ke(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=ur(),d=Be().Symbol("kWeak"),p=Be().Symbol("kResistStopPropagation"),{finished:b}=At(),f=Oa(),{addAbortSignalNoValidate:g}=Kr(),{isWritable:y,isNodeStream:w}=mt(),{deprecate:m}=Ye(),{ArrayPrototypePush:_,Boolean:x,MathFloor:v,Number:E,NumberIsNaN:S,Promise:A,PromiseReject:C,PromiseResolve:O,PromisePrototypeThen:j,Symbol:T}=Be(),B=T("kEmpty"),D=T("kEof");function U(z,G){if(G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),w(z)&&!y(z))throw new r("stream",z,"must be writable");let J=f(this,z);return G!=null&&G.signal&&g(G.signal,J),J}function oe(z,G){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);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 se=Ye().AbortSignalAny([G?.signal].filter(x)),R=this,q=[],ee={signal:se},he,fe,ye=!1,H=0;function me(){ye=!0,ve()}function ve(){H-=1,ae()}function ae(){fe&&!ye&&H<J&&q.length<ge&&(fe(),fe=null)}async function Oe(){try{for await(let h of R){if(ye)return;if(se.aborted)throw new a;try{if(h=z(h,ee),h===B)continue;h=O(h)}catch(k){h=C(k)}H+=1,j(h,ve,me),q.push(h),he&&(he(),he=null),!ye&&(q.length>=ge||H>=J)&&await new A(k=>{fe=k})}q.push(D)}catch(h){let k=C(h);j(k,ve,me),q.push(k)}finally{ye=!0,he&&(he(),he=null)}}Oe();try{for(;;){for(;q.length>0;){let h=await q[0];if(h===D)return;if(se.aborted)throw new a;h!==B&&(yield h),q.shift(),ae()}await new A(h=>{he=h})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function Y(z=void 0){return z!=null&&u(z,"options"),z?.signal!=null&&l(z.signal,"options.signal"),(async function*(){let G=0;for await(let ge of this){var J;if(z!=null&&(J=z.signal)!==null&&J!==void 0&&J.aborted)throw new a({cause:z.signal.reason});yield[G++,ge]}}).call(this)}async function W(z,G=void 0){for await(let J of M.call(this,z,G))return!0;return!1}async function re(z,G=void 0){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);return!await W.call(this,async(...J)=>!await z(...J),G)}async function $(z,G){for await(let J of M.call(this,z,G))return J}async function Z(z,G){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);async function J(ge,se){return await z(ge,se),B}for await(let ge of oe.call(this,J,G));}function M(z,G){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);async function J(ge,se){return await z(ge,se)?ge:B}return oe.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(z,G,J){var ge;if(typeof z!="function")throw new s("reducer",["Function","AsyncFunction"],z);J!=null&&u(J,"options"),J?.signal!=null&&l(J.signal,"options.signal");let se=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 b(this.destroy(fe)),fe}let R=new t,q=R.signal;if(J!=null&&J.signal){let fe={once:!0,[d]:this,[p]:!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;se?G=await z(G,fe,{signal:q}):(G=fe,se=!0)}if(!ee&&!se)throw new Q}finally{R.abort()}return G}async function te(z){z!=null&&u(z,"options"),z?.signal!=null&&l(z.signal,"options.signal");let G=[];for await(let ge of this){var J;if(z!=null&&(J=z.signal)!==null&&J!==void 0&&J.aborted)throw new a(void 0,{cause:z.signal.reason});_(G,ge)}return G}function we(z,G){let J=oe.call(this,z,G);return(async function*(){for await(let ge of J)yield*ge}).call(this)}function K(z){if(z=E(z),S(z))return 0;if(z<0)throw new i("number",">= 0",z);return z}function N(z,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),z=K(z),(async function*(){var J;if(G!=null&&(J=G.signal)!==null&&J!==void 0&&J.aborted)throw new a;for await(let se of this){var ge;if(G!=null&&(ge=G.signal)!==null&&ge!==void 0&&ge.aborted)throw new a;z--<=0&&(yield se)}}).call(this)}function ne(z,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),z=K(z),(async function*(){var J;if(G!=null&&(J=G.signal)!==null&&J!==void 0&&J.aborted)throw new a;for await(let se of this){var ge;if(G!=null&&(ge=G.signal)!==null&&ge!==void 0&&ge.aborted)throw new a;if(z-- >0&&(yield se),z<=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:oe,take:ne,compose:U},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:be,toArray:te,some:W,find:$}}),Ma=pe((o,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Be(),{isIterable:s,isNodeStream:n,isWebStream:i}=mt(),{pipelineImpl:a}=wo(),{finished:l}=At();Ra();function c(...u){return new r((d,p)=>{let b,f,g=u[u.length-1];if(g&&typeof g=="object"&&!n(g)&&!s(g)&&!i(g)){let y=t(u);b=y.signal,f=y.end}a(u,(y,w)=>{y?p(y):d(w)},{signal:b,end:f})})}e.exports={finished:l,pipeline:c}}),Ra=pe((o,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Le(Fe)),{ObjectDefineProperty:r,ObjectKeys:s,ReflectApply:n}=Be(),{promisify:{custom:i}}=Ye(),{streamReturningOperators:a,promiseReturningOperators:l}=ru(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ke(),u=Oa(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=Gr(),{pipeline:b}=wo(),{destroyer:f}=Yt(),g=At(),y=Ma(),w=mt(),m=e.exports=yo().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=Yr();for(let x of s(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 s(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=vo(),m.Duplex=ft(),m.Transform=Ca(),m.PassThrough=Pa(),m.pipeline=b;var{addAbortSignal:_}=Kr();m.addAbortSignal=_,m.finished=g,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(b,i,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(g,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)}}),Bt=pe((o,e)=>{le(),ue(),ce();var t=Ra(),r=Ma(),s=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=s,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}),nu=pe((o,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 s=function(){};s.prototype=r.prototype,t.prototype=new s,t.prototype.constructor=t}}}),iu=pe((o,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Le(Fe)),r=Symbol.for("BufferList");function s(n){if(!(this instanceof s))return new s(n);s._init.call(this,n)}s._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},s.prototype._new=function(n){return new s(n)},s.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}},s.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},s.prototype.getBuffers=function(){return this._bufs},s.prototype.get=function(n){if(n>this.length||n<0)return;let i=this._offset(n);return this._bufs[i[0]][i[1]]},s.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)},s.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,p=d,b=c&&i||0,f=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 g=0;g<this._bufs.length;g++)this._bufs[g].copy(n,b),b+=this._bufs[g].length;return n}if(p<=this._bufs[u[0]].length-f)return c?this._bufs[u[0]].copy(n,i,f,f+p):this._bufs[u[0]].slice(f,f+p);c||(n=t.allocUnsafe(d));for(let g=u[0];g<this._bufs.length;g++){let y=this._bufs[g].length-f;if(p>y)this._bufs[g].copy(n,b,f),b+=y;else{this._bufs[g].copy(n,b,f,f+p),b+=y;break}p-=y,f&&(f=0)}return n.length>b?n.slice(0,b):n},s.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)},s.prototype.toString=function(n,i,a){return this.slice(i,a).toString(n)},s.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},s.prototype.duplicate=function(){let n=this._new();for(let i=0;i<this._bufs.length;i++)n.append(this._bufs[i]);return n},s.prototype.append=function(n){return this._attach(n,s.prototype._appendBuffer)},s.prototype.prepend=function(n){return this._attach(n,s.prototype._prependBuffer,!0)},s.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},s.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},s.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},s.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 p=d.indexOf(n,u);if(p!==-1)return this._reverseOffset([c,p]);u=d.length-n.length+1}else{let p=this._reverseOffset([c,u]);if(this._match(p,n))return p;u++}u=0}return-1},s.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?s.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:s.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(i)})(),s.prototype._isBufferList=function(n){return n instanceof s||s.isBufferList(n)},s.isBufferList=function(n){return n!=null&&n[r]},e.exports=s}),ou=pe((o,e)=>{le(),ue(),ce();var t=Bt().Duplex,r=nu(),s=iu();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}s._init.call(this,i),t.call(this)}r(n,t),Object.assign(n.prototype,s.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 s||n.isBufferList(i)},n.isBufferList=s.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=s}),su=pe((o,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}),La=pe((o,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=($e(),Le(Fe));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 s(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=s("publish"),t.SUBSCRIBE_HEADER=s("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=s("unsubscribe"),t.ACKS={unsuback:s("unsuback"),puback:s("puback"),pubcomp:s("pubcomp"),pubrel:s("pubrel"),pubrec:s("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"}}),au=pe((o,e)=>{le(),ue(),ce();var t=1e3,r=t*60,s=r*60,n=s*24,i=n*7,a=n*365.25;e.exports=function(p,b){b=b||{};var f=typeof p;if(f==="string"&&p.length>0)return l(p);if(f==="number"&&isFinite(p))return b.long?u(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function l(p){if(p=String(p),!(p.length>100)){var b=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(b){var f=parseFloat(b[1]),g=(b[2]||"ms").toLowerCase();switch(g){case"years":case"year":case"yrs":case"yr":case"y":return f*a;case"weeks":case"week":case"w":return f*i;case"days":case"day":case"d":return f*n;case"hours":case"hour":case"hrs":case"hr":case"h":return f*s;case"minutes":case"minute":case"mins":case"min":case"m":return f*r;case"seconds":case"second":case"secs":case"sec":case"s":return f*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function c(p){var b=Math.abs(p);return b>=n?Math.round(p/n)+"d":b>=s?Math.round(p/s)+"h":b>=r?Math.round(p/r)+"m":b>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var b=Math.abs(p);return b>=n?d(p,b,n,"day"):b>=s?d(p,b,s,"hour"):b>=r?d(p,b,r,"minute"):b>=t?d(p,b,t,"second"):p+" ms"}function d(p,b,f,g){var y=b>=f*1.5;return Math.round(p/f)+" "+g+(y?"s":"")}}),lu=pe((o,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=au(),n.destroy=p,Object.keys(r).forEach(b=>{n[b]=r[b]}),n.names=[],n.skips=[],n.formatters={};function s(b){let f=0;for(let g=0;g<b.length;g++)f=(f<<5)-f+b.charCodeAt(g),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=s;function n(b){let f,g=null,y,w;function m(..._){if(!m.enabled)return;let x=m,v=Number(new Date),E=v-(f||v);x.diff=E,x.prev=f,x.curr=v,f=v,_[0]=n.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let S=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(A,C)=>{if(A==="%%")return"%";S++;let O=n.formatters[C];if(typeof O=="function"){let j=_[S];A=O.call(x,j),_.splice(S,1),S--}return A}),n.formatArgs.call(x,_),(x.log||n.log).apply(x,_)}return m.namespace=b,m.useColors=n.useColors(),m.color=n.selectColor(b),m.extend=i,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(y!==n.namespaces&&(y=n.namespaces,w=n.enabled(b)),w),set:_=>{g=_}}),typeof n.init=="function"&&n.init(m),m}function i(b,f){let g=n(this.namespace+(typeof f>"u"?":":f)+b);return g.log=this.log,g}function a(b){n.save(b),n.namespaces=b,n.names=[],n.skips=[];let f=(typeof b=="string"?b:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let g of f)g[0]==="-"?n.skips.push(g.slice(1)):n.names.push(g)}function l(b,f){let g=0,y=0,w=-1,m=0;for(;g<b.length;)if(y<f.length&&(f[y]===b[g]||f[y]==="*"))f[y]==="*"?(w=y,m=g,y++):(g++,y++);else if(w!==-1)y=w+1,m++,g=m;else return!1;for(;y<f.length&&f[y]==="*";)y++;return y===f.length}function c(){let b=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),b}function u(b){for(let f of n.skips)if(l(b,f))return!1;for(let f of n.names)if(l(b,f))return!0;return!1}function d(b){return b instanceof Error?b.stack||b.message:b}function p(){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((o,e)=>{le(),ue(),ce(),o.formatArgs=r,o.save=s,o.load=n,o.useColors=t,o.storage=i(),o.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`."))}})(),o.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,p=>{p!=="%%"&&(u++,p==="%c"&&(d=u))}),l.splice(d,0,c)}o.log=console.debug||console.log||(()=>{});function s(l){try{l?o.storage.setItem("debug",l):o.storage.removeItem("debug")}catch{}}function n(){let l;try{l=o.storage.getItem("debug")||o.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=lu()(o);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),cu=pe((o,e)=>{le(),ue(),ce();var t=ou(),{EventEmitter:r}=(jt(),Le(Et)),s=su(),n=La(),i=pt()("mqtt-packet:parser"),a=class ki extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof ki?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new ki().parser(c)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new s,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,p=n.requiredHeaderFlags[u];return p!=null&&d!==p?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,p,b={},f=this.packet,g=this._parseString();if(g===null)return this._emitError(new Error("Cannot parse protocolId"));if(g!=="MQTT"&&g!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=g,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(f.protocolVersion=this._list.readUInt8(this._pos),f.protocolVersion>=128&&(f.bridgeMode=!0,f.protocolVersion=f.protocolVersion-128),f.protocolVersion!==3&&f.protocolVersion!==4&&f.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"));b.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,b.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,b.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(b.will)f.will={},f.will.retain=y,f.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(f.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,f.keepalive=this._parseNum(),f.keepalive===-1)return this._emitError(new Error("Packet too short"));if(f.protocolVersion===5){let _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(f.properties=_)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(f.clientId=m,i("_parseConnect: packet.clientId: %s",f.clientId),b.will){if(f.protocolVersion===5){let _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(f.will.properties=_)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=c,i("_parseConnect: packet.will.topic: %s",f.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));f.will.payload=u,i("_parseConnect: packet.will.paylaod: %s",f.will.payload)}if(b.username){if(p=this._parseString(),p===null)return this._emitError(new Error("Cannot parse username"));f.username=p,i("_parseConnect: packet.username: %s",f.username)}if(b.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));f.password=d}return this.settings=f,i("_parseConnect: complete"),f}_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,p,b,f,g,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(p=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(g=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,b=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,b>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));y={topic:u,qos:p},this.settings.protocolVersion===5?(y.nl=g,y.rap=f,y.rh=b):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 p=this._list.toString("utf8",this._pos,d);return this._pos+=u,i("_parseString: result: %s",p),p}_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,p=1,b=0,f=!1,g,y=this._pos?this._pos:0;for(;d<u&&y+d<this._list.length;){if(g=this._list.readUInt8(y+d++),b+=p*(g&n.VARBYTEINT_MASK),p*=128,(g&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=d)break}return!f&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=d),f?c?f={bytes:d,value:b}:f=b:f=!1,i("_parseVarByteNum: result: %o",f),f}_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 p=this._parseByte();if(!p)return this._emitError(new Error("Cannot parse property code type")),!1;let b=n.propertiesCodes[p];if(!b)return this._emitError(new Error("Unknown property")),!1;if(b==="userProperties"){d[b]||(d[b]=Object.create(null));let f=this._parseByType(n.propertiesTypes[b]);if(d[b][f.name])if(Array.isArray(d[b][f.name]))d[b][f.name].push(f.value);else{let g=d[b][f.name];d[b][f.name]=[g],d[b][f.name].push(f.value)}else d[b][f.name]=f.value;continue}d[b]?Array.isArray(d[b])?d[b].push(this._parseByType(n.propertiesTypes[b])):(d[b]=[d[b]],d[b].push(this._parseByType(n.propertiesTypes[b]))):d[b]=this._parseByType(n.propertiesTypes[b])}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 s,this._pos=0,!0}_emitError(c){i("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),uu=pe((o,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Le(Fe)),r=65536,s={},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++)s[u]=i(u)}function l(u){let d=0,p=0,b=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),b.writeUInt8(d,p++);while(u>0&&p<4);return u>0&&(p=0),n?b.subarray(0,p):b.slice(0,p)}function c(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:s,generateCache:a,generateNumber:i,genBufVariableByteInt:l,generate4ByteBuffer:c}}),du=pe((o,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,s,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,s)});case 3:return Ne.nextTick(function(){r.call(null,s,n)});case 4:return Ne.nextTick(function(){r.call(null,s,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)})}}}),Na=pe((o,e)=>{le(),ue(),ce();var t=La(),{Buffer:r}=($e(),Le(Fe)),s=r.allocUnsafe(0),n=r.from([0]),i=uu(),a=du().nextTick,l=pt()("mqtt-packet:writeToStream"),c=i.cache,u=i.generateNumber,d=i.generateCache,p=i.genBufVariableByteInt,b=i.generate4ByteBuffer,f=Y,g=!0;function y(K,N,ne){switch(l("generate called"),N.cork&&(N.cork(),a(w,N)),g&&(g=!1,d()),l("generate: packet.cmd: %s",K.cmd),K.cmd){case"connect":return m(K,N);case"connack":return _(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 A(K,N,ne);case"unsuback":return C(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 f===Y},set(K){K?((!c||Object.keys(c).length===0)&&(g=!0),f=Y):(g=!1,f=W)}});function w(K){K.uncork()}function m(K,N,ne){let z=K||{},G=z.protocolId||"MQTT",J=z.protocolVersion||4,ge=z.will,se=z.clean,R=z.keepalive||0,q=z.clientId||"",ee=z.username,he=z.password,fe=z.properties;se===void 0&&(se=!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 q=="string"||r.isBuffer(q))&&(q||J>=4)&&(q||se))ye+=r.byteLength(q)+2;else{if(J<4)return N.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(se*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),z.bridgeMode&&(J+=128),N.write(J===131?t.VERSION131:J===132?t.VERSION132:J===4?t.VERSION4:J===5?t.VERSION5:t.VERSION3);let ae=0;return ae|=ee!=null?t.USERNAME_MASK:0,ae|=he!=null?t.PASSWORD_MASK:0,ae|=ge&&ge.retain?t.WILL_RETAIN_MASK:0,ae|=ge&&ge.qos?ge.qos<<t.WILL_QOS_SHIFT:0,ae|=ge?t.WILL_FLAG_MASK:0,ae|=se?t.CLEAN_SESSION_MASK:0,N.write(r.from([ae])),f(N,R),J===5&&H.write(),$(N,q),ge&&(J===5&&me.write(),U(N,ge.topic),$(N,ge.payload)),ee!=null&&$(N,ee),he!=null&&$(N,he),!0}function _(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=z===5?G.reasonCode:G.returnCode,ge=G.properties,se=2;if(typeof J!="number")return N.destroy(new Error("Invalid return code")),!1;let R=null;if(z===5){if(R=Z(N,ge),!R)return!1;se+=R.length}return N.write(t.CONNACK_HEADER),D(N,se),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 z=ne?ne.protocolVersion:4,G=K||{},J=G.qos||0,ge=G.retain?t.RETAIN_MASK:0,se=G.topic,R=G.payload||s,q=G.messageId,ee=G.properties,he=0;if(typeof se=="string")he+=r.byteLength(se)+2;else if(r.isBuffer(se))he+=se.length+2;else return N.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?he+=R.length:he+=r.byteLength(R),J&&typeof q!="number")return N.destroy(new Error("Invalid messageId")),!1;J&&(he+=2);let fe=null;if(z===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),f(N,te(se)),N.write(se),J>0&&f(N,q),fe?.write(),l("publish: payload: %o",R),N.write(R)}function v(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.cmd||"puback",ge=G.messageId,se=G.dup&&J==="pubrel"?t.DUP_MASK:0,R=0,q=G.reasonCode,ee=G.properties,he=z===5?3:2;if(J==="pubrel"&&(R=1),typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;let fe=null;if(z===5&&typeof ee=="object"){if(fe=M(N,ee,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[J][R][se][0]),he===3&&(he+=q!==0?1:-1),D(N,he),f(N,ge),z===5&&he!==2&&N.write(r.from([q])),fe!==null?fe.write():he===4&&N.write(r.from([0])),!0}function E(K,N,ne){l("subscribe: packet: ");let z=ne?ne.protocolVersion:4,G=K||{},J=G.dup?t.DUP_MASK:0,ge=G.messageId,se=G.subscriptions,R=G.properties,q=0;if(typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;q+=2;let ee=null;if(z===5){if(ee=Z(N,R),!ee)return!1;q+=ee.length}if(typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){let ye=se[fe].topic,H=se[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(z===5){if(typeof(se[fe].nl||!1)!="boolean")return N.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(se[fe].rap||!1)!="boolean")return N.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=se[fe].rh||0;if(typeof me!="number"||me>2)return N.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}q+=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,q),f(N,ge),ee!==null&&ee.write();let he=!0;for(let fe of se){let ye=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,ae=fe.rh,Oe;U(N,ye),Oe=t.SUBSCRIBE_OPTIONS_QOS[H],z===5&&(Oe|=me?t.SUBSCRIBE_OPTIONS_NL:0,Oe|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Oe|=ae?t.SUBSCRIBE_OPTIONS_RH[ae]:0),he=N.write(r.from([Oe]))}return he}function S(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.granted,se=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 q=null;if(z===5){if(q=M(N,se,ne,R),!q)return!1;R+=q.length}return N.write(t.SUBACK_HEADER),D(N,R),f(N,J),q!==null&&q.write(),N.write(r.from(ge))}function A(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.dup?t.DUP_MASK:0,se=G.unsubscriptions,R=G.properties,q=0;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(q+=2,typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){if(typeof se[fe]!="string")return N.destroy(new Error("Invalid unsubscriptions")),!1;q+=r.byteLength(se[fe])+2}else return N.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(z===5){if(ee=Z(N,R),!ee)return!1;q+=ee.length}N.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),D(N,q),f(N,J),ee!==null&&ee.write();let he=!0;for(let fe=0;fe<se.length;fe++)he=U(N,se[fe]);return he}function C(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.dup?t.DUP_MASK:0,se=G.granted,R=G.properties,q=G.cmd,ee=0,he=2;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(z===5)if(typeof se=="object"&&se.length)for(let ye=0;ye<se.length;ye+=1){if(typeof se[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(z===5){if(fe=M(N,R,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[q][ee][ge][0]),D(N,he),f(N,J),fe!==null&&fe.write(),z===5&&N.write(r.from(se)),!0}function O(K,N,ne){return N.write(t.EMPTY[K.cmd])}function j(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.reasonCode,ge=G.properties,se=z===5?1:0,R=null;if(z===5){if(R=M(N,ge,ne,se),!R)return!1;se+=R.length}return N.write(r.from([t.codes.disconnect<<4])),D(N,se),z===5&&N.write(r.from([J])),R!==null&&R.write(),!0}function T(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.reasonCode,ge=G.properties,se=z===5?1:0;z!==5&&N.destroy(new Error("Invalid mqtt version for auth packet"));let R=M(N,ge,ne,se);return R?(se+=R.length,N.write(r.from([t.codes.auth<<4])),D(N,se),N.write(r.from([J])),R!==null&&R.write(),!0):!1}var B={};function D(K,N){if(N>t.VARBYTEINT_MAX)return K.destroy(new Error(`Invalid variable byte integer: ${N}`)),!1;let ne=B[N];return ne||(ne=p(N),N<16384&&(B[N]=ne)),l("writeVarByteInt: writing to stream: %o",ne),K.write(ne)}function U(K,N){let ne=r.byteLength(N);return f(K,ne),l("writeString: %s",N),K.write(N,"utf8")}function oe(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 W(K,N){let ne=u(N);return l("writeNumberGenerated: %o",ne),K.write(ne)}function re(K,N){let ne=b(N);return l("write4ByteNumber: %o",ne),K.write(ne)}function $(K,N){typeof N=="string"?U(K,N):N?(f(K,N.length),K.write(N)):f(K,0)}function Z(K,N){if(typeof N!="object"||N.length!=null)return{length:1,write(){be(K,{},0)}};let ne=0;function z(G,J){let ge=t.propertiesTypes[G],se=0;switch(ge){case"byte":{if(typeof J!="boolean")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=2;break}case"int8":{if(typeof J!="number"||J<0||J>255)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=2;break}case"binary":{if(J&&J===null)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=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;se+=3;break}case"int32":{if(typeof J!="number"||J<0||J>4294967295)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=5;break}case"var":{if(typeof J!="number"||J<0||J>268435455)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=1+r.byteLength(p(J));break}case"string":{if(typeof J!="string")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=3+r.byteLength(J.toString());break}case"pair":{if(typeof J!="object")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=Object.getOwnPropertyNames(J).reduce((R,q)=>{let ee=J[q];return Array.isArray(ee)?R+=ee.reduce((he,fe)=>(he+=3+r.byteLength(q.toString())+2+r.byteLength(fe.toString()),he),0):R+=3+r.byteLength(q.toString())+2+r.byteLength(J[q].toString()),R},0);break}default:return K.destroy(new Error(`Invalid property ${G}: ${J}`)),!1}return se}if(N)for(let G in N){let J=0,ge=0,se=N[G];if(se!==void 0){if(Array.isArray(se))for(let R=0;R<se.length;R++){if(ge=z(G,se[R]),!ge)return!1;J+=ge}else{if(ge=z(G,se),!ge)return!1;J=ge}if(!J)return!1;ne+=J}}return{length:r.byteLength(p(ne))+ne,write(){be(K,N,ne)}}}function M(K,N,ne,z){let G=["reasonString","userProperties"],J=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=Z(K,N);if(J)for(;z+ge.length>J;){let se=G.shift();if(se&&N[se])delete N[se],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]])),f(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(z=>{let G=ne[z];Array.isArray(G)?G.forEach(J=>{K.write(r.from([t.properties[N]])),oe(K,z.toString(),J.toString())}):(K.write(r.from([t.properties[N]])),oe(K,z.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 z in N)if(Object.prototype.hasOwnProperty.call(N,z)&&N[z]!=null){let G=N[z];if(Array.isArray(G))for(let J=0;J<G.length;J++)Q(K,z,G[J]);else Q(K,z,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}),hu=pe((o,e)=>{le(),ue(),ce();var t=Na(),{EventEmitter:r}=(jt(),Le(Et)),{Buffer:s}=($e(),Le(Fe));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]=s.byteLength(c[d]),a+=l[d];let p=s.allocUnsafe(a);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(p,u),u+=l[d]):(p.write(c[d],u),u+=l[d]);return p}destroy(a){a&&this.emit("error",a)}};e.exports=n}),fu=pe(o=>{le(),ue(),ce(),o.parser=cu().parser,o.generate=hu(),o.writeToStream=Na()}),pu=pe((o,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof Wr?Wr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return s(n);let i=new Map;if(i.set(Date,d=>new Date(d)),i.set(Map,(d,p)=>new Map(l(Array.from(d),p))),i.set(Set,(d,p)=>new Set(l(Array.from(d),p))),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,p){let b=Object.keys(d),f=new Array(b.length);for(let g=0;g<b.length;g++){let y=b[g],w=d[y];typeof w!="object"||w===null?f[y]=w:w.constructor!==Object&&(a=i.get(w.constructor))?f[y]=a(w,p):ArrayBuffer.isView(w)?f[y]=t(w):f[y]=p(w)}return f}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 p={};for(let b in d){if(Object.hasOwnProperty.call(d,b)===!1)continue;let f=d[b];typeof f!="object"||f===null?p[b]=f:f.constructor!==Object&&(a=i.get(f.constructor))?p[b]=a(f,c):ArrayBuffer.isView(f)?p[b]=t(f):p[b]=c(f)}return p}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 p={};for(let b in d){let f=d[b];typeof f!="object"||f===null?p[b]=f:f.constructor!==Object&&(a=i.get(f.constructor))?p[b]=a(f,u):ArrayBuffer.isView(f)?p[b]=t(f):p[b]=u(f)}return p}}function s(n){let i=[],a=[],l=new Map;if(l.set(Date,b=>new Date(b)),l.set(Map,(b,f)=>new Map(u(Array.from(b),f))),l.set(Set,(b,f)=>new Set(u(Array.from(b),f))),n.constructorHandlers)for(let b of n.constructorHandlers)l.set(b[0],b[1]);let c=null;return n.proto?p:d;function u(b,f){let g=Object.keys(b),y=new Array(g.length);for(let w=0;w<g.length;w++){let m=g[w],_=b[m];if(typeof _!="object"||_===null)y[m]=_;else if(_.constructor!==Object&&(c=l.get(_.constructor)))y[m]=c(_,f);else if(ArrayBuffer.isView(_))y[m]=t(_);else{let x=i.indexOf(_);x!==-1?y[m]=a[x]:y[m]=f(_)}}return y}function d(b){if(typeof b!="object"||b===null)return b;if(Array.isArray(b))return u(b,d);if(b.constructor!==Object&&(c=l.get(b.constructor)))return c(b,d);let f={};i.push(b),a.push(f);for(let g in b){if(Object.hasOwnProperty.call(b,g)===!1)continue;let y=b[g];if(typeof y!="object"||y===null)f[g]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))f[g]=c(y,d);else if(ArrayBuffer.isView(y))f[g]=t(y);else{let w=i.indexOf(y);w!==-1?f[g]=a[w]:f[g]=d(y)}}return i.pop(),a.pop(),f}function p(b){if(typeof b!="object"||b===null)return b;if(Array.isArray(b))return u(b,p);if(b.constructor!==Object&&(c=l.get(b.constructor)))return c(b,p);let f={};i.push(b),a.push(f);for(let g in b){let y=b[g];if(typeof y!="object"||y===null)f[g]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))f[g]=c(y,p);else if(ArrayBuffer.isView(y))f[g]=t(y);else{let w=i.indexOf(y);w!==-1?f[g]=a[w]:f[g]=p(y)}}return i.pop(),a.pop(),f}}}),mu=pe((o,e)=>{le(),ue(),ce(),e.exports=pu()()}),ja=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.validateTopic=e,o.validateTopics=t;function e(r){let s=r.split("/");for(let n=0;n<s.length;n++)if(s[n]!=="+"){if(s[n]==="#")return n===s.length-1;if(s[n].indexOf("+")!==-1||s[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let s=0;s<r.length;s++)if(!e(r[s]))return r[s];return null}}),Ua=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=Bt(),t={objectMode:!0},r={clean:!0},s=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()}};o.default=s}),gu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,s,n)=>{r.log("handlePublish: packet %o",s),n=typeof n<"u"?n:r.noop;let i=s.topic.toString(),a=s.payload,{qos:l}=s,{messageId:c}=s,{options:u}=r;if(r.options.protocolVersion===5){let d;if(s.properties&&(d=s.properties.topicAlias),typeof d<"u")if(i.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)i=p,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,s,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:p},n):r.incomingStore.put(s,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(i,a,s,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",i,a,s),r.handleMessage(s,b=>{if(b)return n&&n(b);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",i,a,s),r.handleMessage(s,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};o.default=t}),bu=pe((o,e)=>{e.exports={version:"5.15.0"}}),Jt=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.MQTTJS_VERSION=o.nextTick=o.ErrorWithSubackPacket=o.ErrorWithReasonCode=void 0,o.applyMixin=r;var e=class Ba extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,Ba.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};o.ErrorWithReasonCode=e;var t=class Da extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,Da.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};o.ErrorWithSubackPacket=t;function r(s,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(s.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}o.nextTick=typeof Ne?.nextTick=="function"?Ne.nextTick:s=>{setTimeout(s,0)},o.MQTTJS_VERSION=bu().version}),Jr=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.ReasonCodes=void 0;var e=Jt();o.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,s)=>{let{messageId:n}=s,i=s.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=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${o.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,s)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${o.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,s)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=s.granted;for(let d=0;d<u.length;d++){let p=u[d];if((p&128)!==0){c=new Error(`Subscribe error: ${o.ReasonCodes[p]}`),c.code=p;let b=r.messageIdToTopic[n];b&&b.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),l(c,s);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,s);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};o.default=t}),yu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=Jt(),t=Jr(),r=(s,n)=>{let{options:i}=s,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);s.emit("error",c);return}s.handleAuth(n,(c,u)=>{if(c){s.emit("error",c);return}if(l===24)s.reconnecting=!1,s._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);s.emit("error",d)}})};o.default=r}),vu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof Ne=="object"&&Ne?Ne:{},s=(b,f,g,y)=>{typeof r.emitWarning=="function"?r.emitWarning(b,f,g,y):console.error(`[${g}] ${f}: ${b}`)},n=globalThis.AbortController,i=globalThis.AbortSignal;if(typeof n>"u"){i=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(g,y){this._onabort.push(y)}},n=class{constructor(){f()}signal=new i;abort(g){if(!this.signal.aborted){this.signal.reason=g,this.signal.aborted=!0;for(let y of this.signal._onabort)y(g);this.signal.onabort?.(g)}}};let b=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{b&&(b=!1,s("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",f))}}var a=b=>!t.has(b),l=b=>b&&b===Math.floor(b)&&b>0&&isFinite(b),c=b=>l(b)?b<=Math.pow(2,8)?Uint8Array:b<=Math.pow(2,16)?Uint16Array:b<=Math.pow(2,32)?Uint32Array:b<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(b){super(b),this.fill(0)}},d=class sr{heap;length;static#l=!1;static create(f){let g=c(f);if(!g)return[];sr.#l=!0;let y=new sr(f,g);return sr.#l=!1,y}constructor(f,g){if(!sr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new g(f),this.length=0}push(f){this.heap[this.length++]=f}pop(){return this.heap[--this.length]}},p=class Fa{#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;#_;#A;#u;static unsafeExposeInternals(f){return{starts:f.#w,ttls:f.#f,sizes:f.#v,keyMap:f.#n,keyList:f.#r,valList:f.#e,next:f.#c,prev:f.#h,get head(){return f.#a},get tail(){return f.#o},free:f.#y,isBackgroundFetch:g=>f.#t(g),backgroundFetch:(g,y,w,m)=>f.#L(g,y,w,m),moveToTail:g=>f.#C(g),indexes:g=>f.#k(g),rindexes:g=>f.#x(g),isStale:g=>f.#p(g)}}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(f){let{max:g=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:_,updateAgeOnHas:x,allowStale:v,dispose:E,disposeAfter:S,noDisposeOnSet:A,noUpdateTTL:C,maxSize:O=0,maxEntrySize:j=0,sizeCalculation:T,fetchMethod:B,memoMethod:D,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:oe,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:W,ignoreFetchAbort:re}=f;if(g!==0&&!l(g))throw new TypeError("max option must be a nonnegative integer");let $=g?c(g):Array;if(!$)throw new Error("invalid max value: "+g);if(this.#l=g,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,B!==void 0&&typeof B!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=B,this.#A=!!B,this.#n=new Map,this.#r=new Array(g).fill(void 0),this.#e=new Array(g).fill(void 0),this.#c=new $(g),this.#h=new $(g),this.#a=0,this.#o=0,this.#y=d.create(g),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.#_=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!A,this.noUpdateTTL=!!C,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!W,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.#$()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!oe,this.updateAgeOnGet=!!_,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),s("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,Fa))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#N(){let f=new u(this.#l),g=new u(this.#l);this.#f=f,this.#w=g,this.#j=(m,_,x=e.now())=>{if(g[m]=_!==0?x:0,f[m]=_,_!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},_+1);v.unref&&v.unref()}},this.#I=m=>{g[m]=f[m]!==0?e.now():0},this.#E=(m,_)=>{if(f[_]){let x=f[_],v=g[_];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 _=setTimeout(()=>y=0,this.ttlResolution);_.unref&&_.unref()}return m};this.getRemainingTTL=m=>{let _=this.#n.get(m);if(_===void 0)return 0;let x=f[_],v=g[_];if(!x||!v)return 1/0;let E=(y||w())-v;return x-E},this.#p=m=>{let _=g[m],x=f[m];return!!x&&!!_&&(y||w())-_>x}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#$(){let f=new u(this.#l);this.#b=0,this.#v=f,this.#T=g=>{this.#b-=f[g],f[g]=0},this.#U=(g,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,g),!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=(g,y,w)=>{if(f[g]=y,this.#d){let m=this.#d-f[g];for(;this.#b>m;)this.#R(!0)}this.#b+=f[g],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=f=>{};#M=(f,g,y)=>{};#U=(f,g,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:f=this.allowStale}={}){if(this.#i)for(let g=this.#o;!(!this.#B(g)||((f||!this.#p(g))&&(yield g),g===this.#a));)g=this.#h[g]}*#x({allowStale:f=this.allowStale}={}){if(this.#i)for(let g=this.#a;!(!this.#B(g)||((f||!this.#p(g))&&(yield g),g===this.#o));)g=this.#c[g]}#B(f){return f!==void 0&&this.#n.get(this.#r[f])===f}*entries(){for(let f of this.#k())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*rentries(){for(let f of this.#x())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*keys(){for(let f of this.#k()){let g=this.#r[f];g!==void 0&&!this.#t(this.#e[f])&&(yield g)}}*rkeys(){for(let f of this.#x()){let g=this.#r[f];g!==void 0&&!this.#t(this.#e[f])&&(yield g)}}*values(){for(let f of this.#k())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}*rvalues(){for(let f of this.#x())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(f,g={}){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&f(m,this.#r[y],this))return this.get(this.#r[y],g)}}forEach(f,g=this){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(g,m,this.#r[y],this)}}rforEach(f,g=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(g,m,this.#r[y],this)}}purgeStale(){let f=!1;for(let g of this.#x({allowStale:!0}))this.#p(g)&&(this.#S(this.#r[g],"expire"),f=!0);return f}info(f){let g=this.#n.get(f);if(g===void 0)return;let y=this.#e[g],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let _=this.#f[g],x=this.#w[g];if(_&&x){let v=_-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[g]),m}dump(){let f=[];for(let g of this.#k({allowStale:!0})){let y=this.#r[g],w=this.#e[g],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||y===void 0)continue;let _={value:m};if(this.#f&&this.#w){_.ttl=this.#f[g];let x=e.now()-this.#w[g];_.start=Math.floor(Date.now()-x)}this.#v&&(_.size=this.#v[g]),f.unshift([y,_])}return f}load(f){this.clear();for(let[g,y]of f){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(g,y.value,y)}}set(f,g,y={}){if(g===void 0)return this.delete(f),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:_=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=y,{noUpdateTTL:E=this.noUpdateTTL}=y,S=this.#U(f,g,y.size||0,x);if(this.maxEntrySize&&S>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(f,"set"),this;let A=this.#i===0?void 0:this.#n.get(f);if(A===void 0)A=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#R(!1):this.#i,this.#r[A]=f,this.#e[A]=g,this.#n.set(f,A),this.#c[this.#o]=A,this.#h[A]=this.#o,this.#o=A,this.#i++,this.#M(A,S,v),v&&(v.set="add"),E=!1;else{this.#C(A);let C=this.#e[A];if(g!==C){if(this.#A&&this.#t(C)){C.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:O}=C;O!==void 0&&!_&&(this.#_&&this.#m?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]))}else _||(this.#_&&this.#m?.(C,f,"set"),this.#u&&this.#s?.push([C,f,"set"]));if(this.#T(A),this.#M(A,S,v),this.#e[A]=g,v){v.set="replace";let O=C&&this.#t(C)?C.__staleWhileFetching:C;O!==void 0&&(v.oldValue=O)}}else v&&(v.set="update")}if(w!==0&&!this.#f&&this.#N(),this.#f&&(E||this.#j(A,w,m),v&&this.#E(v,A)),!_&&this.#u&&this.#s){let C=this.#s,O;for(;O=C?.shift();)this.#g?.(...O)}return this}pop(){try{for(;this.#i;){let f=this.#e[this.#a];if(this.#R(!0),this.#t(f)){if(f.__staleWhileFetching)return f.__staleWhileFetching}else if(f!==void 0)return f}}finally{if(this.#u&&this.#s){let f=this.#s,g;for(;g=f?.shift();)this.#g?.(...g)}}}#R(f){let g=this.#a,y=this.#r[g],w=this.#e[g];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(g),f&&(this.#r[g]=void 0,this.#e[g]=void 0,this.#y.push(g)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[g],this.#n.delete(y),this.#i--,g}has(f,g={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=g,m=this.#n.get(f);if(m!==void 0){let _=this.#e[m];if(this.#t(_)&&_.__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(f,g={}){let{allowStale:y=this.allowStale}=g,w=this.#n.get(f);if(w===void 0||!y&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#L(f,g,y,w){let m=g===void 0?void 0:this.#e[g];if(this.#t(m))return m;let _=new n,{signal:x}=y;x?.addEventListener("abort",()=>_.abort(x.reason),{signal:_.signal});let v={signal:_.signal,options:y,context:w},E=(T,B=!1)=>{let{aborted:D}=_.signal,U=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(D&&!B?(y.status.fetchAborted=!0,y.status.fetchError=_.signal.reason,U&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),D&&!U&&!B)return A(_.signal.reason);let oe=O;return this.#e[g]===O&&(T===void 0?oe.__staleWhileFetching?this.#e[g]=oe.__staleWhileFetching:this.#S(f,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(f,T,v.options))),T},S=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),A(T)),A=T=>{let{aborted:B}=_.signal,D=B&&y.allowStaleOnFetchAbort,U=D||y.allowStaleOnFetchRejection,oe=U||y.noDeleteOnFetchRejection,Y=O;if(this.#e[g]===O&&(!oe||Y.__staleWhileFetching===void 0?this.#S(f,"fetch"):D||(this.#e[g]=Y.__staleWhileFetching)),U)return y.status&&Y.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},C=(T,B)=>{let D=this.#P?.(f,m,v);D&&D instanceof Promise&&D.then(U=>T(U===void 0?void 0:U),B),_.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(C).then(E,S),j=Object.assign(O,{__abortController:_,__staleWhileFetching:m,__returned:void 0});return g===void 0?(this.set(f,j,{...v.options,status:void 0}),g=this.#n.get(f)):this.#e[g]=j,j}#t(f){if(!this.#A)return!1;let g=f;return!!g&&g instanceof Promise&&g.hasOwnProperty("__staleWhileFetching")&&g.__abortController instanceof n}async fetch(f,g={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:_=this.ttl,noDisposeOnSet:x=this.noDisposeOnSet,size:v=0,sizeCalculation:E=this.sizeCalculation,noUpdateTTL:S=this.noUpdateTTL,noDeleteOnFetchRejection:A=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:C=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:j=this.allowStaleOnFetchAbort,context:T,forceRefresh:B=!1,status:D,signal:U}=g;if(!this.#A)return D&&(D.fetch="get"),this.get(f,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:D});let oe={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:_,noDisposeOnSet:x,size:v,sizeCalculation:E,noUpdateTTL:S,noDeleteOnFetchRejection:A,allowStaleOnFetchRejection:C,allowStaleOnFetchAbort:j,ignoreFetchAbort:O,status:D,signal:U},Y=this.#n.get(f);if(Y===void 0){D&&(D.fetch="miss");let W=this.#L(f,Y,oe,T);return W.__returned=W}else{let W=this.#e[Y];if(this.#t(W)){let M=y&&W.__staleWhileFetching!==void 0;return D&&(D.fetch="inflight",M&&(D.returnedStale=!0)),M?W.__staleWhileFetching:W.__returned=W}let re=this.#p(Y);if(!B&&!re)return D&&(D.fetch="hit"),this.#C(Y),w&&this.#I(Y),D&&this.#E(D,Y),W;let $=this.#L(f,Y,oe,T),Z=$.__staleWhileFetching!==void 0&&y;return D&&(D.fetch=re?"stale":"refresh",Z&&re&&(D.returnedStale=!0)),Z?$.__staleWhileFetching:$.__returned=$}}async forceFetch(f,g={}){let y=await this.fetch(f,g);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(f,g={}){let y=this.#O;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,..._}=g,x=this.get(f,_);if(!m&&x!==void 0)return x;let v=y(f,x,{options:_,context:w});return this.set(f,v,_),v}get(f,g={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:_}=g,x=this.#n.get(f);if(x!==void 0){let v=this.#e[x],E=this.#t(v);return _&&this.#E(_,x),this.#p(x)?(_&&(_.get="stale"),E?(_&&y&&v.__staleWhileFetching!==void 0&&(_.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(f,"expire"),_&&y&&(_.returnedStale=!0),y?v:void 0)):(_&&(_.get="hit"),E?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else _&&(_.get="miss")}#D(f,g){this.#h[g]=f,this.#c[f]=g}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#D(this.#h[f],this.#c[f]),this.#D(this.#o,f),this.#o=f)}delete(f){return this.#S(f,"delete")}#S(f,g){let y=!1;if(this.#i!==0){let w=this.#n.get(f);if(w!==void 0)if(y=!0,this.#i===1)this.#F(g);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(m,f,g),this.#u&&this.#s?.push([m,f,g])),this.#n.delete(f),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 _=this.#h[w];this.#c[_]=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.#F("delete")}#F(f){for(let g of this.#x({allowStale:!0})){let y=this.#e[g];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let w=this.#r[g];this.#_&&this.#m?.(y,w,f),this.#u&&this.#s?.push([y,w,f])}}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 g=this.#s,y;for(;y=g?.shift();)this.#g?.(...y)}}};o.LRUCache=p}),gt=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.ContainerIterator=o.Container=o.Base=void 0;var e=class{constructor(s=0){this.iteratorType=s}equals(s){return this.o===s.o}};o.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};o.Base=t;var r=class extends t{};o.Container=r}),wu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=gt(),t=class extends e.Base{constructor(s=[]){super(),this.S=[];let n=this;s.forEach(function(i){n.push(i)})}clear(){this.i=0,this.S=[]}push(s){return this.S.push(s),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;o.default=r}),_u=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=gt(),t=class extends e.Base{constructor(s=[]){super(),this.j=0,this.q=[];let n=this;s.forEach(function(i){n.push(i)})}clear(){this.q=[],this.i=this.j=0}push(s){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]=s}else this.q[this.j+this.i]=s;return++this.i}pop(){if(this.i===0)return;let s=this.q[this.j++];return this.i-=1,s}front(){if(this.i!==0)return this.q[this.j]}},r=t;o.default=r}),ku=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=gt(),t=class extends e.Base{constructor(s=[],n=function(a,l){return a>l?-1:a<l?1:0},i=!0){if(super(),this.v=n,Array.isArray(s))this.C=i?[...s]:s;else{this.C=[];let l=this;s.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(s){let n=this.C[s];for(;s>0;){let i=s-1>>1,a=this.C[i];if(this.v(a,n)<=0)break;this.C[s]=a,s=i}this.C[s]=n}k(s,n){let i=this.C[s];for(;s<n;){let a=s<<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[s]=c,s=a}this.C[s]=i}clear(){this.i=0,this.C.length=0}push(s){this.C.push(s),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let s=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),s}top(){return this.C[0]}find(s){return this.C.indexOf(s)>=0}remove(s){let n=this.C.indexOf(s);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(s){let n=this.C.indexOf(s);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;o.default=r}),_o=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=gt(),t=class extends e.Container{},r=t;o.default=r}),bt=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),$a=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.RandomIterator=void 0;var e=gt(),t=bt(),r=class extends e.ContainerIterator{constructor(s,n){super(n),this.o=s,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(s){this.container.setElementByPos(this.o,s)}};o.RandomIterator=r}),xu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=r(_o()),t=$a();function r(a){return a&&a.t?a:{default:a}}var s=class qa extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new qa(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 s(0,this)}end(){return new s(this.i,this)}rBegin(){return new s(this.i-1,this,1)}rEnd(){return new s(-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 s(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;o.default=i}),Su=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=s(_o()),t=gt(),r=bt();function s(l){return l&&l.t?l:{default:l}}var n=class Ha extends t.ContainerIterator{constructor(c,u,d,p){super(p),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 Ha(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 b=1;b<l;++b)d=d.B;let p=d.B;for(this.i+=u;u--;)d.B={l:c,L:d},d.B.L=d,d=d.B;d.B=p,p.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;o.default=a}),Eu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=r(_o()),t=$a();function r(a){return a&&a.t?a:{default:a}}var s=class Wa extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Wa(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 p=0;p<this.P;++p)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(p){d.pushBack(p)})}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 s(0,this)}end(){return new s(this.i,this)}rBegin(){return new s(this.i-1,this,1)}rEnd(){return new s(-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 s(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;o.default=i}),Au=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.TreeNodeEnableIndex=o.TreeNode=void 0;var e=class{constructor(r,s){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=s}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 s=r.tt;for(;s.U===r;)r=s,s=r.tt;r=s}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let s=r.tt;for(;s.W===r;)r=s,s=r.tt;return r.W!==s?s:r}}te(){let r=this.tt,s=this.W,n=s.U;return r.tt===this?r.tt=s:r.U===this?r.U=s:r.W=s,s.tt=r,s.U=this,this.tt=s,this.W=n,n&&(n.tt=this),s}se(){let r=this.tt,s=this.U,n=s.W;return r.tt===this?r.tt=s:r.U===this?r.U=s:r.W=s,s.tt=r,s.W=this,this.tt=s,this.U=n,n&&(n.tt=this),s}};o.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)}};o.TreeNodeEnableIndex=t}),za=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=Au(),t=gt(),r=bt(),s=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 p=d.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let b=this.he(d);if(b){let{parentNode:f,grandParent:g,curNode:y}=b;f.ie(),g.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 p=this.h.W,b=this.v(p.u,i);if(b===0){p.l=a;return}else if(b<0)p.W=new this.re(i,a),p.W.tt=p,c=p.W,this.h.W=c;else{if(l!==void 0){let f=l.o;if(f!==this.h){let g=this.v(f.u,i);if(g===0){f.l=a;return}else if(g>0){let y=f.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):(f.U=c,c.tt=f))}}}if(c===void 0)for(c=this.Y;;){let f=this.v(c.u,i);if(f>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(f<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=s;o.default=n}),Va=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=gt(),t=bt(),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}},s=r;o.default=s}),Iu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=s(za()),t=s(Va()),r=bt();function s(l){return l&&l.t?l:{default:l}}var n=class Ka extends t.default{constructor(c,u,d,p){super(c,u,p),this.container=d}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new Ka(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(p){d.insert(p)})}*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;o.default=a}),Tu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=s(za()),t=s(Va()),r=bt();function s(l){return l&&l.t?l:{default:l}}var n=class Ga extends t.default{constructor(c,u,d,p){super(c,u,p),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,p){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new Ga(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(p){d.setElement(p[0],p[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;o.default=a}),Ya=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),Ja=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.HashContainerIterator=o.HashContainer=void 0;var e=gt(),t=s(Ya()),r=bt();function s(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})}};o.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}};o.HashContainer=i}),Cu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=Ja(),t=bt(),r=class Qa 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 Qa(this.o,this.h,this.container,this.iteratorType)}},s=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=s;o.default=n}),Pu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=Ja(),t=s(Ya()),r=bt();function s(l){return l&&l.t?l:{default:l}}var n=class Xa extends e.HashContainerIterator{constructor(c,u,d,p){super(c,u,p),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,p){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new Xa(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;o.default=a}),Ou=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),Object.defineProperty(o,"Deque",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(o,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(o,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(o,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(o,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(o,"OrderedSet",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(o,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(o,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(o,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(o,"Vector",{enumerable:!0,get:function(){return s.default}});var e=d(wu()),t=d(_u()),r=d(ku()),s=d(xu()),n=d(Su()),i=d(Eu()),a=d(Iu()),l=d(Tu()),c=d(Cu()),u=d(Pu());function d(p){return p&&p.t?p:{default:p}}}),Mu=pe((o,e)=>{le(),ue(),ce();var t=Ou().OrderedSet,r=pt()("number-allocator:trace"),s=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){s("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 p=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,d))):this.ss.updateKeyByIterator(c,new n(p,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}),Za=pe((o,e)=>{le(),ue(),ce();var t=Mu();e.exports.NumberAllocator=t}),Ru=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=vu(),t=Za(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(s){s>0&&(this.aliasToTopic=new e.LRUCache({max:s}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,s),this.max=s,this.length=0)}put(s,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,s),this.topicToAlias[s]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(s){return this.aliasToTopic.get(s)}getAliasByTopic(s){let n=this.topicToAlias[s];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]}};o.default=r}),Lu=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(o,"__esModule",{value:!0});var t=Jr(),r=e(Ru()),s=Jt(),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 s.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);i.emit("error",u),i.options.reconnectOnConnackError&&i._cleanUp(!0)}};o.default=n}),Nu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=(t,r,s)=>{t.log("handling pubrel packet");let n=typeof s<"u"?s: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)}))})};o.default=e}),ju=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(o,"__esModule",{value:!0});var t=e(gu()),r=e(yu()),s=e(Lu()),n=e(Jr()),i=e(Nu()),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,s.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}};o.default=a}),el=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__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(){}};o.default=e}),Uu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__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={}}};o.default=e}),Bu=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(o,"__esModule",{value:!0}),o.TypedEventEmitter=void 0;var t=e((jt(),Le(Et))),r=Jt(),s=class{};o.TypedEventEmitter=s,(0,r.applyMixin)(s,t.default)}),Qr=pe((o,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Du=pe((o,e)=>{le(),ue(),ce();var t=Qr().default;function r(s,n){if(t(s)!="object"||!s)return s;var i=s[Symbol.toPrimitive];if(i!==void 0){var a=i.call(s,n||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(s)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Fu=pe((o,e)=>{le(),ue(),ce();var t=Qr().default,r=Du();function s(n){var i=r(n,"string");return t(i)=="symbol"?i:i+""}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),$u=pe((o,e)=>{le(),ue(),ce();var t=Fu();function r(s,n,i){return(n=t(n))in s?Object.defineProperty(s,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[n]=i,s}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),qu=pe((o,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}),Hu=pe((o,e)=>{le(),ue(),ce();function t(r,s){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var i,a,l,c,u=[],d=!0,p=!1;try{if(l=(n=n.call(r)).next,s===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(i=l.call(n)).done)&&(u.push(i.value),u.length!==s);d=!0);}catch(b){p=!0,a=b}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Wu=pe((o,e)=>{le(),ue(),ce();function t(r,s){(s==null||s>r.length)&&(s=r.length);for(var n=0,i=Array(s);n<s;n++)i[n]=r[n];return i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),zu=pe((o,e)=>{le(),ue(),ce();var t=Wu();function r(s,n){if(s){if(typeof s=="string")return t(s,n);var i={}.toString.call(s).slice(8,-1);return i==="Object"&&s.constructor&&(i=s.constructor.name),i==="Map"||i==="Set"?Array.from(s):i==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(s,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Vu=pe((o,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}),Ku=pe((o,e)=>{le(),ue(),ce();var t=qu(),r=Hu(),s=zu(),n=Vu();function i(a,l){return t(a)||r(a,l)||s(a,l)||n()}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),tl=pe((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(o,function(t){var r=function(b){return function(f){var g=b(f);return f.add(g),g}},s=function(b){return function(f,g){return b.set(f,g),g}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,a=i*2,l=function(b,f){return function(g){var y=f.get(g),w=y===void 0?g.size:y<a?y+1:0;if(!g.has(w))return b(g,w);if(g.size<i){for(;g.has(w);)w=Math.floor(Math.random()*a);return b(g,w)}if(g.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;g.has(w);)w=Math.floor(Math.random()*n);return b(g,w)}},c=new WeakMap,u=s(c),d=l(u,c),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),Gu=pe((o,e)=>{le(),ue(),ce();function t(s,n,i,a,l,c,u){try{var d=s[c](u),p=d.value}catch(b){return void i(b)}d.done?n(p):Promise.resolve(p).then(a,l)}function r(s){return function(){var n=this,i=arguments;return new Promise(function(a,l){var c=s.apply(n,i);function u(p){t(c,a,l,u,d,"next",p)}function d(p){t(c,a,l,u,d,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),rl=pe((o,e)=>{le(),ue(),ce();function t(r,s){this.v=r,this.k=s}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),nl=pe((o,e)=>{le(),ue(),ce();function t(r,s,n,i){var a=Object.defineProperty;try{a({},"",{})}catch{a=0}e.exports=t=function(l,c,u,d){function p(b,f){t(l,b,function(g){return this._invoke(b,f,g)})}c?a?a(l,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):l[c]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,s,n,i)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),il=pe((o,e)=>{le(),ue(),ce();var t=nl();function r(){var s,n,i=typeof Symbol=="function"?Symbol:{},a=i.iterator||"@@iterator",l=i.toStringTag||"@@toStringTag";function c(w,m,_,x){var v=m&&m.prototype instanceof d?m:d,E=Object.create(v.prototype);return t(E,"_invoke",(function(S,A,C){var O,j,T,B=0,D=C||[],U=!1,oe={p:0,n:0,v:s,a:Y,f:Y.bind(s,4),d:function(W,re){return O=W,j=0,T=s,oe.n=re,u}};function Y(W,re){for(j=W,T=re,n=0;!U&&B&&!$&&n<D.length;n++){var $,Z=D[n],M=oe.p,Q=Z[2];W>3?($=Q===re)&&(T=Z[(j=Z[4])?5:(j=3,3)],Z[4]=Z[5]=s):Z[0]<=M&&(($=W<2&&M<Z[1])?(j=0,oe.v=re,oe.n=Z[1]):M<Q&&($=W<3||Z[0]>re||re>Q)&&(Z[4]=W,Z[5]=re,oe.n=Q,j=0))}if($||W>1)return u;throw U=!0,re}return function(W,re,$){if(B>1)throw TypeError("Generator is already running");for(U&&re===1&&Y(re,$),j=re,T=$;(n=j<2?s:T)||!U;){O||(j?j<3?(j>1&&(oe.n=-1),Y(j,T)):oe.n=T:oe.v=T);try{if(B=2,O){if(j||(W="next"),n=O[W]){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 '"+W+"' method"),j=1);O=s}else if((n=(U=oe.n<0)?T:S.call(A,oe))!==u)break}catch(Z){O=s,j=1,T=Z}finally{B=1}}return{value:n,done:U}}})(w,_,x),!0),E}var u={};function d(){}function p(){}function b(){}n=Object.getPrototypeOf;var f=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),g=b.prototype=d.prototype=Object.create(f);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,b):(w.__proto__=b,t(w,l,"GeneratorFunction")),w.prototype=Object.create(g),w}return p.prototype=b,t(g,"constructor",b),t(b,"constructor",p),p.displayName="GeneratorFunction",t(b,l,"GeneratorFunction"),t(g),t(g,l,"Generator"),t(g,a,function(){return this}),t(g,"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}),ol=pe((o,e)=>{le(),ue(),ce();var t=rl(),r=nl();function s(n,i){function a(c,u,d,p){try{var b=n[c](u),f=b.value;return f instanceof t?i.resolve(f.v).then(function(g){a("next",g,d,p)},function(g){a("throw",g,d,p)}):i.resolve(f).then(function(g){b.value=g,d(b)},function(g){return a("throw",g,d,p)})}catch(g){p(g)}}var l;this.next||(r(s.prototype),r(s.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function p(){return new i(function(b,f){a(c,d,b,f)})}return l=l?l.then(p,p):p()},!0)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),sl=pe((o,e)=>{le(),ue(),ce();var t=il(),r=ol();function s(n,i,a,l,c){return new r(t().w(n,i,a,l),c||Promise)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Yu=pe((o,e)=>{le(),ue(),ce();var t=sl();function r(s,n,i,a,l){var c=t(s,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}),Ju=pe((o,e)=>{le(),ue(),ce();function t(r){var s=Object(r),n=[];for(var i in s)n.unshift(i);return function a(){for(;n.length;)if((i=n.pop())in s)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}),Qu=pe((o,e)=>{le(),ue(),ce();var t=Qr().default;function r(s){if(s!=null){var n=s[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],i=0;if(n)return n.call(s);if(typeof s.next=="function")return s;if(!isNaN(s.length))return{next:function(){return s&&i>=s.length&&(s=void 0),{value:s&&s[i++],done:!s}}}}throw new TypeError(t(s)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Xu=pe((o,e)=>{le(),ue(),ce();var t=rl(),r=il(),s=Yu(),n=sl(),i=ol(),a=Ju(),l=Qu();function c(){var u=r(),d=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function b(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function g(y){var w,m;return function(_){w||(w={stop:function(){return m(_.a,2)},catch:function(){return _.v},abrupt:function(x,v){return m(_.a,f[x],v)},delegateYield:function(x,v,E){return w.resultName=v,m(_.d,l(x),E)},finish:function(x){return m(_.f,x)}},m=function(x,v,E){_.p=w.prev,_.n=w.next;try{return x(v,E)}finally{w.next=_.n}}),w.resultName&&(w[w.resultName]=_.v,w.resultName=void 0),w.sent=_.v,w.next=_.n;try{return y.call(this,w)}finally{_.p=w.prev,_.n=w.next}}}return(e.exports=c=function(){return{wrap:function(y,w,m,_){return u.w(g(y),w,m,_&&_.reverse())},isGeneratorFunction:b,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:i,async:function(y,w,m,_,x){return(b(w)?n:s)(g(y),w,m,_,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((o,e)=>{le(),ue(),ce();var t=Xu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),ed=pe((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o,$u(),Ku(),tl(),Gu(),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))})(o,function(t,r,s,n,i,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,_){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);_&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function d(m){for(var _=1;_<arguments.length;_++){var x=arguments[_]!=null?arguments[_]:{};_%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 p=function(m){return d(d({},m),{},{connect:function(_){var x=_.call;return i(a.mark(function v(){var E,S,A,C;return a.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return E=new MessageChannel,S=E.port1,A=E.port2,O.next=1,x("connect",{port:S},[S]);case 1:return C=O.sent,c.set(A,C),O.abrupt("return",A);case 2:case"end":return O.stop()}},v)}))},disconnect:function(_){var x=_.call;return(function(){var v=i(a.mark(function E(S){var A;return a.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(A=c.get(S),A!==void 0){C.next=1;break}throw new Error("The given port is not connected.");case 1:return C.next=2,x("disconnect",{portId:A});case 2:case"end":return C.stop()}},E)}));return function(E){return v.apply(this,arguments)}})()},isSupported:function(_){var x=_.call;return function(){return x("isSupported")}}})};function b(m,_){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);_&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function f(m){for(var _=1;_<arguments.length;_++){var x=arguments[_]!=null?arguments[_]:{};_%2?b(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):b(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var g=new WeakMap,y=function(m){if(g.has(m))return g.get(m);var _=new Map;return g.set(m,_),_},w=function(m){var _=p(m);return function(x){var v=y(x);x.addEventListener("message",function(D){var U=D.data,oe=U.id;if(oe!==null&&v.has(oe)){var Y=v.get(oe),W=Y.reject,re=Y.resolve;v.delete(oe),U.error===void 0?re(U.result):W(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,oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(Y,W){var re=n.generateUniqueNumber(v);v.set(re,{reject:W,resolve:Y}),U===null?x.postMessage({id:re,method:D},oe):x.postMessage({id:re,method:D,params:U},oe)})},S=function(D,U){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:D,params:U},oe)},A={},C=0,O=Object.entries(_);C<O.length;C++){var j=s(O[C],2),T=j[0],B=j[1];A=f(f({},A),{},r({},T,B({call:E,notify:S})))}return f({},A)}};t.createBroker=w})}),td=pe((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o,Qr(),ed(),tl()):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))})(o,function(t,r,s,n){var i=new Map([[0,null]]),a=new Map([[0,null]]),l=s.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(i.get(p))==="symbol"&&(i.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){i.delete(p)}))}},clearTimeout:function(u){var d=u.call;return function(p){r(a.get(p))==="symbol"&&(a.set(p,null),d("clear",{timerId:p,timerType:"timeout"}).then(function(){a.delete(p)}))}},setInterval:function(u){var d=u.call;return function(p){for(var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,g=new Array(f>2?f-2:0),y=2;y<f;y++)g[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(i);i.set(m,w);var _=function(){return d("set",{delay:b,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&&(p.apply(void 0,g),i.get(m)===w&&_())})};return _(),m}},setTimeout:function(u){var d=u.call;return function(p){for(var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,g=new Array(f>2?f-2:0),y=2;y<f;y++)g[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(a);return a.set(m,w),d("set",{delay:b,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var _=a.get(m);if(_===void 0)throw new Error("The timer is in an undefined state.");_===w&&(a.delete(m),p.apply(void 0,g))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),rd=pe((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o,td()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(o,function(t,r){var s=function(d,p){var b=null;return function(){if(b!==null)return b;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),g=URL.createObjectURL(f);return b=d(g),setTimeout(function(){return URL.revokeObjectURL(g)}),b}},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=s(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})}),Xr=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.isReactNativeBrowser=o.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",s=e()||t()||r();o.isWebWorker=t(),o.isReactNativeBrowser=r(),o.default=s}),nd=pe(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(c,u,d,p){p===void 0&&(p=d);var b=Object.getOwnPropertyDescriptor(u,d);(!b||("get"in b?!u.__esModule:b.writable||b.configurable))&&(b={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,p,b)}:function(c,u,d,p){p===void 0&&(p=d),c[p]=u[d]}),t=o&&o.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=o&&o.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(d){var p=[];for(var b in d)Object.prototype.hasOwnProperty.call(d,b)&&(p[p.length]=b);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var p=c(u),b=0;b<p.length;b++)p[b]!=="default"&&e(d,u,p[b]);return t(d,u),d}})();Object.defineProperty(o,"__esModule",{value:!0});var s=rd(),n=r(Xr()),i={set:s.setInterval,clear:s.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}};o.default=l}),al=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(o,"__esModule",{value:!0});var t=e(nd()),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(s,n){this.client=s,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(s.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(s){if(s*=1e3,isNaN(s)||s<=0||s>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${s}`);this._keepalive=s,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${s}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let s=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+s,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)}};o.default=r}),xi=pe(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(v,E,S,A){A===void 0&&(A=S);var C=Object.getOwnPropertyDescriptor(E,S);(!C||("get"in C?!E.__esModule:C.writable||C.configurable))&&(C={enumerable:!0,get:function(){return E[S]}}),Object.defineProperty(v,A,C)}:function(v,E,S,A){A===void 0&&(A=S),v[A]=E[S]}),t=o&&o.__setModuleDefault||(Object.create?function(v,E){Object.defineProperty(v,"default",{enumerable:!0,value:E})}:function(v,E){v.default=E}),r=o&&o.__importStar||(function(){var v=function(E){return v=Object.getOwnPropertyNames||function(S){var A=[];for(var C in S)Object.prototype.hasOwnProperty.call(S,C)&&(A[A.length]=C);return A},v(E)};return function(E){if(E&&E.__esModule)return E;var S={};if(E!=null)for(var A=v(E),C=0;C<A.length;C++)A[C]!=="default"&&e(S,E,A[C]);return t(S,E),S}})(),s=o&&o.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(o,"__esModule",{value:!0});var n=s(fu()),i=Bt(),a=s(mu()),l=s(pt()),c=r(ja()),u=s(Ua()),d=s(ju()),p=s(el()),b=s(Uu()),f=Jt(),g=Bu(),y=s(al()),w=r(Xr()),m=globalThis.setImmediate||((...v)=>{let E=v.shift();(0,f.nextTick)(()=>{E(...v)})}),_={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 Si extends g.TypedEventEmitter{static VERSION=f.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 A in _)typeof this.options[A]>"u"?this.options[A]=_[A]:this.options[A]=S[A];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",Si.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:Si.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=S.protocolVersion===5&&S.customHandleAcks?S.customHandleAcks:(...A)=>{A[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=E,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new p.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 b.default(S.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:A}=this,C=()=>{let O=A.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,B=>{O.cb&&O.cb(B),C()}):(this.log("messageId: %d has already used. The message is skipped and removed.",j.messageId),C())};this.log("connect :: sending queued packets"),C()}),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),A=null,C=[];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."),C.push(D)});let O=()=>{this.log("work :: getting next packet in queue");let D=C.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=A;A=null,this.log("work :: done flag is %s",!!U),U&&U()}},j=()=>{if(C.length)(0,f.nextTick)(O);else{let D=A;A=null,D()}};E._write=(D,U,oe)=>{A=oe,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 B={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&&(B.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(B.properties||(B.properties={}),this.topicAliasRecv&&(B.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(B),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,A,C){this.log("publish :: message `%s` to topic `%s`",S,E);let{options:O}=this;typeof A=="function"&&(C=A,A=null),A=A||{},A={qos:0,retain:!1,dup:!1,...A};let{qos:j,retain:T,dup:B,properties:D,cbStorePut:U}=A;if(this._checkDisconnecting(C))return this;let oe=()=>{let Y=0;if((j===1||j===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let W={cmd:"publish",topic:E,payload:S,qos:j,retain:T,messageId:Y,dup:B};switch(O.protocolVersion===5&&(W.properties=D),this.log("publish :: qos",j),j){case 1:case 2:this.outgoing[W.messageId]={volatile:!1,cb:C||this.noop},this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,void 0,U);break;default:this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,C,U);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!oe())&&this._storeProcessingQueue.push({invoke:oe,cbStorePut:A.cbStorePut,callback:C}),this}publishAsync(E,S,A){return new Promise((C,O)=>{this.publish(E,S,A,(j,T)=>{j?O(j):C(T)})})}subscribe(E,S,A){let C=this.options.protocolVersion;typeof S=="function"&&(A=S),A=A||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(A,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(A))return this.log("subscribe: discconecting true"),this;let B={qos:0};C===5&&(B.nl=!1,B.rap=!1,B.rh=0),S={...B,...S};let{properties:D}=S,U=[],oe=(re,$)=>{if($=$||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<$.qos||O){let Z={topic:re,qos:$.qos};C===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),oe(re)}):Object.keys(E).forEach(re=>{this.log("subscribe: object topic %s, %o",re,E[re]),oe(re,E[re])}),!U.length)return A(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};C===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 f.ErrorWithSubackPacket(te.message,we)):Q(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),M},W=()=>{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=>{A(null,U,Z.at(-1))}).catch(Z=>{A(Z,U,Z.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!W())&&this._storeProcessingQueue.push({invoke:W,callback:A}),this}subscribeAsync(E,S){return new Promise((A,C)=>{this.subscribe(E,S,(O,j)=>{O?C(O):A(j)})})}unsubscribe(E,S,A){typeof E=="string"&&(E=[E]),typeof S=="function"&&(A=S),A=A||this.noop;let C=c.validateTopics(E);if(C!==null)return m(A,new Error(`Invalid topic ${C}`)),this;if(this._checkDisconnecting(A))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(B=>{delete this._resubscribeTopics[B]}),typeof S=="object"&&S.properties&&(T.properties=S.properties),this.outgoing[T.messageId]={volatile:!0,cb:A},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!O())&&this._storeProcessingQueue.push({invoke:O,callback:A}),this}unsubscribeAsync(E,S){return new Promise((A,C)=>{this.unsubscribe(E,S,(O,j)=>{O?C(O):A(j)})})}end(E,S,A){this.log("end :: (%s)",this.options.clientId),(E==null||typeof E!="boolean")&&(A=A||S,S=E,E=!1),typeof S!="object"&&(A=A||S,S=null),this.log("end :: cb? %s",!!A),(!A||typeof A!="function")&&(A=this.noop);let C=()=>{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"),A){let B=j||T;this.log("end :: closeStores: invoking callback with args"),A(B)}})}),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,f.nextTick)(C)},S)};return this.disconnecting?(A(),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((A,C)=>{this.end(E,S,O=>{O?C(O):A()})})}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 A=E.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",S,A),A.length===0){if(typeof S>"u")return new Error("Unregistered Topic Alias");if(A=this.topicAliasSend.getTopicByAlias(S),typeof A>"u")return new Error("Unregistered Topic Alias");E.topic=A}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,A={}){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 C={cmd:"disconnect",...A};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(C,()=>{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,A){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",E.cmd);let C=E,O;if(C.cmd==="publish"&&(C=(0,a.default)(E),O=this._removeTopicAliasAndRecoverTopicName(C),O))return S&&S(O);this.outgoingStore.put(C,j=>{if(j)return S&&S(j);A(),this._writePacket(E,S)})}_applyTopicAlias(E){if(this.options.protocolVersion===5&&E.cmd==="publish"){let S;E.properties&&(S=E.properties.topicAlias);let A=E.topic.toString();if(this.topicAliasSend)if(S){if(A.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",A,S),!this.topicAliasSend.put(A,S)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,S),new Error("Sending Topic Alias out of range")}else A.length!==0&&(this.options.autoAssignTopicAlias?(S=this.topicAliasSend.getAliasByTopic(A),S?(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",A,S)):(S=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(A,S),E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",A,S))):this.options.autoUseTopicAlias&&(S=this.topicAliasSend.getAliasByTopic(A),S&&(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",A,S))));else if(S)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,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 A=n.default.writeToStream(E,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",A),!A&&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,A,C){this.log("_sendPacket :: (%s) :: start",this.options.clientId),A=A||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,A);return}if(C){this._writePacket(E,S);return}switch(E.cmd){case"publish":break;case"pubrel":this._storeAndSend(E,S,A);return;default:this._writePacket(E,S);return}switch(E.qos){case 2:case 1:this._storeAndSend(E,S,A);break;default:this._writePacket(E,S);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(E,S,A){this.log("_storePacket :: packet: %o",E),this.log("_storePacket :: cb? %s",!!S),A=A||this.noop;let C=E;if(C.cmd==="publish"){C=(0,a.default)(E);let j=this._removeTopicAliasAndRecoverTopicName(C);if(j)return S&&S(j)}let O=C.qos||0;O===0&&this.queueQoSZero||C.cmd!=="publish"?this.queue.push({packet:C,cb:S}):O>0?(S=this.outgoing[C.messageId]?this.outgoing[C.messageId].cb:null,this.outgoingStore.put(C,j=>{if(j)return S&&S(j);A()})):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 A={};A[E[S]]=this._resubscribeTopics[E[S]],A.resubscribe=!0,this.subscribe(A,{properties:A[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 A=this.outgoingStore.createStream(),C=()=>{A.destroy(),A=null,this._flushStoreProcessingQueue(),O()},O=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",C),A.on("error",T=>{O(),this._flushStoreProcessingQueue(),this.removeListener("close",C),this.emit("error",T)});let j=()=>{if(!A)return;let T=A.read(1),B;if(!T){A.once("readable",j);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){j();return}!this.disconnecting&&!this.reconnectTimer?(B=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(D,U){B&&B(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)):A.destroy&&A.destroy()};A.on("end",()=>{let T=!0;for(let B in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[B]){T=!1;break}this.removeListener("close",C),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},(A,C)=>{S(A,C),this.messageIdProvider.deallocate(E),this._invokeStoreProcessingQueue()})}};o.default=x}),id=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=Za(),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()}};o.default=t});function od(){if(Ei)return wr;Ei=!0;let o=2147483647,e=36,t=1,r=26,s=38,n=700,i=72,a=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},b=e-t,f=Math.floor,g=String.fromCharCode;function y(O){throw new RangeError(p[O])}function w(O,j){let T=[],B=O.length;for(;B--;)T[B]=j(O[B]);return T}function m(O,j){let T=O.split("@"),B="";T.length>1&&(B=T[0]+"@",O=T[1]),O=O.replace(d,".");let D=O.split("."),U=w(D,j).join(".");return B+U}function _(O){let j=[],T=0,B=O.length;for(;T<B;){let D=O.charCodeAt(T++);if(D>=55296&&D<=56319&&T<B){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 B=0;for(O=T?f(O/n):O>>1,O+=f(O/j);O>b*r>>1;B+=e)O=f(O/b);return f(B+(b+1)*O/(O+s))},A=function(O){let j=[],T=O.length,B=0,D=a,U=i,oe=O.lastIndexOf(l);oe<0&&(oe=0);for(let Y=0;Y<oe;++Y)O.charCodeAt(Y)>=128&&y("not-basic"),j.push(O.charCodeAt(Y));for(let Y=oe>0?oe+1:0;Y<T;){let W=B;for(let $=1,Z=e;;Z+=e){Y>=T&&y("invalid-input");let M=v(O.charCodeAt(Y++));M>=e&&y("invalid-input"),M>f((o-B)/$)&&y("overflow"),B+=M*$;let Q=Z<=U?t:Z>=U+r?r:Z-U;if(M<Q)break;let be=e-Q;$>f(o/be)&&y("overflow"),$*=be}let re=j.length+1;U=S(B-W,re,W==0),f(B/re)>o-D&&y("overflow"),D+=f(B/re),B%=re,j.splice(B++,0,D)}return String.fromCodePoint(...j)},C=function(O){let j=[];O=_(O);let T=O.length,B=a,D=0,U=i;for(let W of O)W<128&&j.push(g(W));let oe=j.length,Y=oe;for(oe&&j.push(l);Y<T;){let W=o;for(let $ of O)$>=B&&$<W&&(W=$);let re=Y+1;W-B>f((o-D)/re)&&y("overflow"),D+=(W-B)*re,B=W;for(let $ of O)if($<B&&++D>o&&y("overflow"),$===B){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(g(E(Q+be%te,0))),Z=f(be/te)}j.push(g(E(Z,0))),U=S(D,re,Y===oe),D=0,++Y}++D,++B}return j.join("")};return wr={version:"2.3.1",ucs2:{decode:_,encode:x},decode:A,encode:C,toASCII:function(O){return m(O,function(j){return u.test(j)?"xn--"+C(j):j})},toUnicode:function(O){return m(O,function(j){return c.test(j)?A(j.slice(4).toLowerCase()):j})}},wr}var wr,Ei,xt,sd=Je(()=>{le(),ue(),ce(),wr={},Ei=!1,xt=od(),xt.decode,xt.encode,xt.toASCII,xt.toUnicode,xt.ucs2,xt.version});function ad(){return Ii||(Ii=!0,Ai=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var o={},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;o[e]=r;for(e in o)return!1;if(typeof Object.keys=="function"&&Object.keys(o).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(o).length!==0)return!1;var s=Object.getOwnPropertySymbols(o);if(s.length!==1||s[0]!==e||!Object.prototype.propertyIsEnumerable.call(o,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(o,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),Ai}function ld(){return Ci||(Ci=!0,Ti=Error),Ti}function cd(){return Oi||(Oi=!0,Pi=EvalError),Pi}function ud(){return Ri||(Ri=!0,Mi=RangeError),Mi}function dd(){return Ni||(Ni=!0,Li=ReferenceError),Li}function ll(){return Ui||(Ui=!0,ji=SyntaxError),ji}function dr(){return Di||(Di=!0,Bi=TypeError),Bi}function hd(){return $i||($i=!0,Fi=URIError),Fi}function fd(){if(qi)return _r;qi=!0;var o=typeof Symbol<"u"&&Symbol,e=ad();return _r=function(){return typeof o!="function"||typeof Symbol!="function"||typeof o("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},_r}function pd(){if(Hi)return kr;Hi=!0;var o={__proto__:null,foo:{}},e=Object;return kr=function(){return{__proto__:o}.foo===o.foo&&!(o instanceof e)},kr}function md(){if(Wi)return xr;Wi=!0;var o="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",s=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 xr=function(a){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(o+l);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var y=l.apply(this,s(c,arguments));return Object(y)===y?y:this}return l.apply(a,s(c,arguments))},p=t(0,l.length-c.length),b=[],f=0;f<p;f++)b[f]="$"+f;if(u=Function("binder","return function ("+i(b,",")+"){ return binder.apply(this,arguments); }")(d),l.prototype){var g=function(){};g.prototype=l.prototype,u.prototype=new g,g.prototype=null}return u},xr}function ko(){if(zi)return Sr;zi=!0;var o=md();return Sr=Function.prototype.bind||o,Sr}function gd(){if(Vi)return Er;Vi=!0;var o=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=ko();return Er=t.call(o,e),Er}function Qt(){if(Ki)return Ar;Ki=!0;var o,e=ld(),t=cd(),r=ud(),s=dd(),n=ll(),i=dr(),a=hd(),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},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,b=fd()(),f=pd()(),g=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),y={},w=typeof Uint8Array>"u"||!g?o:g(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?o:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?o:ArrayBuffer,"%ArrayIteratorPrototype%":b&&g?g([][Symbol.iterator]()):o,"%AsyncFromSyncIteratorPrototype%":o,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":typeof Atomics>"u"?o:Atomics,"%BigInt%":typeof BigInt>"u"?o:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?o:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?o:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?o:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?o:Float32Array,"%Float64Array%":typeof Float64Array>"u"?o:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?o:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":y,"%Int8Array%":typeof Int8Array>"u"?o:Int8Array,"%Int16Array%":typeof Int16Array>"u"?o:Int16Array,"%Int32Array%":typeof Int32Array>"u"?o:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":b&&g?g(g([][Symbol.iterator]())):o,"%JSON%":typeof JSON=="object"?JSON:o,"%Map%":typeof Map>"u"?o:Map,"%MapIteratorPrototype%":typeof Map>"u"||!b||!g?o:g(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?o:Promise,"%Proxy%":typeof Proxy>"u"?o:Proxy,"%RangeError%":r,"%ReferenceError%":s,"%Reflect%":typeof Reflect>"u"?o:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?o:Set,"%SetIteratorPrototype%":typeof Set>"u"||!b||!g?o:g(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?o:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":b&&g?g(""[Symbol.iterator]()):o,"%Symbol%":b?Symbol:o,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":w,"%TypeError%":i,"%Uint8Array%":typeof Uint8Array>"u"?o:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?o:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?o:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?o:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?o:WeakMap,"%WeakRef%":typeof WeakRef>"u"?o:WeakRef,"%WeakSet%":typeof WeakSet>"u"?o:WeakSet};if(g)try{null.error}catch(Y){var _=g(g(Y));m["%Error.prototype%"]=_}var x=function Y(W){var re;if(W==="%AsyncFunction%")re=c("async function () {}");else if(W==="%GeneratorFunction%")re=c("function* () {}");else if(W==="%AsyncGeneratorFunction%")re=c("async function* () {}");else if(W==="%AsyncGenerator%"){var $=Y("%AsyncGeneratorFunction%");$&&(re=$.prototype)}else if(W==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&g&&(re=g(Z.prototype))}return m[W]=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=ko(),S=gd(),A=E.call(Function.call,Array.prototype.concat),C=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),B=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,D=/\\(\\)?/g,U=function(Y){var W=j(Y,0,1),re=j(Y,-1);if(W==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&W!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var $=[];return O(Y,B,function(Z,M,Q,be){$[$.length]=Q?O(be,D,"$1"):M||Z}),$},oe=function(Y,W){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"&&!W)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 Ar=function(Y,W){if(typeof Y!="string"||Y.length===0)throw new i("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof W!="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=oe("%"+$+"%",W),M=Z.name,Q=Z.value,be=!1,te=Z.alias;te&&($=te[0],C(re,A([0,1],te)));for(var we=1,K=!0;we<re.length;we+=1){var N=re[we],ne=j(N,0,1),z=j(N,-1);if((ne==='"'||ne==="'"||ne==="`"||z==='"'||z==="'"||z==="`")&&ne!==z)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(!W)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},Ar}function xo(){if(Gi)return Ir;Gi=!0;var o=Qt(),e=o("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Ir=e,Ir}function cl(){if(Yi)return Tr;Yi=!0;var o=Qt(),e=o("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Tr=e,Tr}function bd(){if(Ji)return Cr;Ji=!0;var o=xo(),e=ll(),t=dr(),r=cl();return Cr=function(s,n,i){if(!s||typeof s!="object"&&typeof s!="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(s,n);if(o)o(s,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)s[n]=i;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Cr}function yd(){if(Qi)return Pr;Qi=!0;var o=xo(),e=function(){return!!o};return e.hasArrayLengthDefineBug=function(){if(!o)return null;try{return o([],"length",{value:1}).length!==1}catch{return!0}},Pr=e,Pr}function vd(){if(Xi)return Or;Xi=!0;var o=Qt(),e=bd(),t=yd()(),r=cl(),s=dr(),n=o("%Math.floor%");return Or=function(i,a){if(typeof i!="function")throw new s("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new s("`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},Or}function wd(){if(Zi)return Wt;Zi=!0;var o=ko(),e=Qt(),t=vd(),r=dr(),s=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||o.call(n,s),a=xo(),l=e("%Math.max%");Wt=function(u){if(typeof u!="function")throw new r("a function is required");var d=i(o,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return i(o,s,arguments)};return a?a(Wt,"apply",{value:c}):Wt.apply=c,Wt}function _d(){if(eo)return Mr;eo=!0;var o=Qt(),e=wd(),t=e(o("String.prototype.indexOf"));return Mr=function(r,s){var n=o(r,!!s);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Mr}var Ai,Ii,Ti,Ci,Pi,Oi,Mi,Ri,Li,Ni,ji,Ui,Bi,Di,Fi,$i,_r,qi,kr,Hi,xr,Wi,Sr,zi,Er,Vi,Ar,Ki,Ir,Gi,Tr,Yi,Cr,Ji,Pr,Qi,Or,Xi,Wt,Zi,Mr,eo,kd=Je(()=>{le(),ue(),ce(),Ai={},Ii=!1,Ti={},Ci=!1,Pi={},Oi=!1,Mi={},Ri=!1,Li={},Ni=!1,ji={},Ui=!1,Bi={},Di=!1,Fi={},$i=!1,_r={},qi=!1,kr={},Hi=!1,xr={},Wi=!1,Sr={},zi=!1,Er={},Vi=!1,Ar={},Ki=!1,Ir={},Gi=!1,Tr={},Yi=!1,Cr={},Ji=!1,Pr={},Qi=!1,Or={},Xi=!1,Wt={},Zi=!1,Mr={},eo=!1});function So(o){throw new Error("Node.js process "+o+" is not supported by JSPM core outside of Node.js")}function xd(){!Lt||!Mt||(Lt=!1,Mt.length?at=Mt.concat(at):lr=-1,at.length&&ul())}function ul(){if(!Lt){var o=setTimeout(xd,0);Lt=!0;for(var e=at.length;e;){for(Mt=at,at=[];++lr<e;)Mt&&Mt[lr].run();lr=-1,e=at.length}Mt=null,Lt=!1,clearTimeout(o)}}function Sd(o){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];at.push(new dl(o,e)),at.length===1&&!Lt&&setTimeout(ul,0)}function dl(o,e){this.fun=o,this.array=e}function We(){}function Ed(o){So("_linkedBinding")}function Ad(o){So("dlopen")}function Id(){return[]}function Td(){return[]}function Cd(o,e){if(!o)throw new Error(e||"assertion error")}function Pd(){return!1}function Od(){return ht.now()/1e3}function rn(o){var e=Math.floor((Date.now()-ht.now())*.001),t=ht.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return o&&(r=r-o[0],s=s-o[1],s<0&&(r--,s+=Rr)),[r,s]}function vt(){return Eo}function Md(o){return[]}var at,Lt,Mt,lr,Bo,Do,Fo,$o,qo,Ho,Wo,zo,Vo,Ko,Go,Yo,Jo,Qo,Xo,Zo,es,ts,rs,ns,is,pr,os,ss,as,ls,cs,us,ds,hs,fs,ps,ms,gs,bs,ys,vs,ws,_s,ks,xs,Ss,Es,As,Is,Ts,Cs,ht,nn,Rr,Ps,Os,Ms,Rs,Ls,Ns,js,Us,Bs,Ds,Fs,Eo,hl=Je(()=>{le(),ue(),ce(),at=[],Lt=!1,lr=-1,dl.prototype.run=function(){this.fun.apply(null,this.array)},Bo="browser",Do="x64",Fo="browser",$o={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},qo=["/usr/bin/node"],Ho=[],Wo="v16.8.0",zo={},Vo=function(o,e){console.warn((e?e+": ":"")+o)},Ko=function(o){So("binding")},Go=function(o){return 0},Yo=function(){return"/"},Jo=function(o){},Qo={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Xo=We,Zo=[],es={},ts=!1,rs={},ns=We,is=We,pr=function(){return{}},os=pr,ss=pr,as=We,ls=We,cs=We,us={},ds={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},hs=We,fs=We,ps=We,ms=We,gs=We,bs=We,ys=We,vs=void 0,ws=void 0,_s=void 0,ks=We,xs=2,Ss=1,Es="/bin/usr/node",As=9229,Is="node",Ts=[],Cs=We,ht={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ht.now===void 0&&(nn=Date.now(),ht.timing&&ht.timing.navigationStart&&(nn=ht.timing.navigationStart),ht.now=()=>Date.now()-nn),Rr=1e9,rn.bigint=function(o){var e=rn(o);return typeof BigInt>"u"?e[0]*Rr+e[1]:BigInt(e[0]*Rr)+BigInt(e[1])},Ps=10,Os={},Ms=0,Rs=vt,Ls=vt,Ns=vt,js=vt,Us=vt,Bs=We,Ds=vt,Fs=vt,Eo={version:Wo,versions:zo,arch:Do,platform:Fo,release:Qo,_rawDebug:Xo,moduleLoadList:Zo,binding:Ko,_linkedBinding:Ed,_events:Os,_eventsCount:Ms,_maxListeners:Ps,on:vt,addListener:Rs,once:Ls,off:Ns,removeListener:js,removeAllListeners:Us,emit:Bs,prependListener:Ds,prependOnceListener:Fs,listeners:Md,domain:es,_exiting:ts,config:rs,dlopen:Ad,uptime:Od,_getActiveRequests:Id,_getActiveHandles:Td,reallyExit:ns,_kill:is,cpuUsage:pr,resourceUsage:os,memoryUsage:ss,kill:as,exit:ls,openStdin:cs,allowedNodeEnvironmentFlags:us,assert:Cd,features:ds,_fatalExceptions:hs,setUncaughtExceptionCaptureCallback:fs,hasUncaughtExceptionCaptureCallback:Pd,emitWarning:Vo,nextTick:Sd,_tickCallback:ps,_debugProcess:ms,_debugEnd:gs,_startProfilerIdleNotifier:bs,_stopProfilerIdleNotifier:ys,stdout:vs,stdin:_s,stderr:ws,abort:ks,umask:Go,chdir:Jo,cwd:Yo,env:$o,title:Bo,argv:qo,execArgv:Ho,pid:xs,ppid:Ss,execPath:Es,debugPort:As,hrtime:rn,argv0:Is,_preload_modules:Ts,setSourceMapsEnabled:Cs}});function Rd(){if(to)return Lr;to=!0;var o=Eo;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,p=0;p<=n.length;++p){if(p<n.length)d=n.charCodeAt(p);else{if(d===47)break;d=47}if(d===47){if(!(c===p-1||u===1))if(c!==p-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 b=a.lastIndexOf("/");if(b!==a.length-1){b===-1?(a="",l=0):(a=a.slice(0,b),l=a.length-1-a.lastIndexOf("/")),c=p,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=p,u=0;continue}}i&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,p):a=n.slice(c+1,p),l=p-c-1;c=p,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 s={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=o.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?".":s.normalize(n)},relative:function(n,i){if(e(n),e(i),n===i||(n=s.resolve(n),i=s.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,p=d-u,b=c<p?c:p,f=-1,g=0;g<=b;++g){if(g===b){if(p>b){if(i.charCodeAt(u+g)===47)return i.slice(u+g+1);if(g===0)return i.slice(u+g)}else c>b&&(n.charCodeAt(a+g)===47?f=g:g===0&&(f=0));break}var y=n.charCodeAt(a+g),w=i.charCodeAt(u+g);if(y!==w)break;y===47&&(f=g)}var m="";for(g=a+f+1;g<=l;++g)(g===l||n.charCodeAt(g)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+i.slice(u+f):(u+=f,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,p=-1;for(u=n.length-1;u>=0;--u){var b=n.charCodeAt(u);if(b===47){if(!c){a=u+1;break}}else p===-1&&(c=!1,p=u+1),d>=0&&(b===i.charCodeAt(d)?--d===-1&&(l=u):(d=-1,l=p))}return a===l?l=p: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 p=n.charCodeAt(d);if(p===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),p===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,p=-1,b=!0,f=n.length-1,g=0;f>=c;--f){if(a=n.charCodeAt(f),a===47){if(!b){d=f+1;break}continue}p===-1&&(b=!1,p=f+1),a===46?u===-1?u=f:g!==1&&(g=1):u!==-1&&(g=-1)}return u===-1||p===-1||g===0||g===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&l?i.base=i.name=n.slice(1,p):i.base=i.name=n.slice(d,p)):(d===0&&l?(i.name=n.slice(1,u),i.base=n.slice(1,p)):(i.name=n.slice(d,u),i.base=n.slice(d,p)),i.ext=n.slice(u,p)),d>0?i.dir=n.slice(0,d-1):l&&(i.dir="/"),i},sep:"/",delimiter:":",win32:null,posix:null};return s.posix=s,Lr=s,Lr}var Lr,to,ro,Ld=Je(()=>{le(),ue(),ce(),hl(),Lr={},to=!1,ro=Rd()}),fl={};Gt(fl,{URL:()=>xl,Url:()=>yl,default:()=>ze,fileURLToPath:()=>ml,format:()=>vl,parse:()=>kl,pathToFileURL:()=>gl,resolve:()=>wl,resolveObject:()=>_l});function Nd(){if(no)return Nr;no=!0;var o=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&o?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=o&&e&&typeof e.get=="function"?e.get:null,r=o&&Map.prototype.forEach,s=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,i=s&&n&&typeof n.get=="function"?n.get:null,a=s&&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,p=typeof WeakRef=="function"&&WeakRef.prototype,b=p?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,g=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,_=String.prototype.replace,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,E=RegExp.prototype.test,S=Array.prototype.concat,A=Array.prototype.join,C=Array.prototype.slice,O=Math.floor,j=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,B=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,oe=Object.prototype.propertyIsEnumerable,Y=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(V){return V.__proto__}:null);function W(V,ie){if(V===1/0||V===-1/0||V!==V||V&&V>-1e3&&V<1e3||E.call(/e/,ie))return ie;var Ae=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof V=="number"){var Ie=V<0?-O(-V):O(V);if(Ie!==V){var Pe=String(Ie),Me=m.call(ie,Pe.length+1);return _.call(Pe,Ae,"$&_")+"."+_.call(_.call(Me,/([0-9]{3})/g,"$&_"),/_$/,"")}}return _.call(ie,Ae,"$&_")}var re=bl,$=re.custom,Z=G($)?$:null;Nr=function V(ie,Ae,Ie,Pe){var Me=Ae||{};if(se(Me,"quoteStyle")&&Me.quoteStyle!=="single"&&Me.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(se(Me,"maxStringLength")&&(typeof Me.maxStringLength=="number"?Me.maxStringLength<0&&Me.maxStringLength!==1/0:Me.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var et=se(Me,"customInspect")?Me.customInspect:!0;if(typeof et!="boolean"&&et!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(se(Me,"indent")&&Me.indent!==null&&Me.indent!==" "&&!(parseInt(Me.indent,10)===Me.indent&&Me.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(se(Me,"numericSeparator")&&typeof Me.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var tt=Me.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 ae(ie,Me);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var qe=String(ie);return tt?W(ie,qe):qe}if(typeof ie=="bigint"){var rt=String(ie)+"n";return tt?W(ie,rt):rt}var Ft=typeof Me.depth>"u"?5:Me.depth;if(typeof Ie>"u"&&(Ie=0),Ie>=Ft&&Ft>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var nt=X(Me,Ie);if(typeof Pe>"u")Pe=[];else if(ee(Pe,ie)>=0)return"[Circular]";function Qe(it,yt,Ct){if(yt&&(Pe=C.call(Pe),Pe.push(yt)),Ct){var ot={depth:Me.depth};return se(Me,"quoteStyle")&&(ot.quoteStyle=Me.quoteStyle),V(it,ot,Ie+1,Pe)}return V(it,Me,Ie+1,Pe)}if(typeof ie=="function"&&!we(ie)){var hr=q(ie),$t=ke(ie,Qe);return"[Function"+(hr?": "+hr:" (anonymous)")+"]"+($t.length>0?" { "+A.call($t,", ")+" }":"")}if(G(ie)){var Xt=D?_.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):B.call(ie);return typeof ie=="object"&&!D?h(Xt):Xt}if(ve(ie)){for(var P="<"+v.call(String(ie.nodeName)),L=ie.attributes||[],_e=0;_e<L.length;_e++)P+=" "+L[_e].name+"="+M(Q(L[_e].value),"double",Me);return P+=">",ie.childNodes&&ie.childNodes.length&&(P+="..."),P+="</"+v.call(String(ie.nodeName))+">",P}if(be(ie)){if(ie.length===0)return"[]";var xe=ke(ie,Qe);return nt&&!F(xe)?"["+de(xe,nt)+"]":"[ "+A.call(xe,", ")+" ]"}if(K(ie)){var Se=ke(ie,Qe);return!("cause"in Error.prototype)&&"cause"in ie&&!oe.call(ie,"cause")?"{ ["+String(ie)+"] "+A.call(S.call("[cause]: "+Qe(ie.cause),Se),", ")+" }":Se.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+A.call(Se,", ")+" }"}if(typeof ie=="object"&&et){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Ft-Ie});if(et!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var De=[];return r&&r.call(ie,function(it,yt){De.push(Qe(yt,ie,!0)+" => "+Qe(it,ie))}),I("Map",t.call(ie),De,nt)}if(H(ie)){var Ve=[];return a&&a.call(ie,function(it){Ve.push(Qe(it,ie))}),I("Set",i.call(ie),Ve,nt)}if(fe(ie))return k("WeakMap");if(me(ie))return k("WeakSet");if(ye(ie))return k("WeakRef");if(ne(ie))return h(Qe(Number(ie)));if(J(ie))return h(Qe(j.call(ie)));if(z(ie))return h(f.call(ie));if(N(ie))return h(Qe(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof jr<"u"&&ie===jr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var Ze=ke(ie,Qe),Zt=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,er=ie instanceof Object?"":"null prototype",tr=!Zt&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):er?"Object":"",fr=Zt||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Tt=fr+(tr||er?"["+A.call(S.call([],tr||[],er||[]),": ")+"] ":"");return Ze.length===0?Tt+"{}":nt?Tt+"{"+de(Ze,nt)+"}":Tt+"{ "+A.call(Ze,", ")+" }"}return String(ie)};function M(V,ie,Ae){var Ie=(Ae.quoteStyle||ie)==="double"?'"':"'";return Ie+V+Ie}function Q(V){return _.call(String(V),/"/g,""")}function be(V){return R(V)==="[object Array]"&&(!U||!(typeof V=="object"&&U in V))}function te(V){return R(V)==="[object Date]"&&(!U||!(typeof V=="object"&&U in V))}function we(V){return R(V)==="[object RegExp]"&&(!U||!(typeof V=="object"&&U in V))}function K(V){return R(V)==="[object Error]"&&(!U||!(typeof V=="object"&&U in V))}function N(V){return R(V)==="[object String]"&&(!U||!(typeof V=="object"&&U in V))}function ne(V){return R(V)==="[object Number]"&&(!U||!(typeof V=="object"&&U in V))}function z(V){return R(V)==="[object Boolean]"&&(!U||!(typeof V=="object"&&U in V))}function G(V){if(D)return V&&typeof V=="object"&&V instanceof Symbol;if(typeof V=="symbol")return!0;if(!V||typeof V!="object"||!B)return!1;try{return B.call(V),!0}catch{}return!1}function J(V){if(!V||typeof V!="object"||!j)return!1;try{return j.call(V),!0}catch{}return!1}var ge=Object.prototype.hasOwnProperty||function(V){return V in(this||jr)};function se(V,ie){return ge.call(V,ie)}function R(V){return g.call(V)}function q(V){if(V.name)return V.name;var ie=w.call(y.call(V),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(V,ie){if(V.indexOf)return V.indexOf(ie);for(var Ae=0,Ie=V.length;Ae<Ie;Ae++)if(V[Ae]===ie)return Ae;return-1}function he(V){if(!t||!V||typeof V!="object")return!1;try{t.call(V);try{i.call(V)}catch{return!0}return V instanceof Map}catch{}return!1}function fe(V){if(!c||!V||typeof V!="object")return!1;try{c.call(V,c);try{d.call(V,d)}catch{return!0}return V instanceof WeakMap}catch{}return!1}function ye(V){if(!b||!V||typeof V!="object")return!1;try{return b.call(V),!0}catch{}return!1}function H(V){if(!i||!V||typeof V!="object")return!1;try{i.call(V);try{t.call(V)}catch{return!0}return V instanceof Set}catch{}return!1}function me(V){if(!d||!V||typeof V!="object")return!1;try{d.call(V,d);try{c.call(V,c)}catch{return!0}return V instanceof WeakSet}catch{}return!1}function ve(V){return!V||typeof V!="object"?!1:typeof HTMLElement<"u"&&V instanceof HTMLElement?!0:typeof V.nodeName=="string"&&typeof V.getAttribute=="function"}function ae(V,ie){if(V.length>ie.maxStringLength){var Ae=V.length-ie.maxStringLength,Ie="... "+Ae+" more character"+(Ae>1?"s":"");return ae(m.call(V,0,ie.maxStringLength),ie)+Ie}var Pe=_.call(_.call(V,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Oe);return M(Pe,"single",ie)}function Oe(V){var ie=V.charCodeAt(0),Ae={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ae?"\\"+Ae:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function h(V){return"Object("+V+")"}function k(V){return V+" { ? }"}function I(V,ie,Ae,Ie){var Pe=Ie?de(Ae,Ie):A.call(Ae,", ");return V+" ("+ie+") {"+Pe+"}"}function F(V){for(var ie=0;ie<V.length;ie++)if(ee(V[ie],`
|
|
4
|
+
`)>=0)return!1;return!0}function X(V,ie){var Ae;if(V.indent===" ")Ae=" ";else if(typeof V.indent=="number"&&V.indent>0)Ae=A.call(Array(V.indent+1)," ");else return null;return{base:Ae,prev:A.call(Array(ie+1),Ae)}}function de(V,ie){if(V.length===0)return"";var Ae=`
|
|
5
|
+
`+ie.prev+ie.base;return Ae+A.call(V,","+Ae)+`
|
|
6
|
+
`+ie.prev}function ke(V,ie){var Ae=be(V),Ie=[];if(Ae){Ie.length=V.length;for(var Pe=0;Pe<V.length;Pe++)Ie[Pe]=se(V,Pe)?ie(V[Pe],V):""}var Me=typeof T=="function"?T(V):[],et;if(D){et={};for(var tt=0;tt<Me.length;tt++)et["$"+Me[tt]]=Me[tt]}for(var qe in V)se(V,qe)&&(Ae&&String(Number(qe))===qe&&qe<V.length||D&&et["$"+qe]instanceof Symbol||(E.call(/[^\w$]/,qe)?Ie.push(ie(qe,V)+": "+ie(V[qe],V)):Ie.push(qe+": "+ie(V[qe],V))));if(typeof T=="function")for(var rt=0;rt<Me.length;rt++)oe.call(V,Me[rt])&&Ie.push("["+ie(Me[rt])+"]: "+ie(V[Me[rt]],V));return Ie}return Nr}function jd(){if(io)return Ur;io=!0;var o=Qt(),e=_d(),t=Nd(),r=dr(),s=o("%WeakMap%",!0),n=o("%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),p=function(y,w){for(var m=y,_;(_=m.next)!==null;m=_)if(_.key===w)return m.next=_.next,_.next=y.next,y.next=_,_},b=function(y,w){var m=p(y,w);return m&&m.value},f=function(y,w,m){var _=p(y,w);_?_.value=m:y.next={key:w,next:y.next,value:m}},g=function(y,w){return!!p(y,w)};return Ur=function(){var y,w,m,_={assert:function(x){if(!_.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(s&&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 b(m,x)},has:function(x){if(s&&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 g(m,x);return!1},set:function(x,v){s&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new s),a(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),f(m,x,v))}};return _},Ur}function Ao(){if(oo)return Br;oo=!0;var o=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Br={default:t.RFC3986,formatters:{RFC1738:function(r){return o.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Br}function pl(){if(so)return Dr;so=!0;var o=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})(),s=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var _=[],x=0;x<m.length;++x)typeof m[x]<"u"&&_.push(m[x]);w.obj[w.prop]=_}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},_=0;_<y.length;++_)typeof y[_]<"u"&&(m[_]=y[_]);return m},i=function y(w,m,_){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(_&&(_.plainObjects||_.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,_)),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,_):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,_):v[E]=S,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,_){return m[_]=w[_],m},y)},l=function(y,w,m){var _=y.replace(/\+/g," ");if(m==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},c=1024,u=function(y,w,m,_,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 A=v.length>=c?v.slice(S,S+c):v,C=[],O=0;O<A.length;++O){var j=A.charCodeAt(O);if(j===45||j===46||j===95||j===126||j>=48&&j<=57||j>=65&&j<=90||j>=97&&j<=122||x===o.RFC1738&&(j===40||j===41)){C[C.length]=A.charAt(O);continue}if(j<128){C[C.length]=r[j];continue}if(j<2048){C[C.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){C[C.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}O+=1,j=65536+((j&1023)<<10|A.charCodeAt(O)&1023),C[C.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}E+=C.join("")}return E},d=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],_=0;_<w.length;++_)for(var x=w[_],v=x.obj[x.prop],E=Object.keys(v),S=0;S<E.length;++S){var A=E[S],C=v[A];typeof C=="object"&&C!==null&&m.indexOf(C)===-1&&(w.push({obj:v,prop:A}),m.push(C))}return s(w),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},b=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},f=function(y,w){return[].concat(y,w)},g=function(y,w){if(t(y)){for(var m=[],_=0;_<y.length;_+=1)m.push(w(y[_]));return m}return w(y)};return Dr={arrayToObject:n,assign:a,combine:f,compact:d,decode:l,encode:u,isBuffer:b,isRegExp:p,maybeMap:g,merge:i},Dr}function Ud(){if(ao)return Fr;ao=!0;var o=jd(),e=pl(),t=Ao(),r=Object.prototype.hasOwnProperty,s={brackets:function(g){return g+"[]"},comma:"comma",indices:function(g,y){return g+"["+y+"]"},repeat:function(g){return g}},n=Array.isArray,i=Array.prototype.push,a=function(g,y){i.apply(g,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(g){return l.call(g)},skipNulls:!1,strictNullHandling:!1},d=function(g){return typeof g=="string"||typeof g=="number"||typeof g=="boolean"||typeof g=="symbol"||typeof g=="bigint"},p={},b=function g(y,w,m,_,x,v,E,S,A,C,O,j,T,B,D,U,oe,Y){for(var W=y,re=Y,$=0,Z=!1;(re=re.get(p))!==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(p)>"u"&&($=0)}if(typeof C=="function"?W=C(w,W):W instanceof Date?W=T(W):m==="comma"&&n(W)&&(W=e.maybeMap(W,function(R){return R instanceof Date?T(R):R})),W===null){if(v)return A&&!U?A(w,u.encoder,oe,"key",B):w;W=""}if(d(W)||e.isBuffer(W)){if(A){var Q=U?w:A(w,u.encoder,oe,"key",B);return[D(Q)+"="+D(A(W,u.encoder,oe,"value",B))]}return[D(w)+"="+D(String(W))]}var be=[];if(typeof W>"u")return be;var te;if(m==="comma"&&n(W))U&&A&&(W=e.maybeMap(W,A)),te=[{value:W.length>0?W.join(",")||null:void 0}];else if(n(C))te=C;else{var we=Object.keys(W);te=O?we.sort(O):we}var K=S?w.replace(/\./g,"%2E"):w,N=_&&n(W)&&W.length===1?K+"[]":K;if(x&&n(W)&&W.length===0)return N+"[]";for(var ne=0;ne<te.length;++ne){var z=te[ne],G=typeof z=="object"&&typeof z.value<"u"?z.value:W[z];if(!(E&&G===null)){var J=j&&S?z.replace(/\./g,"%2E"):z,ge=n(W)?typeof m=="function"?m(N,J):N:N+(j?"."+J:"["+J+"]");Y.set(y,$);var se=o();se.set(p,Y),a(be,g(G,ge,m,_,x,v,E,S,m==="comma"&&U&&n(W)?null:A,C,O,j,T,B,D,U,oe,se))}}return be},f=function(g){if(!g)return u;if(typeof g.allowEmptyArrays<"u"&&typeof g.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof g.encodeDotInKeys<"u"&&typeof g.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(g.encoder!==null&&typeof g.encoder<"u"&&typeof g.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=g.charset||u.charset;if(typeof g.charset<"u"&&g.charset!=="utf-8"&&g.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 g.format<"u"){if(!r.call(t.formatters,g.format))throw new TypeError("Unknown format option provided.");w=g.format}var m=t.formatters[w],_=u.filter;(typeof g.filter=="function"||n(g.filter))&&(_=g.filter);var x;if(g.arrayFormat in s?x=g.arrayFormat:"indices"in g?x=g.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in g&&typeof g.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof g.allowDots>"u"?g.encodeDotInKeys===!0?!0:u.allowDots:!!g.allowDots;return{addQueryPrefix:typeof g.addQueryPrefix=="boolean"?g.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof g.allowEmptyArrays=="boolean"?!!g.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof g.charsetSentinel=="boolean"?g.charsetSentinel:u.charsetSentinel,commaRoundTrip:g.commaRoundTrip,delimiter:typeof g.delimiter>"u"?u.delimiter:g.delimiter,encode:typeof g.encode=="boolean"?g.encode:u.encode,encodeDotInKeys:typeof g.encodeDotInKeys=="boolean"?g.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof g.encoder=="function"?g.encoder:u.encoder,encodeValuesOnly:typeof g.encodeValuesOnly=="boolean"?g.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:w,formatter:m,serializeDate:typeof g.serializeDate=="function"?g.serializeDate:u.serializeDate,skipNulls:typeof g.skipNulls=="boolean"?g.skipNulls:u.skipNulls,sort:typeof g.sort=="function"?g.sort:null,strictNullHandling:typeof g.strictNullHandling=="boolean"?g.strictNullHandling:u.strictNullHandling}};return Fr=function(g,y){var w=g,m=f(y),_,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,_=x);var v=[];if(typeof w!="object"||w===null)return"";var E=s[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;_||(_=Object.keys(w)),m.sort&&_.sort(m.sort);for(var A=o(),C=0;C<_.length;++C){var O=_[C];m.skipNulls&&w[O]===null||a(v,b(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,A))}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:""},Fr}function Bd(){if(lo)return $r;lo=!0;var o=pl(),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:o.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},s=function(p){return p.replace(/&#(\d+);/g,function(b,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,b){return p&&typeof p=="string"&&b.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,b){var f={__proto__:null},g=b.ignoreQueryPrefix?p.replace(/^\?/,""):p;g=g.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=b.parameterLimit===1/0?void 0:b.parameterLimit,w=g.split(b.delimiter,y),m=-1,_,x=b.charset;if(b.charsetSentinel)for(_=0;_<w.length;++_)w[_].indexOf("utf8=")===0&&(w[_]===a?x="utf-8":w[_]===i&&(x="iso-8859-1"),m=_,_=w.length);for(_=0;_<w.length;++_)if(_!==m){var v=w[_],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,A,C;S===-1?(A=b.decoder(v,r.decoder,x,"key"),C=b.strictNullHandling?null:""):(A=b.decoder(v.slice(0,S),r.decoder,x,"key"),C=o.maybeMap(n(v.slice(S+1),b),function(j){return b.decoder(j,r.decoder,x,"value")})),C&&b.interpretNumericEntities&&x==="iso-8859-1"&&(C=s(C)),v.indexOf("[]=")>-1&&(C=t(C)?[C]:C);var O=e.call(f,A);O&&b.duplicates==="combine"?f[A]=o.combine(f[A],C):(!O||b.duplicates==="last")&&(f[A]=C)}return f},c=function(p,b,f,g){for(var y=g?b:n(b,f),w=p.length-1;w>=0;--w){var m,_=p[w];if(_==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(y===""||f.strictNullHandling&&y===null)?[]:[].concat(y);else{m=f.plainObjects?Object.create(null):{};var x=_.charAt(0)==="["&&_.charAt(_.length-1)==="]"?_.slice(1,-1):_,v=f.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!f.parseArrays&&v===""?m={0:y}:!isNaN(E)&&_!==v&&String(E)===v&&E>=0&&f.parseArrays&&E<=f.arrayLimit?(m=[],m[E]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,b,f,g){if(p){var y=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,_=f.depth>0&&w.exec(y),x=_?y.slice(0,_.index):y,v=[];if(x){if(!f.plainObjects&&e.call(Object.prototype,x)&&!f.allowPrototypes)return;v.push(x)}for(var E=0;f.depth>0&&(_=m.exec(y))!==null&&E<f.depth;){if(E+=1,!f.plainObjects&&e.call(Object.prototype,_[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(_[1])}if(_){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+y.slice(_.index)+"]")}return c(v,b,f,g)}},d=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var b=typeof p.charset>"u"?r.charset:p.charset,f=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var g=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:g,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:b,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||o.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:f,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:r.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:r.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:r.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:r.strictNullHandling}};return $r=function(p,b){var f=d(b);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?l(p,f):p,y=f.plainObjects?Object.create(null):{},w=Object.keys(g),m=0;m<w.length;++m){var _=w[m],x=u(_,g[_],f,typeof p=="string");y=o.merge(y,x,f)}return f.allowSparse===!0?y:o.compact(y)},$r}function Dd(){if(co)return qr;co=!0;var o=Ud(),e=Bd(),t=Ao();return qr={formats:t,parse:e,stringify:o},qr}function Fd(){if(uo)return St;uo=!0;var o=xt;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]*$/,s=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
|
+
`," "],i=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(i),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=Dd();function w(v,E,S){if(v&&typeof v=="object"&&v instanceof e)return v;var A=new e;return A.parse(v,E,S),A}e.prototype.parse=function(v,E,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var A=v.indexOf("?"),C=A!==-1&&A<v.indexOf("#")?"?":"#",O=v.split(C),j=/\\/g;O[0]=O[0].replace(j,"/"),v=O.join(C);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var B=s.exec(T);if(B)return this.path=T,this.href=T,this.pathname=B[1],B[2]?(this.search=B[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 oe=T.substr(0,2)==="//";oe&&!(D&&f[D])&&(T=T.substr(2),this.slashes=!0)}if(!f[D]&&(oe||D&&!g[D])){for(var Y=-1,W=0;W<c.length;W++){var re=T.indexOf(c[W]);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 W=0;W<l.length;W++){var re=T.indexOf(l[W]);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(/\./),W=0,be=Q.length;W<be;W++){var te=Q[W];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,W),z=Q.slice(W+1),G=te.match(p);G&&(ne.push(G[1]),z.unshift(G[2])),z.length&&(T="/"+z.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=o.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(!b[U])for(var W=0,be=a.length;W<be;W++){var se=a[W];if(T.indexOf(se)!==-1){var R=encodeURIComponent(se);R===se&&(R=escape(se)),T=T.split(se).join(R)}}var q=T.indexOf("#");q!==-1&&(this.hash=T.substr(q),T=T.slice(0,q));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),g[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||"",A=this.hash||"",C=!1,O="";this.host?C=v+this.host:this.hostname&&(C=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(C+=":"+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||g[E])&&C!==!1?(C="//"+(C||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):C||(C=""),A&&A.charAt(0)!=="#"&&(A="#"+A),j&&j.charAt(0)!=="?"&&(j="?"+j),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),j=j.replace("#","%23"),E+C+S+j+A};function _(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,A=Object.keys(this),C=0;C<A.length;C++){var O=A[C];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 B=j[T];B!=="protocol"&&(S[B]=v[B])}return g[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(!g[v.protocol]){for(var D=Object.keys(v),U=0;U<D.length;U++){var oe=D[U];S[oe]=v[oe]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!f[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||"",W=S.search||"";S.path=Y+W}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&&!g[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,z=Q.length;z>=0;z--)K=Q[z],K==="."?Q.splice(z,1):K===".."?(Q.splice(z,1),ne++):ne&&(Q.splice(z,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=_,St.resolveObject=x,St.format=m,St.Url=e,St}function ml(o){if(typeof o=="string")o=new URL(o);else if(!(o instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(o.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return zr?$d(o):qd(o)}function $d(o){let e=o.hostname,t=o.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let s=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&s===102||t[r+1]==="5"&&s===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(Tl,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,s=t[2];if(r<Al||r>Il||s!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function qd(o){if(o.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=o.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 gl(o){let e=ro.resolve(o),t=o.charCodeAt(o.length-1);(t===El||zr&&t===Sl)&&e[e.length-1]!==ro.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Cl,"%25")),!zr&&e.includes("\\")&&(e=e.replace(Pl,"%5C")),e.includes(`
|
|
8
|
+
`)&&(e=e.replace(Ol,"%0A")),e.includes("\r")&&(e=e.replace(Ml,"%0D")),e.includes(" ")&&(e=e.replace(Rl,"%09")),r.pathname=e,r}var bl,Nr,no,jr,Ur,io,Br,oo,Dr,so,Fr,ao,$r,lo,qr,co,St,uo,ze,$s,yl,vl,wl,_l,kl,xl,Sl,El,Al,Il,zr,Tl,Cl,Pl,Ol,Ml,Rl,Hd=Je(()=>{le(),ue(),ce(),sd(),kd(),Ld(),hl(),bl=Object.freeze(Object.create(null)),Nr={},no=!1,jr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Ur={},io=!1,Br={},oo=!1,Dr={},so=!1,Fr={},ao=!1,$r={},lo=!1,qr={},co=!1,St={},uo=!1,ze=Fd(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,$s=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=gl,ze.fileURLToPath=ml,yl=ze.Url,vl=ze.format,wl=ze.resolve,_l=ze.resolveObject,kl=ze.parse,xl=ze.URL,Sl=92,El=47,Al=97,Il=122,zr=$s==="win32",Tl=/\//g,Cl=/%/g,Pl=/\\/g,Ol=/\n/g,Ml=/\r/g,Rl=/\t/g}),Wd=pe((o,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")}}),Io=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.BufferedDuplex=void 0,o.writev=r;var e=Bt(),t=($e(),Le(Fe));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 s=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)}}};o.BufferedDuplex=s}),mr=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(o,"__esModule",{value:!0}),o.streamBuilder=o.browserStreamBuilder=void 0;var t=($e(),Le(Fe)),r=e(Wd()),s=e(pt()),n=Bt(),i=e(Xr()),a=Io(),l=(0,s.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let _=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(_=w.transformWsUrl(_,w,m)),_}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(_=>{Object.prototype.hasOwnProperty.call(w,_)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,_)&&(m.wsOptions[_]=w[_])}),m}function p(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 _=new URL(document.URL);m.hostname=_.hostname,m.port||(m.port=Number(_.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function b(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function f(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var g=(w,m)=>{l("streamBuilder");let _=d(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=b(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};o.streamBuilder=g;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=f(w,m),A=O(m,U,oe);m.objectMode||(A._writev=a.writev.bind(A)),A.on("close",()=>{S.close()});let C=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=A,_.socket=S):(_=new a.BufferedDuplex(m,A,S),C?S.addEventListener("open",j):S.onopen=j),C?(S.addEventListener("close",T),S.addEventListener("error",B),S.addEventListener("message",D)):(S.onclose=T,S.onerror=B,S.onmessage=D);function O(Y,W,re){let $=new n.Transform({objectMode:Y.objectMode});return $._write=W,$._flush=re,$}function j(){l("WebSocket onOpen"),_ instanceof a.BufferedDuplex&&_.socketReady()}function T(Y){l("WebSocket onClose",Y),_.end(),_.destroy()}function B(Y){l("WebSocket onError",Y);let W=new Error("WebSocket error");W.event=Y,_.destroy(W)}async function D(Y){if(!A||!A.readable||!A.writable)return;let{data:W}=Y;W instanceof ArrayBuffer?W=t.Buffer.from(W):W instanceof Blob?W=t.Buffer.from(await new Response(W).arrayBuffer()):W=t.Buffer.from(W,"utf8"),A.push(W)}function U(Y,W,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,W,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch($){return re($)}re()}function oe(Y){S.close(),Y()}return _};o.browserStreamBuilder=y}),To={};Gt(To,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>Ll,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 Ll,Nl=Je(()=>{le(),ue(),ce(),Ll={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),jl=pe((o,e)=>{le(),ue(),ce(),e.exports={}}),qs=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(o,"__esModule",{value:!0});var t=e((Nl(),Le(To))),r=e(pt()),s=e(jl()),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,s.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})};o.default=i}),Ul={};Gt(Ul,{default:()=>Bl});var Bl,zd=Je(()=>{le(),ue(),ce(),Bl={}}),Hs=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(o,"__esModule",{value:!0});var t=(zd(),Le(Ul)),r=e((Nl(),Le(To))),s=e(pt()),n=e(jl()),i=(0,s.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:p,...b}=c;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:c.socksTimeout});return(0,t.connect)({...b,socket:f})}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",p)});function p(b){u.rejectUnauthorized&&c.emit("error",b),d.end()}return d.on("error",p),d};o.default=l}),Ws=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=($e(),Le(Fe)),t=Bt(),r=Io(),s,n,i;function a(){let p=new t.Transform;return p._write=(b,f,g)=>{s.send({data:b.buffer,success(){g()},fail(y){g(new Error(y))}})},p._flush=b=>{s.close({success(){b()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,b){let f=p.protocol==="wxs"?"wss":"ws",g=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,b)),g}function u(){s.onOpen(()=>{i.socketReady()}),s.onMessage(p=>{let{data:b}=p;b instanceof ArrayBuffer?b=e.Buffer.from(b):b=e.Buffer.from(b,"utf8"),n.push(b)}),s.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),s.onError(p=>{let b=new Error(p.errMsg);i.destroy(b)})}var d=(p,b)=>{if(b.hostname=b.hostname||b.host,!b.hostname)throw new Error("Could not determine host. Specify host manually.");let f=b.protocolId==="MQIsdp"&&b.protocolVersion===3?"mqttv3.1":"mqtt";l(b);let g=c(b,p);s=wx.connectSocket({url:g,protocols:[f]}),n=a(),i=new r.BufferedDuplex(b,n,s),i._destroy=(w,m)=>{s.close({success(){m&&m(w)}})};let y=i.destroy;return i.destroy=(w,m)=>(i.destroy=y,setTimeout(()=>{s.close({fail(){i._destroy(w,m)}})},0),i),u(),i};o.default=d}),zs=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=($e(),Le(Fe)),t=Bt(),r=Io(),s,n,i,a=!1;function l(){let b=new t.Transform;return b._write=(f,g,y)=>{s.sendSocketMessage({data:f.buffer,success(){y()},fail(){y(new Error)}})},b._flush=f=>{s.closeSocket({success(){f()}})},b}function c(b){b.hostname||(b.hostname="localhost"),b.path||(b.path="/"),b.wsOptions||(b.wsOptions={})}function u(b,f){let g=b.protocol==="alis"?"wss":"ws",y=`${g}://${b.hostname}${b.path}`;return b.port&&b.port!==80&&b.port!==443&&(y=`${g}://${b.hostname}:${b.port}${b.path}`),typeof b.transformWsUrl=="function"&&(y=b.transformWsUrl(y,b,f)),y}function d(){a||(a=!0,s.onSocketOpen(()=>{i.socketReady()}),s.onSocketMessage(b=>{if(typeof b.data=="string"){let f=e.Buffer.from(b.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(b.data)}}),s.onSocketClose(()=>{i.end(),i.destroy()}),s.onSocketError(b=>{i.destroy(b)}))}var p=(b,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let g=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let y=u(f,b);return s=f.my,s.connectSocket({url:y,protocols:g}),n=l(),i=new r.BufferedDuplex(f,n,s),d(),i};o.default=p}),Vd=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(o,"__esModule",{value:!0}),o.connectAsync=u;var t=e(pt()),r=e((Hd(),Le(fl))),s=e(xi()),n=e(Xr());typeof Ne?.nextTick!="function"&&(Ne.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),a=null;function l(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,b,f]=p;d.username=b,d.password=f}else d.username=d.auth}function c(d,p){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let g=r.default.parse(d,!0),y={};if(g.port!=null&&(y.port=Number(g.port)),y.host=g.hostname,y.query=g.query,y.auth=g.auth,y.protocol=g.protocol,y.path=g.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Ne<"u"&&(p.socksProxy=Ne.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=mr().streamBuilder,a.wss=mr().streamBuilder,a.mqtt=qs().default,a.tcp=qs().default,a.ssl=Hs().default,a.tls=a.ssl,a.mqtts=Hs().default):(a.ws=mr().browserStreamBuilder,a.wss=mr().browserStreamBuilder,a.wx=Ws().default,a.wxs=Ws().default,a.ali=zs().default,a.alis=zs().default)),!a[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>g&&w%2===0?!1:typeof a[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function b(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),a[p.protocol](g,p)}let f=new s.default(b,p);return f.on("error",()=>{}),f}function u(d,p,b=!0){return new Promise((f,g)=>{let y=c(d,p),w={connect:_=>{m(),f(y)},end:()=>{m(),f(y)},error:_=>{m(),y.end(),g(_)}};b===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}o.default=c}),Vs=pe(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(b,f,g,y){y===void 0&&(y=g);var w=Object.getOwnPropertyDescriptor(f,g);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(b,y,w)}:function(b,f,g,y){y===void 0&&(y=g),b[y]=f[g]}),t=o&&o.__setModuleDefault||(Object.create?function(b,f){Object.defineProperty(b,"default",{enumerable:!0,value:f})}:function(b,f){b.default=f}),r=o&&o.__importStar||(function(){var b=function(f){return b=Object.getOwnPropertyNames||function(g){var y=[];for(var w in g)Object.prototype.hasOwnProperty.call(g,w)&&(y[y.length]=w);return y},b(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var y=b(f),w=0;w<y.length;w++)y[w]!=="default"&&e(g,f,y[w]);return t(g,f),g}})(),s=o&&o.__exportStar||function(b,f){for(var g in b)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,b,g)},n=o&&o.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(o,"__esModule",{value:!0}),o.ReasonCodes=o.KeepaliveManager=o.UniqueMessageIdProvider=o.DefaultMessageIdProvider=o.Store=o.MqttClient=o.connectAsync=o.connect=o.Client=void 0;var i=n(xi());o.MqttClient=i.default;var a=n(el());o.DefaultMessageIdProvider=a.default;var l=n(id());o.UniqueMessageIdProvider=l.default;var c=n(Ua());o.Store=c.default;var u=r(Vd());o.connect=u.default,Object.defineProperty(o,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(al());o.KeepaliveManager=d.default,o.Client=i.default,s(xi(),o),s(Jt(),o),s(ja(),o);var p=Jr();Object.defineProperty(o,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Kd=pe(o=>{le(),ue(),ce();var e=o&&o.__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=o&&o.__setModuleDefault||(Object.create?function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}:function(i,a){i.default=a}),r=o&&o.__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}})(),s=o&&o.__exportStar||function(i,a){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,i,l)};Object.defineProperty(o,"__esModule",{value:!0});var n=r(Vs());o.default=n,s(Vs(),o)});const Gd=Kd();const Yd={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}/#"},Jd=300,Qd={templateId:"7",type:"link",isDeepLink:!0},Xd={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Dl{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={...Yd,...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,s={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&&(s.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,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:p?.message}),l(()=>i(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Gd.connect(this.config.mqttEndpoint,s),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,p)=>{this.dispatchInbound(d,p)}),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[s,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[s]=`${n.slice(0,200)}…(${n.length})`:r[s]=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 s=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,s)}publishFileMessage(e,t){if(!this.client)return;const r={...Qd,...this.config.fileTemplate??{},...Zd(t)},s={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(s),type:"html",attributes:n,metadata:s.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Jd){if(!this.client)return;const s=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(s,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 s=[...this.subscribedTopics];this.subscribedTopics.clear(),s.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 s=null;try{s=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!s)return;this.debugLog("RECV",{topic:e,sender:s.sender,type:s.type,contentType:s.metadata?.contentType,templateId:s.metadata?.templateId,messageId:s.message_id,text:typeof s.text=="string"?s.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof s.status=="number"?s.status:Number(s.status??0),p={conversationId:c,messageId:u,status:d,raw:s};this.statusUpdateHandlers.forEach(b=>b(p)),this.messageHandlers.forEach(b=>b(s,{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 s.message_id=="string"?s.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(s,l))}buildOutgoingEnvelope(e,t){const r={...Xd,...this.config.messageDefaults??{}},s=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:s,senderFullname:s,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,(s,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(s,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(o){const e={};for(const[t,r]of Object.entries(o))r!==void 0&&(e[t]=r);return e}function Fl(o,e){return(o.sender??"").toString()===e}function $l(o,e){const t=(o.sender??"").toString(),r=e.systemSenders??["metadata","system"],s=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(s)?"assistant":r.includes(t)?"system":"agent":"system"}function Co(o){const e={raw:o},t=o.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 o.text=="string"&&o.text.trim().startsWith("{"))try{const s=o.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(s);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=o.attributes;if(r&&typeof r=="object"){const s=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&s&&typeof s.contentType=="string"&&(e.contentType=s.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&s&&typeof s.templateId=="string"&&(e.templateId=s.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&s&&s.payload!==void 0&&(e.payload=s.payload),e.payload===void 0&&s&&s.template!==void 0&&(e.payload=s.template)}return e}function ql(o){const e=Co(o);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 s=r[0],n=s.action,i=n&&typeof n.url=="string"?n.url:void 0,a=typeof s.description=="string"?s.description:void 0,l=o.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 Ks(o,e,t){const r=$l(o,t),s=Co(o),n=ql(o);let i="";s.innerMessage?i=s.innerMessage:typeof o.text=="string"&&(o.text.trim().startsWith("{")?s.contentType!=="300"&&(i=o.text):i=o.text);const a=typeof o.message_id=="string"?o.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof o.timestamp=="number"?new Date(o.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof o.status=="number"?eh(o.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:o.sender,sender_fullname:o.sender_fullname??o.senderFullname,app_id:o.app_id,attributes:o.attributes}};return s.contentType&&(d.template={contentType:s.contentType,templateId:s.templateId,payload:s.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:s}}function eh(o){return o<0?"error":o>=250?"read":o>=150?"delivered":"sent"}class Hl extends po{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 ia(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new oa,this.conversationManager=new aa(e.conversationId),this.usesAikaara()&&(this.connection=new na(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 Dl({...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 s=r?"connected":"disconnected";this.emit("connection:state",s),this.config.onConnectionStateChange?.(s)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,s)=>this.handleTiledeskMessage(r,s))),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),s=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;s&&(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 s=r.map(l=>Ks(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=s.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 s){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 s=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",s),this.config.onMessage?.(s);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 s=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:s.fileName,fileUrl:s.url,cloudFileId:s.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 s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(s,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 s=t.conversationId??r;if(!s)return;const n=this.config.tiledeskIdentity?.userId??"",{message:i,template:a}=Ks(e,s,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(Fl(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:s,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||"",s=e.content||"";s?this.messageStore.updateStreaming(s):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,s=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),s&&(this.emit("stream:end",{messageId:s.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",s),this.config.onMessage?.(s));break}case"message_queued":{const r=this.messageStore.messages.findLast(s=>s.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}}}const Gs={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 th(o){const e=o.lastIndexOf(".");return e<0||e===o.length-1?"":o.slice(e+1).toLowerCase()}function rh(o,e,t){const r=th(o.name||"");if(r&&e&&e[r])return e[r];const s=o.type;return s&&s.trim().length>0?s:r&&Gs[r]?Gs[r]:t}function on(o,e){return o.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function nh(o,e){const t=e.split(".");let r=o;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return"";return typeof r=="string"?r:""}function Wl(o){const e=o.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const s=t.name||`upload-${Date.now()}`,n=rh(t,o.contentTypeMap,o.contentTypeFallback??"application/octet-stream"),i={fileName:s,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=o.authHeader?await o.authHeader():void 0,l={accept:"application/json",...o.extraHeaders??{},...a?{authorization:a}:{}};let c=o.signEndpoint.includes("{")?o.signEndpoint:`${o.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=on(c,i),d=await fetch(u,{method:o.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const p=await d.json().catch(()=>({})),b=nh(p,e);if(!b)throw new Error(`Sign response missing path "${e}"`);const f=o.s3HostRewrite?b.replace(/^https:\/\/[^/]+/i,o.s3HostRewrite):b,g=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const w=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${w.slice(0,200)}`)}if(o.registerEndpoint){const w=JSON.parse(on(JSON.stringify(o.registerBody??{}),i)),m=await fetch(o.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const _=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${_.slice(0,200)}`)}}return{url:o.viewerTemplate?on(o.viewerTemplate,i):b.split("?")[0],fileName:s,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Po(o){return{async upload(e,t){const r=new FormData,s=o.fieldName??"file";r.append(s,e,e.name);const n=typeof o.extraFields=="function"?o.extraFields(t):o.extraFields;if(n)for(const[p,b]of Object.entries(n))r.append(p,b);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof o.headers=="function"?await o.headers():o.headers??{},a=await fetch(o.endpoint,{method:o.method??"POST",body:r,headers:i,credentials:o.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(o.parseResponse)return o.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 ih="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function zl(o){const e=o.apiBase.replace(/\/$/,""),t=o.pageSize??200,r=o.pathTemplate??ih;return{async fetchMessages(s,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(s)).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",...o.extraHeaders??{}};if(o.getToken){const p=await o.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(o.parseResponse&&u)return o.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 oh="^[A-Z]{4}[0-9]{5}[A-Z]$",sh="^[A-Z]{4}0[A-Z0-9]{6}$",ah="^[0-9]{6}$",lh={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"},ch={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:oh,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"},uh={id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"Amount",currency:"₹",min:0,max:15e4},{id:"us80cPolicyNumber",type:"text",label:"Policy Number"}]},{id:"section80ccd1b",type:"group",title:"Section 80CCD(1B)",fields:[{id:"us80ccd1bAmount",type:"number",label:"Amount",currency:"₹",min:0},{id:"us80ccd1bPanNo",type:"text",label:"PRAN No."}]},{id:"section80ccd2",type:"group",title:"Section 80CCD(2)",fields:[{id:"us80ccd2Amount",type:"number",label:"Amount",currency:"₹",min:0}]},{id:"section80g",type:"group",title:"Section 80G — Donations",fields:[{id:"us80gDonationAmount",type:"number",label:"Donation Amount",currency:"₹",min:0},{id:"us80gNameOfCharity",type:"text",label:"Name of Charity / Trust"},{id:"us80gCharityPan",type:"text",label:"Charity / Trust PAN"},{id:"us80gTrustAddress",type:"text",label:"Trust / Charity Address"},{id:"us80gPincode",type:"text",label:"Pincode",maxLength:6,pattern:ah}]},{id:"section80e",type:"group",title:"Section 80E — Education Loan Interest",fields:[{id:"us80eLoanTakenFrom",type:"text",label:"Loan Taken From"},{id:"us80eBankName",type:"text",label:"Bank Name"},{id:"us80eLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0}]},{id:"section80ee",type:"group",title:"Section 80EEB — Electric Vehicle Loan Interest",fields:[{id:"us80eeLoanTakenFrom",type:"text",label:"Loan Taken From"},{id:"us80eeBankName",type:"text",label:"Bank Name"},{id:"us80eeLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eeLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eeLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eeOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eeVehicleRegistrationNumber",type:"text",label:"Vehicle Registration Number"}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Self — Amount",currency:"₹",min:0,max:25e3},{id:"us80dForSelfAndFamilyPolicyCompany",type:"text",label:"Self — Policy Company Name"},{id:"us80dForSelfAndFamilyPolicyNumber",type:"text",label:"Self — Policy Number"},{id:"us80dForParentsAmount",type:"number",label:"Parents — Amount",currency:"₹",min:0,max:5e4},{id:"us80dForParentsPolicyCompany",type:"text",label:"Parents — Policy Company Name"},{id:"us80dForParentsPolicyNumber",type:"text",label:"Parents — Policy Number"}]}],submitLabel:"Save"},dh={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"},hh={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"},fh={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"},ph={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:sh,maxLength:11}]}],submitLabel:"Save"},mh=[ch,fh,dh,hh,lh,uh,ph];function gh(o,e){const t=o||{},r={userId:It(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Te(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:Ih()};r.us80cAmount=Ee(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Ee(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Ee(t.us80dForParentsAmount),r.hasParentOverSixty=Vr(t.hasParentOverSixty),r.preventiveHealthCheckUp=Ee(t.preventiveHealthCheckUp),r.medicalExpenditure=Ee(t.medicalExpenditure),r.savingBankInterest=Ee(t.savingBankInterest),r.fdInterest=Ee(t.fdInterest),r.dividend=Ee(t.dividend),r.anyOtherIncome=Ee(t.anyOtherIncome),r.cryptoSellValue=Ee(t.cryptoSellPrice),r.cryptoPurchaseAmount=Ee(t.cryptoPurchasePrice),r.vdaPurchaseCost=Ee(t.cryptoPurchasePrice);const s=(Ee(t.bizReceiptsBank)??0)+(Ee(t.bizReceiptsCash)??0),n=(Ee(t.profReceiptsBank)??0)+(Ee(t.profReceiptsCash)??0),i=Te(t.bizName)!==void 0||s>0;r.businessName=Te(i?t.bizName:t.profName),r.businessAnnualTurnOver=i?s||void 0:n||void 0,r.agricultureDetails={income:Ee(t.agricultureIncome)},r.exemptIncomeAmount=Ee(t.exemptIncome),r.exemptIncomeNature=Te(t.exemptIncomeNature),Ee(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Te(t.exemptIncomeNature)??"Exempt income",value:String(Ee(t.exemptIncome))}]),r.bankAccountNumber=Te(t.bankAccountNumber),r.bankIfscCode=Te(t.bankIfscCode),(Te(t.bankAccountNumber)||Te(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Te(t.bankAccountNumber),bankIfscCode:Te(t.bankIfscCode)}]);const a={description:Te(t.immovableAssetDescription),flatNo:Te(t.immovableAssetFlatNo),area:Te(t.immovableAssetArea),pinCode:Te(t.immovableAssetPincode),amount:Ee(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=sn(t.hpDetails,bh);l.length&&(r.hpDetails=l);const c=sn(t.salaryDetails,yh);if(c.length){r.salaryIncome=c;const u=sn(t.salaryDetails,p=>({grossSalary:Ee(p.grossSalary),employerName:Te(p.employerName)}));u.length&&(r.salary=u);const d=Zr(t.salaryDetails)[0]??{};r.hraAmount=Ee(d.hraReceived),r.leaveTravelAllowanceAmount=Ee(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Ee(d.leaveEncashment),r.anyOtherAllowanceAmount=Ee(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return Nt(r)}function bh(o){const e={loanType:"HOME_LOAN",loanTakenFrom:Te(o.loanTakenFrom),bankOrInstituteName:Te(o.lenderName),loanAccountNo:Te(o.loanAccountNumber),loanSanctionDate:Kl(o.sanctionDate),totalLoanAmount:Ee(o.totalLoanAmount),loanOutstandingAmount:Ee(o.outstandingAmount),interest:Ee(o.homeLoanInterest)},t=Object.entries(e).some(([r,s])=>r!=="loanType"&&s!==void 0);return{typeOfHouseProperty:Te(o.typeOfHouseProperty),hasRentalIncome:o.typeOfHouseProperty==="LOP"?!0:Vr(o.hasRentalIncome),homeLoanInterest:Ee(o.homeLoanInterest),homeLoanPrinciple:Ee(o.homeLoanPrinciple),housePropertyAddress:Te(o.housePropertyAddress),housePropertyPincode:Te(o.housePropertyPincode),rentalIncome:Ee(o.rentalIncome),nameOfTenant:Te(o.nameOfTenant),propertyTax:Ee(o.propertyTax),hasCoOwnedProperty:Vr(o.hasCoOwnedProperty),coOwnerName:Te(o.coOwnerName),coOwnerPan:Te(o.coOwnerPan),coOwnerShare:Te(o.coOwnerShare),loanDetails:t?[e]:void 0}}function yh(o){return{grossSalaryIncome:Ee(o.grossSalary),salary:Ee(o.basicSalary),employer:{employerName:Te(o.employerName),employerTan:Te(o.employerTan)},allowance:{hraAmount:Ee(o.hraReceived),leaveTravelAllowanceAmount:Ee(o.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Ee(o.leaveEncashment),anyOtherAllowanceAmount:Ee(o.anyOtherAllowance)}}}function vh(o,e){const t=[];for(const r of o){const s=Te(r.employerName),n=Te(r.employerTan),i=Ee(r.grossSalary),a=Ee(r.basicSalary),l=Ee(r.totalTdsDeposited);s===void 0&&n===void 0&&i===void 0&&a===void 0&&l===void 0||t.push({grossSalary:i??0,basicSalary:a??0,employerName:s??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:It(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function wh(o,e){const t=Te(o.aadhaarNumber),r=Te(o.bankAccountNumber),s=Te(o.bankIfscCode);return t===void 0&&r===void 0&&s===void 0?null:{userId:It(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:s}]}}function _h(o,e){return{userId:It(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Ee(o.savingBankInterest)??0,fdInterest:Ee(o.fdInterest)??0,dividend:Ee(o.dividend)??0,anyOtherIncome:Ee(o.anyOtherIncome)??0,familyPension:Ee(o.familyPension)??0}}function kh(o,e){const t=Ee(o.cryptoSellPrice),r=Ee(o.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:It(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function xh(o,e){const t=(s,n,i,a)=>{const l=Te(o[s]),c=Te(o[n]),u=Ee(o[i]),d=Ee(o[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(s=>s!==null);return r.length?{userId:It(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Sh(o){return Te(o.lenderName)!==void 0||Te(o.loanAccountNumber)!==void 0||Ee(o.totalLoanAmount)!==void 0||Ee(o.outstandingAmount)!==void 0||Ee(o.homeLoanInterest)!==void 0}function Vl(o){const e=Te(o.typeOfHouseProperty)?.toUpperCase();return Ee(o.rentalIncome)!==void 0||Te(o.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function Eh(o,e){const t=Zr(o.hpDetails).filter(Sh).map(r=>{const s=Nt({loanType:"HOMELOAN",bankOrInstituteName:Te(r.lenderName),loanAccountNo:Te(r.loanAccountNumber),loanSanctionDate:Kl(r.sanctionDate),totalLoanAmount:Ee(r.totalLoanAmount),loanOutstandingAmount:Ee(r.outstandingAmount),interest:Ee(r.homeLoanInterest)});return Nt({typeOfHouseProperty:Te(r.typeOfHouseProperty),housePropertyAddress:Te(r.housePropertyAddress),housePropertyPincode:Te(r.housePropertyPincode),homeLoanInterest:Ee(r.homeLoanInterest),homeLoanPrinciple:Ee(r.homeLoanPrinciple),propertyTax:Ee(r.propertyTax),eligible80EEAAmount:Ee(r.eligible80EEAAmount),eligible80EEAmount:Ee(r.eligible80EEAmount),hasCoOwnedProperty:Vr(r.hasCoOwnedProperty)??!1,hasRentalIncome:Vl(r),loanDetails:[s]})});return t.length?{userId:It(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Ah(o,e){const t=Zr(o.hpDetails).filter(Vl).map(r=>Nt({typeOfHouseProperty:Te(r.typeOfHouseProperty),housePropertyAddress:Te(r.housePropertyAddress),housePropertyPincode:Te(r.housePropertyPincode),rentalIncome:Ee(r.rentalIncome),propertyTax:Ee(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Te(r.nameOfTenant),tenantPanNumber:Te(r.tenantPanNumber),homeLoanInterest:Ee(r.homeLoanInterest)}));return t.length?{userId:It(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function It(o){if(o===void 0||o==="")return;const e=Number(o);return Number.isFinite(e)&&String(e)===String(o)?e:o}function Ee(o){if(o==null||o==="")return;const e=typeof o=="number"?o:Number(o);return Number.isFinite(e)?e:void 0}function Te(o){if(o==null)return;const e=String(o).trim();return e===""?void 0:e}function Vr(o){return o===!0||o===!1?o:void 0}function Ih(){const o=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${o.getFullYear()}-${e(o.getMonth()+1)}-${e(o.getDate())}T${e(o.getHours())}:${e(o.getMinutes())}:${e(o.getSeconds())}.${e(o.getMilliseconds(),3)}`}function Kl(o){const e=Te(o);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Zr(o){return Array.isArray(o)?o.filter(e=>e&&typeof e=="object"):[]}function sn(o,e){return Zr(o).map(t=>Nt(e(t))).filter(t=>t!==void 0)}function Nt(o){if(Array.isArray(o)){const e=o.map(Nt).filter(t=>t!==void 0);return e.length?e:void 0}if(o&&typeof o=="object"){const e={};for(const[t,r]of Object.entries(o)){const s=Nt(r);s!==void 0&&(e[t]=s)}return Object.keys(e).length?e:void 0}return o}function Th(o){const e=o&&typeof o=="object"?o:{},t={},r=Ue(e.employers),s=Ue(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(A=>{const C=an(A.salary),O=an(A.perquisites),j=an(A.profitsInLieuOfSalaryType),T=C+O+j,B=Ph(A.allowance);return{employerName:Ce(A.employerName),employerTan:Ce(A.employerTAN),basicSalary:C||void 0,grossSalary:T||void 0,hraReceived:B.hra,leaveTravelAllowance:B.lta,leaveEncashment:B.leaveEncashment,anyOtherAllowance:B.other,totalTdsDeposited:Ch(A,s,r)??Re(A.totalTdsDeposited)}}));const n=Ue(e.houseProperties);n.length&&(t.hpDetails=n.map(A=>{const C=Ue(A.loanDetails),O=C.length?C[0]:void 0,j=Re(A.grossAnnualRentReceived),T=C.length?C.reduce((Y,W)=>Y+(Re(W.interest)??0),0):void 0,B=Ue(A.tenant),D=Ue(A.coOwners),U=B[0],oe=D[0];return{typeOfHouseProperty:Ce(A.propertyType),loanTakenFrom:Ce(O?.loanTakenFrom),lenderName:Ce(O?.bankOrInstituteName),loanAccountNumber:Ce(O?.loanAccountNo),sanctionDate:Ys(O?.loanSanctionDate),totalLoanAmount:Re(O?.totalLoanAmount),outstandingAmount:Re(O?.loanOutstandingAmount),homeLoanInterest:T,homeLoanPrinciple:void 0,housePropertyAddress:Ce(A.address),housePropertyPincode:Ce(A.pinCode),rentalIncome:j,nameOfTenant:Ce(U?.name),tenantPanNumber:Ce(U?.panNumber),eligible80EEAmount:Re(A.eligible80EEAmount),eligible80EEAAmount:Re(A.eligible80EEAAmount),propertyTax:Re(A.propertyTax),hasCoOwnedProperty:D.length>0,coOwnerName:Ce(oe?.name),coOwnerPan:Ce(oe?.panNumber),coOwnerShare:Re(oe?.share)?.toString()}}));const i=Ue(e.deductionUS80CDetails),a=wt(i.map(A=>Re(A.amount))),l=i.find(A=>Ce(A.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ce(l?.identificationNo);const c=Ue(e.deductionUS80DDetails),u=c.find(A=>Ce(A.policyFor)?.toUpperCase()==="DEPENDANT")??Ue(e.insurances).find(A=>Ce(A.policyFor)?.toUpperCase()==="DEPENDANT"),d=c.find(A=>Ce(A.policyFor)?.toUpperCase()==="PARENTS")??Ue(e.insurances).find(A=>Ce(A.policyFor)?.toUpperCase()==="PARENTS"),p=Array.isArray(u?.bifurcation)?u.bifurcation[0]:void 0,b=Array.isArray(d?.bifurcation)?d.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Re(u?.healthInsuranceAmount??u?.premium),t.us80dForSelfAndFamilyPolicyCompany=Ce(u?.insurerName??p?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Ce(u?.policyNo??p?.accountNo),t.us80dForParentsAmount=Re(d?.healthInsuranceAmount??d?.premium),t.us80dForParentsPolicyCompany=Ce(d?.insurerName??b?.insurerName),t.us80dForParentsPolicyNumber=Ce(d?.policyNo??b?.accountNo),t.hasParentOverSixty=Oh(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=void 0,t.us80ccd1bPanNo=Ce(e.pranNumber),t.us80ccd2Amount=void 0;const g=Ue(e.donations)[0];t.us80gDonationAmount=Re(g?.amount??g?.donationAmount),t.us80gNameOfCharity=Ce(g?.nameOfCharity??g?.donorName??g?.trustName),t.us80gCharityPan=Ce(g?.panNumber??g?.charityPan),t.us80gTrustAddress=Ce(g?.address??g?.charityAddress),t.us80gPincode=Ce(g?.pinCode??g?.pincode);const w=Ue(e.houseProperties?.[0]?.loanDetails)[0];t.us80eLoanTakenFrom=void 0,t.us80eBankName=void 0,t.us80eLoanAccountNumber=void 0,t.us80eLoanSanctionDate=void 0,t.us80eLoanAmount=void 0,t.us80eeLoanTakenFrom=Ce(w?.loanTakenFrom),t.us80eeBankName=Ce(w?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ce(w?.loanAccountNo),t.us80eeLoanSanctionDate=Ys(w?.loanSanctionDate),t.us80eeLoanAmount=Re(w?.totalLoanAmount),t.us80eeOutstandingLoan=Re(w?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ce(w?.vehicleRegistrationNo);const m=Ue(e.insurances);t.preventiveHealthCheckUp=wt(m.map(A=>Re(A.preventiveCheckUp))),t.medicalExpenditure=wt(m.map(A=>Re(A.medicalExpenditure)));const _=Ue(e.incomes),x=A=>wt(_.filter(C=>Ce(C.incomeType)===A).map(C=>Re(C.amount)));t.savingBankInterest=x("SAVING_INTEREST"),t.fdInterest=x("FD_RD_INTEREST"),t.anyOtherIncome=x("ANY_OTHER"),t.familyPension=x("FAMILY_PENSION"),t.dividend=wt(Ue(e.dividendIncomes).map(A=>Re(A.income)));const v=e.business;if(v){const A=Ue(v.presumptiveIncomes),C=T=>{const B=Ue(T.incomes),D=U=>Re(B.find(oe=>Ce(oe.incomeType)===U)?.receipts)??0;return D("ANY_OTHER")>0?!0:D("BANK")>0||D("CASH")>0?!1:!!Ce(T.businessType)?.toUpperCase().includes("PROFESSION")},O=T=>A.find(B=>C(B)===T),j=(T,B)=>{if(!T)return;const D=Ue(T.incomes),U=Y=>Re(D.find(W=>Ce(W.incomeType)===Y)?.receipts),oe=U("BANK")||U("ANY_OTHER");t[B.name]=Ce(T.businessType),t[B.nature]=Ce(T.natureOfBusiness),t[B.bank]=oe||void 0,t[B.cash]=U("CASH")||void 0,t[B.net]=wt(D.map(Y=>Re(Y.presumptiveIncome)))||void 0};j(O(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),j(O(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const E=Ue(e.capitalGain).filter(A=>Ce(A.assetType)?.toUpperCase()==="VDA").flatMap(A=>Ue(A.assetDetails));E.length&&(t.cryptoSellPrice=wt(E.map(A=>Re(A.sellValue))),t.cryptoPurchasePrice=wt(E.map(A=>Re(A.purchaseCost)))),t.agricultureIncome=Re(e.agriculturalDetails?.income),t.aadhaarNumber=Ce(e.aadharNumber);const S=Ue(e.bankDetails)[0];return S&&(t.bankAccountNumber=Ce(S.accountNumber),t.bankIfscCode=Ce(S.ifsCode)),Gl(t)}function Ys(o){const e=Ce(o);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function an(o){return Ue(o).reduce((e,t)=>e+(Re(t.taxableAmount)??0),0)}function Ch(o,e,t){if(!e.length)return;const r=Ce(o.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ce(n.deductorTAN)?.trim().toUpperCase()===r)return Re(n.totalTdsDeposited)}const s=Ce(o.employerName)?.trim().toLowerCase();if(s){for(const n of e)if(Ce(n.deductorName)?.trim().toLowerCase()===s)return Re(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Re(e[0].totalTdsDeposited)}function Ph(o){const e=Ue(o);if(!e.length)return{};let t,r,s,n;for(const i of e){const a=Re(i.exemptAmount)??Re(i.allowanceAmount);switch(Ce(i.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":s=a;break;default:n=(n??0)+(Re(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:s,other:n}}function wt(o){let e=0,t=!1;for(const r of o)r!=null&&(e+=r,t=!0);return t?e:void 0}function Ue(o){return Array.isArray(o)?o.filter(e=>e&&typeof e=="object"):[]}function Re(o){if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"&&o.trim()!==""&&Number.isFinite(Number(o)))return Number(o)}function Ce(o){if(o==null)return;const e=String(o).trim();return e===""?void 0:e}function Oh(o){if(typeof o=="boolean")return o;if(typeof o=="string"){const e=o.trim().toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="y")return!0;if(e==="false"||e==="0"||e==="no"||e==="n")return!1}if(typeof o=="number")return o===1?!0:o===0?!1:void 0}function Gl(o){const e={};for(const[t,r]of Object.entries(o))r!==void 0&&(Array.isArray(r)?e[t]=r.map(s=>s&&typeof s=="object"?Gl(s):s):e[t]=r);return e}function ln(){if(typeof window>"u")return null;const o=window,e=o.__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=o.__aikaara_descriptor__??{},r=$h(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 s=qh(e.slug),n=typeof s?.tenantJwt=="string"?s.tenantJwt:"",i=e.getChatJwt,a=async()=>n||await i(),l=(s&&s.userId!=null&&s.userId!==""?String(s.userId):Wh(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:Hh(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||zh(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function Mh(o){const e=await o.getToken(),t=o.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${o.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...o.headers}});if(!r.ok){const s=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${s.slice(0,200)}`)}return Th(Oo(await r.json().catch(()=>({}))))}async function Rh(o,e){const t=await o.getToken(),r=o.userId,s={...gh(e,{userId:r,assessmentYear:o.assessmentYear,isRevised:o.isRevised}),sendSummary:!0},n=o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...o.headers};o.txbdyApiKey&&(i["txbdy-api-key"]=o.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(s).join(", "));const a=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(s)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Oo(await a.json().catch(()=>({})))}async function Lh(o,e){return Dt(o,`${o.baseUrl}/itr/v1/automation/salary`,e)}async function Nh(o,e){return Dt(o,`${o.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function jh(o,e){return Dt(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function Uh(o,e){return Dt(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function Bh(o,e){return Dt(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function Dh(o,e){return Dt(o,`${o.baseUrl}/itr/v1/automation/hp-income`,e)}async function Fh(o,e){return Dt(o,`${o.baseUrl}/itr/v1/automation/vda`,e)}async function Dt(o,e,t){const s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await o.getToken()}`,...o.headers};o.txbdyApiKey&&(s["txbdy-api-key"]=o.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:s,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 Oo(await n.json().catch(()=>({})))}function $h(o){const e=[o.cloud?.listEndpoint,o.cloud?.downloadEndpoint,o.upload?.signEndpoint,o.login?.pan?.basicPanEndpoint,o.login?.pan?.panDetailEndpoint,o.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 qh(o){if(!o||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${o}`);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 Hh(o){const e={};if(!o)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,s]of Object.entries(o))!t.test(r)&&typeof s=="string"&&(e[r]=s);return e}function Wh(o){if(!o)return;const e=o.userId??o.id??o.ext_uid??o.extUid;return e==null||e===""?void 0:String(e)}function Oo(o){if(o&&typeof o=="object"){const e=o;return e.data&&typeof e.data=="object"?e.data:e}return{}}function zh(){const o=new Date,e=o.getMonth()>=3?o.getFullYear():o.getFullYear()-1;return`${e}-${e+1}`}class Vh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Hl(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??{},s=t.attributes?.action??{},n={...t.attributes,action:{...r,...s}};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(),s=r(e);return t.some(n=>typeof n=="string"&&r(n)===s)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:mh,data:{}});const t=ln();if(!(!t||!t.baseUrl))try{const r=await Mh(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=ln();if(!r)return;const s={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],i=vh(n,s);i&&await Lh(r,i)}else if(e==="bank-details"){const n=wh(t,s);n&&await Nh(r,n)}else if(e==="other-sources")await jh(r,_h(t,s));else if(e==="business-profession"){const n=xh(t,s);n&&await Uh(r,n)}else if(e==="crypto-income"){const n=kh(t,s);n&&await Fh(r,n)}else if(e==="house-property"){const n=Eh(t,s);n&&await Bh(r,n);const i=Ah(t,s);i&&await Dh(r,i)}}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=ln();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Rh(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 Yl 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||Dc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Ro,position:this.getAttribute("position")||this._config.position||Bc,width:Number(this.getAttribute("width"))||this._config.width||Lc,height:Number(this.getAttribute("height"))||this._config.height||Nc,fontFamily:this._config.fontFamily||Uc,borderRadius:this._config.borderRadius??jc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Lo,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||Fc,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,s){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??s),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=s=>typeof s=="number"?`${s}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(([,s])=>s!==void 0&&s!=="").map(([s,n])=>`--aikaara-${s}: ${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;
|
|
12
12
|
z-index: 9999;
|
|
13
13
|
bottom: var(--aikaara-offset-y);
|
|
14
14
|
${e.position==="bottom-left"?"left":"right"}: var(--aikaara-offset-x);
|
|
15
|
-
`,
|
|
15
|
+
`,s=`
|
|
16
16
|
font-family: var(--aikaara-font);
|
|
17
17
|
display: flex;
|
|
18
18
|
flex-direction: column;
|
|
@@ -60,7 +60,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
60
60
|
--aikaara-offset-x: ${e.offset?.x??20}px;
|
|
61
61
|
--aikaara-offset-y: ${e.offset?.y??20}px;
|
|
62
62
|
${this.themeVars(e.themeTokens)}
|
|
63
|
-
${t?
|
|
63
|
+
${t?s:r}
|
|
64
64
|
}
|
|
65
65
|
|
|
66
66
|
.aikaara-panel {
|
|
@@ -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 Vh(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),s=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|s<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class Jl 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 Kh=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class Ql extends HTMLElement{shadow;actions=Kh;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 s=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:s,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"),s=this.getAttribute("status")||"connected",n=s==="connected"?"#10b981":s==="connecting"||s==="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 Gh=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,Yh=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,Jh={""":'"',"'":"'","<":"<",">":">","&":"&"," ":" "};function Qh(o){return o.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>Jh[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 zt(o){if(Gh.test(o))return o;const e=Yh.test(o)?Qh(o):o;let t=Xh(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,s,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,s,n)=>{const i=/[.,!?;:]+$/.exec(n),a=i?i[0]:"",l=a?n.slice(0,n.length-a.length):n;return`${s}<a href="${l}" target="_self" rel="noopener noreferrer">${l}</a>${a}`}),t=t.replace(/\n/g,"<br>"),t}function Xh(o){const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return o.replace(/[&<>"']/g,t=>e[t])}const Zh=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"]),ef={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 Vt(o){const e=document.createElement("template");return e.innerHTML=o,Xl(e.content),e.innerHTML}function Xl(o){const e=Array.from(o.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,s=r.tagName.toLowerCase();if(!Zh.has(s)){const a=document.createTextNode(r.textContent||"");o.replaceChild(a,t);continue}const n=ef[s]||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")}Xl(t)}}function Zl(o,e={}){const{width:t=600,height:r=700,closeOnTypes:s}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),i=Math.round(window.screenY+(window.outerHeight-r)/2),a=window.open(o,"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;s&&typeof d=="string"&&!s.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 tf(o){const e=Date.now()-o.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 s=Math.round(r/60);if(s<24)return`${s} hr ago`;const n=Math.round(s/24);return n===1?"Yesterday":n<7?`${n} d ago`:o.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class ec 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(s=>r.includes(s)):!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 s=this.linkHandlers.some(i=>Js(r.href,i.match));r.target==="_self"&&!s||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">${Vt(zt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const
|
|
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">${Vt(zt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const s=r.externalId??r.id;this.appendMessageElement(r,t.get(s))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;let r=-1;for(let s=e.length-1;s>=0;s--)if(e[s].role==="user"){r=s;break}for(let s=0;s<e.length;s++){const n=e[s];if(n.role==="user"){const i=n.metadata?.attributes?.action;if(i){const a=rf(i);if(i.message_id&&t.set(i.message_id,a),Object.keys(a).length>0)for(let l=s-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&&s<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=Vt(zt(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 p=document.createElement("aikaara-system-pill");p.setAttribute("text",e.content),d.appendChild(p),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 s=document.createElement("div");s.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?s.classList.add("attachment-only"):s.textContent=e.content:i?e.content&&(s.innerHTML=Vt(zt(e.content))):(s.innerHTML=Vt(zt(e.content||"")),e.status==="streaming"&&s.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 p=e.externalId??e.id;p&&d.setAttribute("message-id",p),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):s.appendChild(d)}const l=e.template?.templateId==="7";if(e.attachments?.length&&!l){const d=document.createElement("div");d.classList.add("attachments");for(const p of e.attachments){const b=document.createElement("aikaara-template-renderer");b.setAttribute("content-type","300"),b.setAttribute("template-id","7");const f={elements:[{description:p.fileName,action:{url:p.fileUrl,type:"link",isDeepLink:!0}}]};b.setPayload(f,""),d.appendChild(b)}s.appendChild(d)}const u=!(s.childNodes.length===0&&(s.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(s),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 p=document.createElement("span");p.classList.add("status-tick"),e.status==="read"&&p.classList.add("read"),p.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",d.appendChild(p)}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 tf(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(b=>Js(e,b.match)),s=r?.target??"iframe";if(s==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(s==="popup"){Zl(e);return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(s==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const a=nf(e),l=tc(r.fetch.url,a),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const b=await this.getLinkBearer(u);b&&(c.authorization=`Bearer ${b}`)}const d={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",d.body=JSON.stringify(ho(r.fetch.body,a)));let p=null;try{const b=await fetch(l,d);b.ok&&(p=await b.json().catch(()=>null))}catch(b){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",b)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,b=>{const f=r.props??{setData:p};for(const[y,w]of Object.entries(f)){const m=b[y];typeof m=="function"&&m.call(b,w)}const g=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})))};b.addEventListener("aikaara-plan-select",g),b.addEventListener("aikaara-select",g)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function rf(o){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,s]of Object.entries(o))e.has(r)||(Array.isArray(s)&&s.every(n=>typeof n=="string")?t[r]=s:typeof s=="string"&&(t[r]=[s]));return t}function Js(o,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(o)}function nf(o){try{const e=new URL(o),t={};return e.searchParams.forEach((r,s)=>{t[s]=r}),t}catch{return{}}}function tc(o,e){return o.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function ho(o,e){if(typeof o=="string")return tc(o,e);if(Array.isArray(o))return o.map(t=>ho(t,e));if(o&&typeof o=="object"){const t={};for(const[r,s]of Object.entries(o))t[r]=ho(s,e);return t}return o}class rc 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")||"",s=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||"":Vt(zt(t)),c=e==="user"&&s,u=s==="sending"?"○":s==="sent"?"✓":s==="delivered"||s==="read"?"✓✓":"";this.shadow.innerHTML=`
|
|
479
479
|
<style>
|
|
480
480
|
:host { display: flex; flex-direction: column; }
|
|
481
481
|
:host([role="user"]) { align-items: flex-end; }
|
|
@@ -514,7 +514,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
514
514
|
}
|
|
515
515
|
.status {
|
|
516
516
|
font-size: 10px;
|
|
517
|
-
color: ${
|
|
517
|
+
color: ${s==="read"?"var(--aikaara-primary, #6366f1)":"var(--aikaara-text-secondary, #6b7280)"};
|
|
518
518
|
margin-left: 4px;
|
|
519
519
|
}
|
|
520
520
|
.attachments {
|
|
@@ -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="${Qs(a)}"
|
|
547
547
|
></aikaara-template-renderer>`:""}
|
|
548
548
|
${this.renderAttachments()}
|
|
549
549
|
</div>
|
|
@@ -552,15 +552,15 @@ 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
|
|
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",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${Qs(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
|
|
556
|
+
📎 ${of(t.fileName)}
|
|
557
|
+
</a>`).join("")}</div>`:""}}function Qs(o){return String(o).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function of(o){return String(o).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class nc 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")??"",s=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"/>
|
|
561
561
|
</svg>
|
|
562
562
|
</button>
|
|
563
|
-
<input type="file" ${r?`accept="${r}"`:""} ${
|
|
563
|
+
<input type="file" ${r?`accept="${r}"`:""} ${s?"multiple":""} />`:"",l=`
|
|
564
564
|
<button class="send-btn" aria-label="Send message" type="button" disabled>
|
|
565
565
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
566
566
|
<line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
|
|
@@ -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
|
|
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 ic 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 oc 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=Vt(zt(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=Vt(zt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class sc 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 cn=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 cn=new Map;function ac(o){const e=cn.get(o);if(e)return e;const t=new Promise((r,s)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(o)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>s(new Error(`Failed to load ${o}`)),{once:!0}));return}const i=document.createElement("script");i.src=o,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=o,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{cn.delete(o),s(new Error(`Failed to load ${o}`))},{once:!0}),document.head.appendChild(i)});return cn.set(o,t),t}function sf(o,e=5e3){return new Promise((t,r)=>{const s=setTimeout(()=>r(new Error(`Custom element <${o}> not registered within ${e}ms`)),e);customElements.whenDefined(o).then(()=>{clearTimeout(s),t()})})}const af={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>require("./AikaaraPaymentLink-D_SZ081m.cjs")).then(({registerAikaaraPaymentLink:o})=>o())};function lf(o){const e=`template:${o}`,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?.[o]}class lc 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 s=df(t.attributes.action);if(Object.keys(s).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(s))}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 s=localStorage.getItem(`aikaara_form:${r}`);s&&(e=JSON.parse(s))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(s=>{const n=s,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?lf(t):void 0,s=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=af[s];if(n&&!customElements.get(s)?n().then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] native template ${s} failed to load`,i)):r?.scriptUrl&&!customElements.get(s)&&ac(r.scriptUrl).then(()=>sf(s)).then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,i)),customElements.get(s)){const i=document.createElement(s);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 <${s}>`,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 s=document.createElement("aikaara-text-input");s.setPayload(r),this.appendChild(s);return}if(t==="checkbox"||t==="radio"||t==="button"){const s=document.createElement("aikaara-option-list");s.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(s);return}if(t==="submit"){const s=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;s.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(s);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(()=>require("./AikaaraLinkButton-RQCl2v5d.cjs")).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:s})=>{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:uf(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 cf=new Set(["type","url","name","openLinkInNewTab","orderId"]);function uf(o){const e={};for(const[t,r]of Object.entries(o))cf.has(t)||(e[t]=r);return e}function df(o){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,s]of Object.entries(o))e.has(r)||(Array.isArray(s)&&s.every(n=>typeof n=="string")?t[r]=s:typeof s=="string"&&(t[r]=[s]));return t}class cc 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">${Xs(e)}</span>
|
|
786
|
+
${t?`<span class="sub">${Xs(t)}</span>`:""}
|
|
787
|
+
`}}function Xs(o){return String(o).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class uc 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,s=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 {
|
|
@@ -825,9 +825,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
825
825
|
<path d="M3 8 L7 12 L13 4" />
|
|
826
826
|
</svg>
|
|
827
827
|
</span>
|
|
828
|
-
<span class="text">${
|
|
828
|
+
<span class="text">${Pt(e)}</span>
|
|
829
829
|
</div>
|
|
830
|
-
`,!this.preSelectedDisabled){const c=this.shadow.querySelector(".row");if(c){const u=()=>this.toggle(i.value);c.addEventListener("click",u),c.addEventListener("keydown",
|
|
830
|
+
`,!this.preSelectedDisabled){const c=this.shadow.querySelector(".row");if(c){const u=()=>this.toggle(i.value);c.addEventListener("click",u),c.addEventListener("keydown",d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),u())})}}return}if(r==="radio"){const i=this.preSelectedDisabled?"default":"pointer";this.shadow.innerHTML=`
|
|
831
831
|
<style>
|
|
832
832
|
:host { display: block; margin: 8px 0; }
|
|
833
833
|
.title {
|
|
@@ -867,14 +867,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
867
867
|
.row[aria-checked="true"] .dot { opacity: 1; transform: scale(1); }
|
|
868
868
|
.label { flex: 1; }
|
|
869
869
|
</style>
|
|
870
|
-
${e?`<div class="title">${
|
|
871
|
-
<div class="list" role="radiogroup" aria-label="${
|
|
870
|
+
${e?`<div class="title">${Pt(e)}</div>`:""}
|
|
871
|
+
<div class="list" role="radiogroup" aria-label="${Pt(e??this.data.name)}">
|
|
872
872
|
${t.map(a=>{const l=this.selected.has(a.value);return`
|
|
873
873
|
<div class="row" role="radio" tabindex="${this.preSelectedDisabled?"-1":"0"}"
|
|
874
874
|
aria-checked="${l}" aria-disabled="${this.preSelectedDisabled}"
|
|
875
875
|
data-value="${un(a.value)}">
|
|
876
876
|
<span class="circle" aria-hidden="true"><span class="dot"></span></span>
|
|
877
|
-
<span class="label">${
|
|
877
|
+
<span class="label">${Pt(a.label)}</span>
|
|
878
878
|
</div>`}).join("")}
|
|
879
879
|
</div>
|
|
880
880
|
`,this.preSelectedDisabled||this.shadow.querySelectorAll(".row").forEach(a=>{const l=()=>this.toggle(a.dataset.value||"");a.addEventListener("click",l),a.addEventListener("keydown",c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),l())})});return}this.shadow.innerHTML=`
|
|
@@ -910,18 +910,18 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
910
910
|
border-color: var(--aikaara-option-selected-border, var(--aikaara-primary, #6366f1));
|
|
911
911
|
}
|
|
912
912
|
</style>
|
|
913
|
-
${e?`<div class="title">${
|
|
914
|
-
<div class="grid" role="${
|
|
913
|
+
${e?`<div class="title">${Pt(e)}</div>`:""}
|
|
914
|
+
<div class="grid" role="${s?"group":"radiogroup"}" aria-label="${Pt(e??this.data.name)}">
|
|
915
915
|
${t.map(i=>`
|
|
916
916
|
<button class="opt" type="button"
|
|
917
917
|
data-value="${un(i.value)}"
|
|
918
|
-
role="${
|
|
918
|
+
role="${s?"checkbox":"radio"}"
|
|
919
919
|
aria-pressed="${this.selected.has(i.value)}"
|
|
920
920
|
${this.preSelectedDisabled?'disabled aria-disabled="true"':""}>
|
|
921
|
-
${
|
|
921
|
+
${Pt(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
|
|
924
|
+
`,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(i=>{i.addEventListener("click",()=>this.toggle(i.dataset.value||""))})}}function Pt(o){return String(o).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}function un(o){return String(o).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class dc 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(s=>{(s.validate?.()??!0)||(r=!1)}),r?(t.querySelectorAll("aikaara-option-list").forEach(s=>{const n=s.getValues?.();n?.name&&(e[n.name]=n.type==="radio"?n.values[0]??"":n.values)}),t.querySelectorAll("aikaara-text-input").forEach(s=>{const n=s.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">${hf(e)}</button>
|
|
943
|
+
`,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function hf(o){return String(o).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class hc 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 {
|
|
@@ -981,14 +981,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
981
981
|
</style>
|
|
982
982
|
<div class="overlay" role="dialog" aria-modal="true">
|
|
983
983
|
<div class="modal">
|
|
984
|
-
<div class="msg">${
|
|
984
|
+
<div class="msg">${dn(this.data.message)}</div>
|
|
985
985
|
<div class="actions">
|
|
986
|
-
${t?`<button class="cancel" type="button">${
|
|
987
|
-
<button class="ok" type="button">${
|
|
986
|
+
${t?`<button class="cancel" type="button">${dn(t)}</button>`:""}
|
|
987
|
+
<button class="ok" type="button">${dn(e)}</button>
|
|
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
|
|
991
|
+
`,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function dn(o){return String(o).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class fc 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,s=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 {
|
|
@@ -1022,7 +1022,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1022
1022
|
}
|
|
1023
1023
|
:host([data-consumed]) input { pointer-events: none; opacity: 0.65; background: var(--aikaara-input-bg, #f9fafb); }
|
|
1024
1024
|
</style>
|
|
1025
|
-
<label>${rr(e)}${
|
|
1025
|
+
<label>${rr(e)}${s}</label>
|
|
1026
1026
|
<input
|
|
1027
1027
|
type="text"
|
|
1028
1028
|
placeholder="${rr(t)}"
|
|
@@ -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">${rr(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 rr(
|
|
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 rr(o){return String(o).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class pc 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"),s=this.tokenGetter??r;if(!s){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 Oc({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:s,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 mc 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 s=!1;this.iframe.addEventListener("load",()=>{s=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{s||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const s=this.shadow.querySelector(".modal-title");s&&(s.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 ff=[{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"}],pf=[{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 gc extends HTMLElement{shadow;data=null;columns=pf;features=ff;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;
|
|
@@ -1137,35 +1137,35 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1137
1137
|
<thead>
|
|
1138
1138
|
<tr>
|
|
1139
1139
|
<th>Feature</th>
|
|
1140
|
-
${e.map(r=>`<th>${
|
|
1140
|
+
${e.map(r=>`<th>${hn(r.label)}</th>`).join("")}
|
|
1141
1141
|
</tr>
|
|
1142
1142
|
</thead>
|
|
1143
1143
|
<tbody>
|
|
1144
|
-
${t.map((r,
|
|
1144
|
+
${t.map((r,s)=>`
|
|
1145
1145
|
<tr>
|
|
1146
|
-
<td>${
|
|
1147
|
-
${e.map(n=>n.features[
|
|
1146
|
+
<td>${hn(r.label)}</td>
|
|
1147
|
+
${e.map(n=>n.features[s]?'<td><span class="check">✓</span></td>':'<td><span class="cross">✕</span></td>').join("")}
|
|
1148
1148
|
</tr>`).join("")}
|
|
1149
1149
|
<tr class="price-row">
|
|
1150
1150
|
<td>Price (excl. GST)</td>
|
|
1151
|
-
${e.map(r=>{const
|
|
1151
|
+
${e.map(r=>{const s=this.priceFor(r);return`<td>${s!=null?"₹"+Math.round(s):"—"}</td>`}).join("")}
|
|
1152
1152
|
</tr>
|
|
1153
1153
|
</tbody>
|
|
1154
1154
|
</table>
|
|
1155
1155
|
<div class="actions">
|
|
1156
|
-
${e.map((r,
|
|
1157
|
-
<span>${
|
|
1156
|
+
${e.map((r,s)=>{const n=this.priceFor(r),i=r.selectLabel.replace("{price}",n!=null?String(Math.round(n)):"—");return`<button class="action" data-col="${s}" type="button">
|
|
1157
|
+
<span>${hn(i)}</span>
|
|
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
|
|
1161
|
+
`,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const s=Number(r.dataset.col),n=e[s];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function hn(o){return o.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class bc 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("[]"),s=r?t.slice(0,-2):t,n=this.data[s];return r?Array.isArray(n)?n:[]:n??null}handleSectionSubmit(e,t){const r=this.schemas.find(s=>s.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">${
|
|
1165
|
-
`;const r=this.shadow.querySelector(".modal-body"),
|
|
1166
|
-
<button class="chip" type="button" data-section-id="${
|
|
1164
|
+
<button class="icon-btn close-btn" type="button" aria-label="Close">${Zs}</button>
|
|
1165
|
+
`;const r=this.shadow.querySelector(".modal-body"),s=this.schemas.map(i=>`
|
|
1166
|
+
<button class="chip" type="button" data-section-id="${gf(i.id)}">
|
|
1167
1167
|
<span class="chip-icon">${i.icon??"📄"}</span>
|
|
1168
|
-
<span class="chip-label">${
|
|
1168
|
+
<span class="chip-label">${ea(i.title)}</span>
|
|
1169
1169
|
</button>`).join("");r.innerHTML=`
|
|
1170
1170
|
<div class="picker">
|
|
1171
1171
|
<div class="intro-card">
|
|
@@ -1175,15 +1175,15 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1175
1175
|
<div class="intro-sub">Select a category to edit</div>
|
|
1176
1176
|
</div>
|
|
1177
1177
|
</div>
|
|
1178
|
-
<div class="chip-grid">${
|
|
1178
|
+
<div class="chip-grid">${s}</div>
|
|
1179
1179
|
</div>
|
|
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">${
|
|
1186
|
-
`;const
|
|
1183
|
+
<button class="icon-btn back-btn" type="button" aria-label="Back">${mf}</button>
|
|
1184
|
+
<div class="modal-title">${ea(t?.title??"Edit")}</div>
|
|
1185
|
+
<button class="icon-btn close-btn" type="button" aria-label="Close">${Zs}</button>
|
|
1186
|
+
`;const s=this.shadow.querySelector(".modal-footer");s.style.display="none",s.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(s=>s.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",(s=>{const n=s.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">
|
|
1189
1189
|
<div class="modal view-picker" role="dialog" aria-modal="true" aria-label="Correct Your ITR Details">
|
|
@@ -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 Zs='<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>',mf='<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 gf(o){return o.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function ea(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}class yc 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 s=this.getEntries(),n={...s[e]||{}};n[t]=r,s[e]=n,this.isRepeatable()?this.value=s: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||[],s=>{if(!this.fieldVisible(s,t)||s.type==="group")return;const n=t[s.id],i=`${r}.${s.id}`;if(s.required&&(n==null||n==="")){this.errors.set(i,"Required");return}if(s.type==="text"&&typeof n=="string"&&(s.pattern&&n&&!new RegExp(s.pattern).test(n)?this.errors.set(i,"Invalid format"):s.maxLength&&n.length>s.maxLength&&this.errors.set(i,`Max ${s.maxLength} characters`)),s.type==="textarea"&&typeof n=="string"&&s.maxLength&&n.length>s.maxLength&&this.errors.set(i,`Max ${s.maxLength} characters`),s.type==="number"&&n!==void 0&&n!==null&&n!==""){const a=typeof n=="number"?n:Number(n),l=s;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((s,n)=>this.renderEntry(s,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">
|
|
@@ -1341,42 +1341,42 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1341
1341
|
</button>
|
|
1342
1342
|
</div>
|
|
1343
1343
|
</div>
|
|
1344
|
-
`,this.bindHandlers()}renderEntry(e,t){const
|
|
1344
|
+
`,this.bindHandlers()}renderEntry(e,t){const s=this.isRepeatable()&&this.schema?.repeatable?this.schema.repeatable.labelTemplate.replace("{index}",String(t+1)):"",n=this.isRepeatable()&&this.getEntries().length>1?`<button class="remove-btn" type="button" data-entry-index="${t}" data-action="remove-entry" aria-label="Remove">Remove</button>`:"",i=(this.schema?.fields||[]).map(l=>this.renderField(l,e,t)).join("");return`<section class="entry-card">${s?`<div class="entry-header">
|
|
1345
1345
|
<span class="entry-label">
|
|
1346
1346
|
${this.schema?.entryIcon?`<span class="entry-icon">${this.schema.entryIcon}</span>`:""}
|
|
1347
|
-
${Ge(
|
|
1347
|
+
${Ge(s)}
|
|
1348
1348
|
</span>
|
|
1349
1349
|
${n}
|
|
1350
|
-
</div>`:""}<div class="entry-body">${i}</div></section>`}renderField(e,t,r){if(!this.fieldVisible(e,t))return"";if(e.type==="group"){const
|
|
1350
|
+
</div>`:""}<div class="entry-body">${i}</div></section>`}renderField(e,t,r){if(!this.fieldVisible(e,t))return"";if(e.type==="group"){const d=e,p=d.fields.map(g=>this.renderField(g,t,r)).join("");if(!d.collapsible)return`
|
|
1351
1351
|
<fieldset class="group">
|
|
1352
|
-
${
|
|
1353
|
-
${
|
|
1352
|
+
${d.title?`<legend class="group-title">${Ge(d.title)}</legend>`:""}
|
|
1353
|
+
${d.hint?`<div class="group-hint">${Ge(d.hint)}</div>`:""}
|
|
1354
1354
|
<div class="group-body">${p}</div>
|
|
1355
|
-
</fieldset>`;const b=`${r}.${
|
|
1356
|
-
<fieldset class="group group--collapsible ${
|
|
1357
|
-
<button type="button" class="group-toggle" data-action="toggle-group" data-group-key="${
|
|
1358
|
-
<span class="group-title">${Ge(
|
|
1355
|
+
</fieldset>`;const b=`${r}.${d.id}`;d.defaultCollapsed&&!this.collapseSeeded.has(b)&&(this.collapseSeeded.add(b),this.collapsed.add(b));const f=this.collapsed.has(b);return`
|
|
1356
|
+
<fieldset class="group group--collapsible ${f?"is-collapsed":""}">
|
|
1357
|
+
<button type="button" class="group-toggle" data-action="toggle-group" data-group-key="${_t(b)}" aria-expanded="${!f}">
|
|
1358
|
+
<span class="group-title">${Ge(d.title??"")}</span>
|
|
1359
1359
|
<span class="group-chevron" aria-hidden="true"></span>
|
|
1360
1360
|
</button>
|
|
1361
|
-
${
|
|
1362
|
-
<div class="group-body" ${
|
|
1363
|
-
</fieldset>`}const
|
|
1361
|
+
${d.hint&&!f?`<div class="group-hint">${Ge(d.hint)}</div>`:""}
|
|
1362
|
+
<div class="group-body" ${f?"hidden":""}>${p}</div>
|
|
1363
|
+
</fieldset>`}const s=`${r}.${e.id}`,n=this.errors.get(s),i=n?"has-error":"",a=e.required?'<span class="req">*</span>':"",l=e.label?`<label class="field-label" for="${this.fieldHtmlId(e,r)}">${Ge(e.label)} ${a}</label>`:"",c=this.renderInput(e,t,r),u=n?`<div class="field-error">${Ge(n)}</div>`:"";return`
|
|
1364
1364
|
<div class="field ${i}" data-field-id="${e.id}" data-entry-index="${r}">
|
|
1365
1365
|
${l}
|
|
1366
1366
|
${c}
|
|
1367
1367
|
${u}
|
|
1368
|
-
</div>`}renderInput(e,t,r){const
|
|
1368
|
+
</div>`}renderInput(e,t,r){const s=t[e.id],n=this.fieldHtmlId(e,r),i=`data-field-id="${e.id}" data-entry-index="${r}"`;if(e.type==="text"){const a=e,l=a.readOnly?"input--readonly":"",c=a.readOnly?"disabled":"";return`<input type="text" class="input ${l}" id="${n}" ${i} value="${_t(String(s??""))}" placeholder="${_t(a.placeholder??"")}" ${a.maxLength?`maxlength="${a.maxLength}"`:""} ${c}/>`}if(e.type==="textarea"){const a=e;return`<textarea class="input textarea" id="${n}" ${i} rows="${a.rows??4}" placeholder="${_t(a.placeholder??"")}" ${a.maxLength?`maxlength="${a.maxLength}"`:""}>${Ge(String(s??""))}</textarea>`}if(e.type==="number"){const a=e,l=a.currency?`<span class="prefix">${Ge(a.currency)}</span>`:"",c=a.readOnly?"disabled":"",u=a.readOnly?"input--readonly":"";return`
|
|
1369
1369
|
<div class="input-with-prefix">
|
|
1370
1370
|
${l}
|
|
1371
|
-
<input type="number" class="input ${u}" id="${n}" ${i} value="${
|
|
1372
|
-
</div>`}if(e.type==="date")return`<input type="date" class="input" id="${n}" ${i} value="${
|
|
1371
|
+
<input type="number" class="input ${u}" id="${n}" ${i} value="${_t(String(s??""))}" placeholder="${_t(a.placeholder??"")}" ${a.min!==void 0?`min="${a.min}"`:""} ${a.max!==void 0?`max="${a.max}"`:""} ${c}/>
|
|
1372
|
+
</div>`}if(e.type==="date")return`<input type="date" class="input" id="${n}" ${i} value="${_t(String(s??""))}"/>`;if(e.type==="radio")return`
|
|
1373
1373
|
<div class="radio-group">
|
|
1374
|
-
${e.options.map(l=>{const c=
|
|
1374
|
+
${e.options.map(l=>{const c=s===l.value?"checked":"",u=`${n}-${l.value}`;return`
|
|
1375
1375
|
<label class="radio-item ${c?"selected":""}" for="${u}">
|
|
1376
|
-
<input type="radio" id="${u}" ${i} name="${n}" value="${
|
|
1376
|
+
<input type="radio" id="${u}" ${i} name="${n}" value="${_t(l.value)}" ${c}/>
|
|
1377
1377
|
<span class="radio-label">${Ge(l.label)}</span>
|
|
1378
1378
|
</label>`}).join("")}
|
|
1379
|
-
</div>`;if(e.type==="yes-no"){const a=
|
|
1379
|
+
</div>`;if(e.type==="yes-no"){const a=s===!0?"checked":"",l=s===!1?"checked":"";return`
|
|
1380
1380
|
<div class="radio-group">
|
|
1381
1381
|
<label class="radio-item ${a?"selected":""}">
|
|
1382
1382
|
<input type="radio" ${i} name="${n}" value="true" ${a}/>
|
|
@@ -1388,9 +1388,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1388
1388
|
</label>
|
|
1389
1389
|
</div>`}return e.type==="checkbox"?`
|
|
1390
1390
|
<label class="checkbox-item">
|
|
1391
|
-
<input type="checkbox" id="${n}" ${i} ${
|
|
1391
|
+
<input type="checkbox" id="${n}" ${i} ${s===!0?"checked":""}/>
|
|
1392
1392
|
<span class="checkbox-label">${Ge(e.label??"")}</span>
|
|
1393
|
-
</label>`:""}fieldHtmlId(e,t){return`aikf-${e.id}-${t}`}bindHandlers(){this.shadow.querySelectorAll("input[data-field-id], textarea[data-field-id]").forEach(e=>{const t=e,r=t.dataset.fieldId,
|
|
1393
|
+
</label>`:""}fieldHtmlId(e,t){return`aikf-${e.id}-${t}`}bindHandlers(){this.shadow.querySelectorAll("input[data-field-id], textarea[data-field-id]").forEach(e=>{const t=e,r=t.dataset.fieldId,s=Number(t.dataset.entryIndex||0),i=t.type==="radio"||t.type==="checkbox"?"change":"input";t.addEventListener(i,()=>{let a;t.type==="checkbox"?a=t.checked:t.type==="radio"?t.value==="true"?a=!0:t.value==="false"?a=!1:a=t.value:t.type==="number"?a=t.value===""?null:Number(t.value):a=t.value,i==="input"?this.setEntryNoRender(s,r,a):this.setEntry(s,r,a)})}),this.shadow.querySelector('[data-action="save"]')?.addEventListener("click",()=>this.handleSubmit()),this.shadow.querySelector('[data-action="add-entry"]')?.addEventListener("click",()=>this.addEntry()),this.shadow.querySelectorAll('[data-action="toggle-group"]').forEach(e=>{e.addEventListener("click",()=>{const t=e.dataset.groupKey;this.collapsed.has(t)?this.collapsed.delete(t):this.collapsed.add(t),this.render()})}),this.shadow.querySelectorAll('[data-action="remove-entry"]').forEach(e=>{e.addEventListener("click",()=>{const t=Number(e.dataset.entryIndex||0);this.removeEntry(t)})})}css(){return`
|
|
1394
1394
|
/* Pure-flex height chain — no percentage heights, which do not
|
|
1395
1395
|
resolve reliably through a max-height-only flex ancestor. The
|
|
1396
1396
|
modal makes this element a flex item (flex:1; min-height:0); we
|
|
@@ -1596,4 +1596,4 @@ 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 wt(s){return s.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ge(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function yc(){const s=[["aikaara-chat-widget",Gl],["aikaara-chat-bubble",Yl],["aikaara-chat-header",Jl],["aikaara-message-list",Zl],["aikaara-message-bubble",tc],["aikaara-chat-input",rc],["aikaara-typing-indicator",nc],["aikaara-streaming-message",ic],["aikaara-error-banner",oc],["aikaara-template-renderer",ac],["aikaara-system-pill",lc],["aikaara-option-list",cc],["aikaara-submit-action",uc],["aikaara-modal-action",hc],["aikaara-text-input",dc],["aikaara-chat",fc],["aikaara-link-modal",pc],["aikaara-compare-plans",mc],["aikaara-smart-edit-modal",gc],["aikaara-schema-form",bc]];for(const[e,t]of s)customElements.get(e)||customElements.define(e,t)}yc();function gr(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 ea(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 Kt(s){return typeof s=="function"?await s():s}class vc{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=ea(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 Kt(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=gr(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,h=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!h)throw new Error("Session auth response missing token");const p=gr(l,this.descriptor.requestIdPath??"data.requestId"),b=this.cache?.requestId||p||"",d=gr(l,this.descriptor.fullNamePath??"data.fullName"),g=gr(l,this.descriptor.userPath??"data.userId"),y=ea(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:b,fullName:d,userId:g,expiresAt:y},this.cache}}async function wc(s){const e={};for(const t of s.spec){const r=await pf(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 pf(s,e){const t=s.key??s.name;switch(s.source){case"cookie":return mf(t);case"localStorage":return br(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return br(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return br(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return br(()=>document.querySelector(`meta[name="${gf(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 mf(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 br(s){try{return s()}catch{return}}function gf(s){return s.replace(/["\\]/g,"\\$&")}const bf=1800;class _c{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 wc({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 h=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${h.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??bf;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 yf=3e4,vf=2e3,wf=100;async function kc(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=_f(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=kf(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=If(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:yf;return{token:await Af({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=xf(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=Sf(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:vf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:wf,i=await Ef(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 xc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await kc(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 _f(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 kf(s){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(s)??void 0}catch{return}}function xf(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 Sf(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 Ef(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 Af(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 If(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 Tf(){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 Cf="aikaara_chat:requestId";function Mo(s,e,t){const r=`${Cf}:${s}:${e}`;return t?`${r}:${t}`:r}function Ec(s,e,t){try{return localStorage.getItem(Mo(s,e,t))}catch{return null}}function Of(s,e,t,r){try{localStorage.setItem(Mo(s,e,r),t)}catch{}}function Pf(s,e,t){try{localStorage.removeItem(Mo(s,e,t))}catch{}}async function fo(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,h]of Object.entries(e.identity))typeof h=="string"&&(o[u]=h);typeof e.serviceType=="string"&&(o.serviceType=e.serviceType),typeof e.userType=="string"&&(o.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(h,p)=>p in o?o[p]:""),i=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(i);if(u&&typeof u=="object"){const h={};for(const[p,b]of Object.entries(u))h[p]=i(b);return h}return u},a=await Kt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const h=r[u],p=n(h.url),b=h.method??(h.body?"POST":"GET"),d={accept:"application/json",...h.headers??{}};if((h.authHeader??"session")==="session"){const x=h.authHeaderTemplate??"Bearer {token}";d.authorization=x.replace("{token}",a)}const g={method:b,headers:d};h.body&&(d["content-type"]="application/json",g.body=JSON.stringify(i(h.body)));let y=0,w="",m=0,_=null;for(;;)try{const x=await fetch(p,g);if(x.ok){_=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&Rf(y,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${b} ${p} → ${y} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${b} ${p} → ${y} ${w.slice(0,200)}`;if(h.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(h.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(_&&h.capture&&h.capture.as)try{const x=await _.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(h.capture.path)for(const E of h.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;h.capture.stripPrefix&&E.startsWith(h.capture.stripPrefix)&&(E=E.slice(h.capture.stripPrefix.length)),l[h.capture.as]=E,o[h.capture.as]=E,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${h.capture.as} (${E.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function Mf(s){const e=s.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await fo(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 Rf(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 Ic(s,e){return s.replace("{projectId}",e).replace("{uuid}",Tf().replace(/-/g,""))}function Tc(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=>sc(r)))}async function Cc(s){const e={...s.config??(s.configUrl?await Ac(s.configUrl,s.configHeaders):{}),...s.overrides??{}};Tc(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:Ec(n,o,i),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=s.conversationId??a??Ic(l,o);(s.conversationId||!a||s.forceNewConversation)&&o&&Of(n,o,c,i);const u=await s.tokenProvider(),h=s.tokenProvider,p=s.historyTokenProvider??h,b=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:h}:void 0,d=s.uploadAdapter??(e.uploadEndpoint?Oo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),g=s.historyAdapter??(e.historyApiBase?Wl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):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:b,tiledeskIdentity:{userId:n,userName:s.identity.userName,departmentId:s.identity.departmentId,senderFullname:s.identity.senderFullname??s.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:d,historyAdapter:g,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 Lf(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 Oc(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(Tc(o),o.templates&&Object.keys(o.templates).length>0){o.components={...o.components??{}};for(const[I,O]of Object.entries(o.templates)){const P=`template:${I}`;o.components[P]||!O?.scriptUrl||!O?.render||(o.components[P]={kind:"iife-element",scriptUrl:O.scriptUrl,tag:O.render,...O.props?{props:O.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,h=null;const p=await Kt(s.user.token).catch(()=>""),b=typeof p=="string"&&p.length>0;if(!b&&o.sso?.tokenSource){h=new xc({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 h.get();u=async()=>(await h.get()).token,s.user.identity&&!s.user.identity.partnerToken&&(s.user.identity.partnerToken=I.token)}else if(!b&&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 _c({descriptor:o.sso,providers:s.user.credentialProviders,exchangeUrl:I}).get(),a=i.extUid||a,l=l??i.displayName,c=i.userToken}let d="",g="";if(o.preflight&&o.preflight.length){const I=await fo(o.preflight,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:s.user.identity});if(I.captured.sessionToken){d=I.captured.sessionToken;const O=d;u=()=>O}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const y=new vc(o.auth,u);if(d){const I=o.tiledesk?.projectId??"",O=I?Ec(a,I):null,P=o.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=O??(I?Ic(P,I):"");y.prime(d,{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:()=>Kt(s.user.token),identity:s.user.identity,slug:s.slug,configBase:e};const _=h&&o.sso?.autoRefresh?async()=>{try{return await h.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 Kt(s.user.token)}`,E=s.hooks?.upload??(x&&x.mode==="presigned-3step"?Hl({...x,authHeader:v}):x&&x.mode==="direct"?Oo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await Cc({container:Lf(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||g||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:Kt(s.user.token)});return Object.assign(S,{fullName:m,requestId:w.requestId,descriptor:o,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return _?_():null},async runMethodSelectPreflight(I){const O=o.preflight;return!O||!O.length?{}:O.some(j=>j.trigger==="on-method-select")?(await fo(O,{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:{}}})}exports.ActionCableClient=fn;exports.AikaaraChat=fc;exports.AikaaraChatBubble=Yl;exports.AikaaraChatClient=ql;exports.AikaaraChatHeader=Jl;exports.AikaaraChatInput=rc;exports.AikaaraChatWidget=Gl;exports.AikaaraComparePlans=mc;exports.AikaaraErrorBanner=oc;exports.AikaaraLinkModal=pc;exports.AikaaraMessageBubble=tc;exports.AikaaraMessageList=Zl;exports.AikaaraModalAction=hc;exports.AikaaraOptionList=cc;exports.AikaaraSchemaForm=bc;exports.AikaaraSmartEditModal=gc;exports.AikaaraStreamingMessage=ic;exports.AikaaraSubmitAction=uc;exports.AikaaraSystemPill=lc;exports.AikaaraTemplateRenderer=ac;exports.AikaaraTextInput=dc;exports.AikaaraTypingIndicator=nc;exports.ApiClient=na;exports.ChannelSubscription=ta;exports.ConnectionManager=ra;exports.ConversationManager=sa;exports.EventEmitter=po;exports.MessageStore=ia;exports.SessionAuthAdapter=vc;exports.SsoExchangeAdapter=_c;exports.TiledeskTransport=Bl;exports.TokenDiscoveryError=Xe;exports.TokenDiscoveryReader=xc;exports.clearPersistedConversationId=Pf;exports.collectSsoCredentials=wc;exports.createFetchUploadAdapter=Oo;exports.createPresigned3StepUploadAdapter=Hl;exports.createTiledeskHistoryAdapter=Wl;exports.discoverToken=kc;exports.extractTiledeskFileEnvelope=Fl;exports.inferTiledeskRole=$l;exports.isTiledeskSelfEcho=Dl;exports.mount=Cc;exports.mountFromSlug=Oc;exports.openInPopupWindow=Xl;exports.parseTiledeskTemplate=Co;exports.registerComponents=yc;exports.runMethodSelectPreflight=Mf;
|
|
1599
|
+
`}}function _t(o){return o.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ge(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function vc(){const o=[["aikaara-chat-widget",Yl],["aikaara-chat-bubble",Jl],["aikaara-chat-header",Ql],["aikaara-message-list",ec],["aikaara-message-bubble",rc],["aikaara-chat-input",nc],["aikaara-typing-indicator",ic],["aikaara-streaming-message",oc],["aikaara-error-banner",sc],["aikaara-template-renderer",lc],["aikaara-system-pill",cc],["aikaara-option-list",uc],["aikaara-submit-action",dc],["aikaara-modal-action",hc],["aikaara-text-input",fc],["aikaara-chat",pc],["aikaara-link-modal",mc],["aikaara-compare-plans",gc],["aikaara-smart-edit-modal",bc],["aikaara-schema-form",yc]];for(const[e,t]of o)customElements.get(e)||customElements.define(e,t)}vc();function gr(o,e,t=""){if(!e)return t;const r=e.split(".");let s=o;for(const n of r)if(s&&typeof s=="object"&&n in s)s=s[n];else return t;return typeof s=="string"?s:t}function ta(o){try{const e=o.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 Kt(o){return typeof o=="function"?await o():o}class wc{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=ta(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 Kt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",s={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:s};n==="POST"&&(s["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=gr(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 p=gr(l,this.descriptor.requestIdPath??"data.requestId"),b=this.cache?.requestId||p||"",f=gr(l,this.descriptor.fullNamePath??"data.fullName"),g=gr(l,this.descriptor.userPath??"data.userId"),y=ta(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:b,fullName:f,userId:g,expiresAt:y},this.cache}}async function _c(o){const e={};for(const t of o.spec){const r=await bf(t,o.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 bf(o,e){const t=o.key??o.name;switch(o.source){case"cookie":return yf(t);case"localStorage":return br(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return br(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return br(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return br(()=>document.querySelector(`meta[name="${vf(t)}"]`)?.content??void 0);case"callback":{const r=e?.[o.name];if(!r)return;const s=await r();return typeof s=="string"?s:void 0}default:return}}function yf(o){if(typeof document>"u")return;const e=encodeURIComponent(o),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const s=r.indexOf("=");if(s===-1)continue;const n=r.slice(0,s);if(n===o||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function br(o){try{return o()}catch{return}}function vf(o){return o.replace(/["\\]/g,"\\$&")}const wf=1800;class kc{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 _c({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 s=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!s)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(s,{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??wf;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 _f=3e4,kf=2e3,xf=100;async function xc(o){const{descriptor:e}=o,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!o.initToken)throw new Xe("init","No init token supplied to Aikaara.init({token})");return{token:o.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=Sf(r);if(!s)throw new Xe("query",`?${r}= not present`);return{token:s,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=Ef(r);if(!s)throw new Xe("hash",`#${r}= not present`);return{token:s,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",s=typeof t.key=="string"&&t.key?t.key:"token",n=Pf(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:_f;return{token:await Cf({type:r,key:s,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 s=Af(r);if(!s)throw new Xe("cookie",`cookie "${r}" not set`);return{token:s,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",s=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!s)throw new Xe("storage","storage.key not configured");const i=If(r,s,n);if(!i)throw new Xe("storage",`${r}Storage["${s}"] 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 s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:kf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:xf,i=await Tf(r,s,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 Sc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await xc(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 Sf(o){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))===o)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function Ef(o){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(o)??void 0}catch{return}}function Af(o){if(typeof document>"u")return;const e=encodeURIComponent(o),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const s=r.indexOf("=");if(s===-1)continue;const n=r.slice(0,s);if(n===o||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function If(o,e,t){if(!(typeof window>"u"))try{const s=(o==="session"?window.sessionStorage:window.localStorage).getItem(e);if(s==null)return;if(!t)return s;let n;try{n=JSON.parse(s)}catch{return s}const i=Ec(n,t);return typeof i=="string"?i:void 0}catch{return}}async function Tf(o,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const s=Ec(window,o);if(typeof s=="string"&&s.length>0)return s;if(typeof s=="function")try{const n=s();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function Cf(o){return new Promise((e,t)=>{if(typeof window>"u"){t(new Xe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(s)},s=setTimeout(()=>{r(),t(new Xe("postmsg",`timeout after ${o.timeoutMs}ms`))},o.timeoutMs),n=i=>{if(o.origins.length>0&&!o.origins.includes(i.origin))return;const a=i.data;if(!a||typeof a!="object")return;const l=a;if(o.type&&l.type!==o.type)return;const c=l[o.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function Pf(o){return o?o.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Ec(o,e){if(!e)return o;const t=e.split(".").filter(Boolean);let r=o;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Of(){const o=typeof crypto<"u"?crypto:null;if(o?.randomUUID)return o.randomUUID();if(o?.getRandomValues){const e=new Uint8Array(16);o.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 Mf="aikaara_chat:requestId";function Mo(o,e,t){const r=`${Mf}:${o}:${e}`;return t?`${r}:${t}`:r}function Ac(o,e,t){try{return localStorage.getItem(Mo(o,e,t))}catch{return null}}function Rf(o,e,t,r){try{localStorage.setItem(Mo(o,e,r),t)}catch{}}function Lf(o,e,t){try{localStorage.removeItem(Mo(o,e,t))}catch{}}async function fo(o,e,t="before-chat"){const r=o.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const s={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(s[u]=d);typeof e.serviceType=="string"&&(s.serviceType=e.serviceType),typeof e.userType=="string"&&(s.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,p)=>p in s?s[p]:""),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[p,b]of Object.entries(u))d[p]=i(b);return d}return u},a=await Kt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const d=r[u],p=n(d.url),b=d.method??(d.body?"POST":"GET"),f={accept:"application/json",...d.headers??{}};if((d.authHeader??"session")==="session"){const x=d.authHeaderTemplate??"Bearer {token}";f.authorization=x.replace("{token}",a)}const g={method:b,headers:f};d.body&&(f["content-type"]="application/json",g.body=JSON.stringify(i(d.body)));let y=0,w="",m=0,_=null;for(;;)try{const x=await fetch(p,g);if(x.ok){_=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&jf(y,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${b} ${p} → ${y} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${b} ${p} → ${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(_&&d.capture&&d.capture.as)try{const x=await _.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,s[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 Nf(o){const e=o.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await fo(e,{sessionToken:o.sessionToken,userId:o.userId,projectId:o.projectId??"",slug:o.slug??"",identity:o.identity,serviceType:o.serviceType,userType:o.userType},"on-method-select")).captured:{}}function jf(o,e){if(o===503||o===504||o===502)return!0;if(o===401||o===403)return e.trim().length===0;if(o===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Ic(o,e){const t=await fetch(o,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const s=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${s.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 Tc(o,e){return o.replace("{projectId}",e).replace("{uuid}",Of().replace(/-/g,""))}function Cc(o){const e=o._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=>ac(r)))}async function Pc(o){const e={...o.config??(o.configUrl?await Ic(o.configUrl,o.configHeaders):{}),...o.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 s=r?.projectId??"",n=o.identity.userId,i=o.conversationScope||void 0,a=o.forceNewConversation?null:Ac(n,s,i),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=o.conversationId??a??Tc(l,s);(o.conversationId||!a||o.forceNewConversation)&&s&&Rf(n,s,c,i);const u=await o.tokenProvider(),d=o.tokenProvider,p=o.historyTokenProvider??d,b=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:o.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,...o.identity.departmentId?{departmentId:o.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:o.identity.senderFullname??o.identity.userName,tokenProvider:d}:void 0,f=o.uploadAdapter??(e.uploadEndpoint?Po({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),g=o.historyAdapter??(e.historyApiBase?zl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),y={transport:t,baseUrl:"",userToken:o.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:o.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:b,tiledeskIdentity:{userId:n,userName:o.identity.userName,departmentId:o.identity.departmentId,senderFullname:o.identity.senderFullname??o.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:f,historyAdapter:g,onError:o.onError,onMessage:o.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;"),o.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function Uf(o){if(typeof o!="string")return o;const e=document.querySelector(o);if(!e)throw new Error(`mountFromSlug: container "${o}" not found`);return e}async function Oc(o){const e=(o.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(o.slug)}`;let r=null;try{r=await Ic(t,o.configHeaders)}catch(A){if(!o.fallbackConfig)throw A;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${o.slug}" — using fallbackConfig.`,A)}const s={...o.fallbackConfig??{},...r??{},...o.overrides??{}};if(Cc(s),s.templates&&Object.keys(s.templates).length>0){s.components={...s.components??{}};for(const[A,C]of Object.entries(s.templates)){const O=`template:${A}`;s.components[O]||!C?.scriptUrl||!C?.render||(s.components[O]={kind:"iife-element",scriptUrl:C.scriptUrl,tag:C.render,...C.props?{props:C.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:s.templates,components:s.components,razorpay:s.razorpay,title:s.title,cloud:s.cloud??n.__aikaara_descriptor__?.cloud,upload:s.upload??n.__aikaara_descriptor__?.upload,themeSource:s.themeSource??n.__aikaara_descriptor__?.themeSource,api:s.api,auth:s.auth},!s.auth)throw new Error(`mountFromSlug: widget_configs/${o.slug} descriptor must include "auth" block`);let i=null,a=o.user.id,l=o.user.name,c="",u=o.user.token,d=null;const p=await Kt(o.user.token).catch(()=>""),b=typeof p=="string"&&p.length>0;if(!b&&s.sso?.tokenSource){d=new Sc({descriptor:{provider:s.sso.provider,flow:s.sso.flow,skipLogin:s.sso.skipLogin,autoRefresh:s.sso.autoRefresh,tokenSource:s.sso.tokenSource,tokenSourceConfig:s.sso.tokenSourceConfig,fallback:s.sso.fallback,map:s.sso.map},initToken:o.user.partnerToken});const A=await d.get();u=async()=>(await d.get()).token,o.user.identity&&!o.user.identity.partnerToken&&(o.user.identity.partnerToken=A.token)}else if(!b&&s.sso&&s.sso.collect&&s.sso.collect.length>0){const A=`${e}/api/v1/projects/by-slug/${encodeURIComponent(o.slug)}/sso_exchange`;i=await new kc({descriptor:s.sso,providers:o.user.credentialProviders,exchangeUrl:A}).get(),a=i.extUid||a,l=l??i.displayName,c=i.userToken}let f="",g="";if(s.preflight&&s.preflight.length){const A=await fo(s.preflight,{sessionToken:u,userId:a,projectId:s.tiledesk?.projectId??"",slug:o.slug,identity:o.user.identity});if(A.captured.sessionToken){f=A.captured.sessionToken;const C=f;u=()=>C}A.captured.userId&&(a=A.captured.userId),A.captured.requestId&&(g=A.captured.requestId)}const y=new wc(s.auth,u);if(f){const A=s.tiledesk?.projectId??"",C=A?Ac(a,A):null,O=s.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=C??(A?Tc(O,A):"");y.prime(f,{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:()=>Kt(o.user.token),identity:o.user.identity,slug:o.slug,configBase:e};const _=d&&s.sso?.autoRefresh?async()=>{try{return await d.refresh(),y.reset(),(await y.get()).token}catch(A){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",A),null}}:null,x=s.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await y.get()).token:await Kt(o.user.token)}`,E=o.hooks?.upload??(x&&x.mode==="presigned-3step"?Wl({...x,authHeader:v}):x&&x.mode==="direct"?Po({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await Pc({container:Uf(o.container),config:s,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:o.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:E,historyAdapter:o.hooks?.history,conversationId:w.requestId||g||void 0,conversationScope:o.conversationScope,onError:o.hooks?.onError,onMessage:o.hooks?.onMessage,getLinkBearer:async A=>A==="none"?null:A==="chat"?(await y.get()).token:Kt(o.user.token)});return Object.assign(S,{fullName:m,requestId:w.requestId,descriptor:s,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return _?_():null},async runMethodSelectPreflight(A){const C=s.preflight;return!C||!C.length?{}:C.some(j=>j.trigger==="on-method-select")?(await fo(C,{sessionToken:u,userId:a,projectId:s.tiledesk?.projectId??"",slug:o.slug,identity:{...o.user.identity??{},...A?.identity??{}},serviceType:A?.serviceType,userType:A?.userType},"on-method-select")).captured:{}}})}exports.ActionCableClient=fn;exports.AikaaraChat=pc;exports.AikaaraChatBubble=Jl;exports.AikaaraChatClient=Hl;exports.AikaaraChatHeader=Ql;exports.AikaaraChatInput=nc;exports.AikaaraChatWidget=Yl;exports.AikaaraComparePlans=gc;exports.AikaaraErrorBanner=sc;exports.AikaaraLinkModal=mc;exports.AikaaraMessageBubble=rc;exports.AikaaraMessageList=ec;exports.AikaaraModalAction=hc;exports.AikaaraOptionList=uc;exports.AikaaraSchemaForm=yc;exports.AikaaraSmartEditModal=bc;exports.AikaaraStreamingMessage=oc;exports.AikaaraSubmitAction=dc;exports.AikaaraSystemPill=cc;exports.AikaaraTemplateRenderer=lc;exports.AikaaraTextInput=fc;exports.AikaaraTypingIndicator=ic;exports.ApiClient=ia;exports.ChannelSubscription=ra;exports.ConnectionManager=na;exports.ConversationManager=aa;exports.EventEmitter=po;exports.MessageStore=oa;exports.SessionAuthAdapter=wc;exports.SsoExchangeAdapter=kc;exports.TiledeskTransport=Dl;exports.TokenDiscoveryError=Xe;exports.TokenDiscoveryReader=Sc;exports.clearPersistedConversationId=Lf;exports.collectSsoCredentials=_c;exports.createFetchUploadAdapter=Po;exports.createPresigned3StepUploadAdapter=Wl;exports.createTiledeskHistoryAdapter=zl;exports.discoverToken=xc;exports.extractTiledeskFileEnvelope=ql;exports.inferTiledeskRole=$l;exports.isTiledeskSelfEcho=Fl;exports.mount=Pc;exports.mountFromSlug=Oc;exports.openInPopupWindow=Zl;exports.parseTiledeskTemplate=Co;exports.registerComponents=vc;exports.runMethodSelectPreflight=Nf;
|