@aikaara/chat-sdk 1.4.20 → 1.4.21

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.
@@ -1,18 +1,18 @@
1
- var AikaaraChat=(function(Ce){"use strict";class No{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 en{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 No(t,i=>{this.send({command:"message",identifier:t,data:JSON.stringify(i)})});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((i,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>i(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 ur{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(i){console.error(`Error in event handler for "${e}":`,i)}})}removeAllListeners(){this.handlers.clear()}}const Sc=1e3,Ec=10,Ac=400,Ic=600,jo="#6366f1",Tc=12,Cc="system-ui, -apple-system, sans-serif",Uo="Type a message...",Pc="bottom-right",Oc="light",Mc={x:20,y:20},tn="aikaara_conversation_id";class Bo extends ur{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 en(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,i){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...i&&{source:i}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??Ec;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Sc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const i=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new en(i),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const i=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${i}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class Do{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,i){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=i}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 i=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(i,e,r);if(n.status===401&&this.refreshHook){let l=null;try{l=await this.refreshHook()}catch(a){console.warn("[aikaara-chat-sdk] auth refresh hook threw",a)}l&&(this.authToken=l,n=await this.fetchWithHeaders(i,e,r))}if(!n.ok){const l=await n.text();let a;try{const c=JSON.parse(l);a=c.error||c.message||l}catch{a=l}throw new Error(`API error ${n.status}: ${a}`)}const o=await n.json();if(o&&typeof o=="object"&&"success"in o){if(!o.success)throw new Error(`API error: ${o.message||"Request failed"}`);return o.data}return o}async fetchWithHeaders(e,t,r){const i={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(i["X-Api-Key"]=this.apiKey),this.authToken&&(i.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:i};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class Fo{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const i={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(i),i}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(i=>i.status==="sending"&&i.role===e.role&&i.content===e.content&&i.conversationId===e.conversationId&&Date.now()-new Date(i.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 i=$o(this._messages,e);return i?(Object.assign(i,e,{id:i.id}),{message:i,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(i=>i.externalId===e||i.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 i=$o(t,r);if(i){const n=dr(i),o=dr(r);!n&&o&&Object.assign(i,r,{id:i.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function $o(s,e,t=15e3){const r=e.attachments&&e.attachments[0],i=(e.metadata??{}).attributes;if(!(!!r||!!(i&&i.fileMessage)))return null;const o=dr(e),l=qo(e),a=Ho(e);if(!o&&!l&&!a)return null;const c=new Date(e.createdAt).getTime();for(let u=s.length-1;u>=0;u--){const d=s[u],p=d.attachments&&d.attachments[0],g=(d.metadata??{}).attributes;if(!(!!p||!!(g&&g.fileMessage)))continue;const y=(d.content||"").trim().toLowerCase();if(y==="file_uploaded"||y==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const b=dr(d);if(o&&b&&o===b)return d;const w=qo(d);if(l&&w&&l===w)return d;const m=Ho(d);if(a&&m&&a===m)return d}return null}function qo(s){const e=s.attachments&&s.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=Wo(s);if(t)return t}function Ho(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 dr(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=Wo(s);if(r){const i=/[?&]cloudFileId=([^&]+)/.exec(r);if(i)return decodeURIComponent(i[1])}}function Wo(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 zo{_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(tn)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(tn)}catch{return null}}saveToStorage(e){try{localStorage.setItem(tn,e)}catch{}}}var rn=Object.defineProperty,Rc=Object.getOwnPropertyDescriptor,Lc=Object.getOwnPropertyNames,Nc=Object.prototype.hasOwnProperty,Ke=(s,e)=>()=>(s&&(e=s(s=0)),e),pe=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ut=(s,e)=>{for(var t in e)rn(s,t,{get:e[t],enumerable:!0})},jc=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Lc(e))!Nc.call(s,i)&&i!==t&&rn(s,i,{get:()=>e[i],enumerable:!(r=Rc(e,i))||r.enumerable});return s},Re=s=>jc(rn({},"__esModule",{value:!0}),s),le=Ke(()=>{}),Le={};Ut(Le,{_debugEnd:()=>Bn,_debugProcess:()=>Un,_events:()=>ei,_eventsCount:()=>ti,_exiting:()=>xn,_fatalExceptions:()=>Ln,_getActiveHandles:()=>Xo,_getActiveRequests:()=>Qo,_kill:()=>An,_linkedBinding:()=>Yo,_maxListeners:()=>Zn,_preload_modules:()=>Jn,_rawDebug:()=>wn,_startProfilerIdleNotifier:()=>Dn,_stopProfilerIdleNotifier:()=>Fn,_tickCallback:()=>jn,abort:()=>Wn,addListener:()=>ri,allowedNodeEnvironmentFlags:()=>Mn,arch:()=>sn,argv:()=>cn,argv0:()=>Yn,assert:()=>Zo,binding:()=>pn,browser:()=>vn,chdir:()=>yn,config:()=>Sn,cpuUsage:()=>Jt,cwd:()=>gn,debugPort:()=>Kn,default:()=>ui,dlopen:()=>Jo,domain:()=>kn,emit:()=>ai,emitWarning:()=>fn,env:()=>ln,execArgv:()=>un,execPath:()=>Gn,exit:()=>Pn,features:()=>Rn,hasUncaughtExceptionCaptureCallback:()=>es,hrtime:()=>hr,kill:()=>Cn,listeners:()=>rs,memoryUsage:()=>Tn,moduleLoadList:()=>_n,nextTick:()=>Go,off:()=>ii,on:()=>ct,once:()=>ni,openStdin:()=>On,pid:()=>zn,platform:()=>an,ppid:()=>Vn,prependListener:()=>li,prependOnceListener:()=>ci,reallyExit:()=>En,release:()=>bn,removeAllListeners:()=>si,removeListener:()=>oi,resourceUsage:()=>In,setSourceMapsEnabled:()=>Qn,setUncaughtExceptionCaptureCallback:()=>Nn,stderr:()=>qn,stdin:()=>Hn,stdout:()=>$n,title:()=>on,umask:()=>mn,uptime:()=>ts,version:()=>dn,versions:()=>hn});function nn(s){throw new Error("Node.js process "+s+" is not supported by JSPM core outside of Node.js")}function Uc(){!At||!It||(At=!1,It.length?tt=It.concat(tt):Yt=-1,tt.length&&Vo())}function Vo(){if(!At){var s=setTimeout(Uc,0);At=!0;for(var e=tt.length;e;){for(It=tt,tt=[];++Yt<e;)It&&It[Yt].run();Yt=-1,e=tt.length}It=null,At=!1,clearTimeout(s)}}function Go(s){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];tt.push(new Ko(s,e)),tt.length===1&&!At&&setTimeout(Vo,0)}function Ko(s,e){this.fun=s,this.array=e}function qe(){}function Yo(s){nn("_linkedBinding")}function Jo(s){nn("dlopen")}function Qo(){return[]}function Xo(){return[]}function Zo(s,e){if(!s)throw new Error(e||"assertion error")}function es(){return!1}function ts(){return ut.now()/1e3}function hr(s){var e=Math.floor((Date.now()-ut.now())*.001),t=ut.now()*.001,r=Math.floor(t)+e,i=Math.floor(t%1*1e9);return s&&(r=r-s[0],i=i-s[1],i<0&&(r--,i+=fr)),[r,i]}function ct(){return ui}function rs(s){return[]}var tt,At,It,Yt,on,sn,an,ln,cn,un,dn,hn,fn,pn,mn,gn,yn,bn,vn,wn,_n,kn,xn,Sn,En,An,Jt,In,Tn,Cn,Pn,On,Mn,Rn,Ln,Nn,jn,Un,Bn,Dn,Fn,$n,qn,Hn,Wn,zn,Vn,Gn,Kn,Yn,Jn,Qn,ut,Xn,fr,Zn,ei,ti,ri,ni,ii,oi,si,ai,li,ci,ui,Bc=Ke(()=>{le(),ue(),ce(),tt=[],At=!1,Yt=-1,Ko.prototype.run=function(){this.fun.apply(null,this.array)},on="browser",sn="x64",an="browser",ln={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},cn=["/usr/bin/node"],un=[],dn="v16.8.0",hn={},fn=function(s,e){console.warn((e?e+": ":"")+s)},pn=function(s){nn("binding")},mn=function(s){return 0},gn=function(){return"/"},yn=function(s){},bn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},vn=!0,wn=qe,_n=[],kn={},xn=!1,Sn={},En=qe,An=qe,Jt=function(){return{}},In=Jt,Tn=Jt,Cn=qe,Pn=qe,On=qe,Mn={},Rn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Ln=qe,Nn=qe,jn=qe,Un=qe,Bn=qe,Dn=qe,Fn=qe,$n=void 0,qn=void 0,Hn=void 0,Wn=qe,zn=2,Vn=1,Gn="/bin/usr/node",Kn=9229,Yn="node",Jn=[],Qn=qe,ut={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ut.now===void 0&&(Xn=Date.now(),ut.timing&&ut.timing.navigationStart&&(Xn=ut.timing.navigationStart),ut.now=()=>Date.now()-Xn),fr=1e9,hr.bigint=function(s){var e=hr(s);return typeof BigInt>"u"?e[0]*fr+e[1]:BigInt(e[0]*fr)+BigInt(e[1])},Zn=10,ei={},ti=0,ri=ct,ni=ct,ii=ct,oi=ct,si=ct,ai=qe,li=ct,ci=ct,ui={version:dn,versions:hn,arch:sn,platform:an,browser:vn,release:bn,_rawDebug:wn,moduleLoadList:_n,binding:pn,_linkedBinding:Yo,_events:ei,_eventsCount:ti,_maxListeners:Zn,on:ct,addListener:ri,once:ni,off:ii,removeListener:oi,removeAllListeners:si,emit:ai,prependListener:li,prependOnceListener:ci,listeners:rs,domain:kn,_exiting:xn,config:Sn,dlopen:Jo,uptime:ts,_getActiveRequests:Qo,_getActiveHandles:Xo,reallyExit:En,_kill:An,cpuUsage:Jt,resourceUsage:In,memoryUsage:Tn,kill:Cn,exit:Pn,openStdin:On,allowedNodeEnvironmentFlags:Mn,assert:Zo,features:Rn,_fatalExceptions:Ln,setUncaughtExceptionCaptureCallback:Nn,hasUncaughtExceptionCaptureCallback:es,emitWarning:fn,nextTick:Go,_tickCallback:jn,_debugProcess:Un,_debugEnd:Bn,_startProfilerIdleNotifier:Dn,_stopProfilerIdleNotifier:Fn,stdout:$n,stdin:Hn,stderr:qn,abort:Wn,umask:mn,chdir:yn,cwd:gn,env:ln,title:on,argv:cn,execArgv:un,pid:zn,ppid:Vn,execPath:Gn,debugPort:Kn,hrtime:hr,argv0:Yn,_preload_modules:Jn,setSourceMapsEnabled:Qn}}),ce=Ke(()=>{Bc()});function Dc(){if(di)return Bt;di=!0,Bt.byteLength=l,Bt.toByteArray=c,Bt.fromByteArray=p;for(var s=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,n=r.length;i<n;++i)s[i]=r[i],e[r.charCodeAt(i)]=i;e[45]=62,e[95]=63;function o(g){var f=g.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=g.indexOf("=");y===-1&&(y=f);var b=y===f?0:4-y%4;return[y,b]}function l(g){var f=o(g),y=f[0],b=f[1];return(y+b)*3/4-b}function a(g,f,y){return(f+y)*3/4-y}function c(g){var f,y=o(g),b=y[0],w=y[1],m=new t(a(g,b,w)),_=0,x=w>0?b-4:b,v;for(v=0;v<x;v+=4)f=e[g.charCodeAt(v)]<<18|e[g.charCodeAt(v+1)]<<12|e[g.charCodeAt(v+2)]<<6|e[g.charCodeAt(v+3)],m[_++]=f>>16&255,m[_++]=f>>8&255,m[_++]=f&255;return w===2&&(f=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[_++]=f&255),w===1&&(f=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[_++]=f>>8&255,m[_++]=f&255),m}function u(g){return s[g>>18&63]+s[g>>12&63]+s[g>>6&63]+s[g&63]}function d(g,f,y){for(var b,w=[],m=f;m<y;m+=3)b=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(b));return w.join("")}function p(g){for(var f,y=g.length,b=y%3,w=[],m=16383,_=0,x=y-b;_<x;_+=m)w.push(d(g,_,_+m>x?x:_+m));return b===1?(f=g[y-1],w.push(s[f>>2]+s[f<<4&63]+"==")):b===2&&(f=(g[y-2]<<8)+g[y-1],w.push(s[f>>10]+s[f>>4&63]+s[f<<2&63]+"=")),w.join("")}return Bt}function Fc(){return hi?Qt:(hi=!0,Qt.read=function(s,e,t,r,i){var n,o,l=i*8-r-1,a=(1<<l)-1,c=a>>1,u=-7,d=t?i-1:0,p=t?-1:1,g=s[e+d];for(d+=p,n=g&(1<<-u)-1,g>>=-u,u+=l;u>0;n=n*256+s[e+d],d+=p,u-=8);for(o=n&(1<<-u)-1,n>>=-u,u+=r;u>0;o=o*256+s[e+d],d+=p,u-=8);if(n===0)n=1-c;else{if(n===a)return o?NaN:(g?-1:1)*(1/0);o=o+Math.pow(2,r),n=n-c}return(g?-1:1)*o*Math.pow(2,n-r)},Qt.write=function(s,e,t,r,i,n){var o,l,a,c=n*8-i-1,u=(1<<c)-1,d=u>>1,p=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,f=r?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-o))<1&&(o--,a*=2),o+d>=1?e+=p/a:e+=p*Math.pow(2,1-d),e*a>=2&&(o++,a/=2),o+d>=u?(l=0,o=u):o+d>=1?(l=(e*a-1)*Math.pow(2,i),o=o+d):(l=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;s[t+g]=l&255,g+=f,l/=256,i-=8);for(o=o<<i|l,c+=i;c>0;s[t+g]=o&255,g+=f,o/=256,c-=8);s[t+g-f]|=y*128},Qt)}function $c(){if(fi)return vt;fi=!0;let s=Dc(),e=Fc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;vt.Buffer=o,vt.SlowBuffer=w,vt.INSPECT_MAX_BYTES=50;let r=2147483647;vt.kMaxLength=r,o.TYPED_ARRAY_SUPPORT=i(),!o.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 i(){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(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.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,o.prototype),k}function o(h,k,A){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 l(h,k,A)}o.poolSize=8192;function l(h,k,A){if(typeof h=="string")return d(h,k);if(ArrayBuffer.isView(h))return g(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,A);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=h.valueOf&&h.valueOf();if(B!=null&&B!==h)return o.from(B,k,A);let X=y(h);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return o.from(h[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 h)}o.from=function(h,k,A){return l(h,k,A)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function a(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,A){return a(h),h<=0?n(h):k!==void 0?typeof A=="string"?n(h).fill(k,A):n(h).fill(k):n(h)}o.alloc=function(h,k,A){return c(h,k,A)};function u(h){return a(h),n(h<0?0:b(h)|0)}o.allocUnsafe=function(h){return u(h)},o.allocUnsafeSlow=function(h){return u(h)};function d(h,k){if((typeof k!="string"||k==="")&&(k="utf8"),!o.isEncoding(k))throw new TypeError("Unknown encoding: "+k);let A=m(h,k)|0,B=n(A),X=B.write(h,k);return X!==A&&(B=B.slice(0,X)),B}function p(h){let k=h.length<0?0:b(h.length)|0,A=n(k);for(let B=0;B<k;B+=1)A[B]=h[B]&255;return A}function g(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,A){if(k<0||h.byteLength<k)throw new RangeError('"offset" is outside of buffer bounds');if(h.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(h):A===void 0?B=new Uint8Array(h,k):B=new Uint8Array(h,k,A),Object.setPrototypeOf(B,o.prototype),B}function y(h){if(o.isBuffer(h)){let k=b(h.length)|0,A=n(k);return A.length===0||h.copy(A,0,0,k),A}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 b(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),o.alloc(+h)}o.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==o.prototype},o.compare=function(h,k){if(H(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),H(k,Uint8Array)&&(k=o.from(k,k.offset,k.byteLength)),!o.isBuffer(h)||!o.isBuffer(k))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===k)return 0;let A=h.length,B=k.length;for(let X=0,de=Math.min(A,B);X<de;++X)if(h[X]!==k[X]){A=h[X],B=k[X];break}return A<B?-1:B<A?1:0},o.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}},o.concat=function(h,k){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return o.alloc(0);let A;if(k===void 0)for(k=0,A=0;A<h.length;++A)k+=h[A].length;let B=o.allocUnsafe(k),X=0;for(A=0;A<h.length;++A){let de=h[A];if(H(de,Uint8Array))X+de.length>B.length?(o.isBuffer(de)||(de=o.from(de)),de.copy(B,X)):Uint8Array.prototype.set.call(B,de,X);else if(o.isBuffer(de))de.copy(B,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=de.length}return B};function m(h,k){if(o.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 A=h.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 $(h).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(h).length;default:if(X)return B?-1:$(h).length;k=(""+k).toLowerCase(),X=!0}}o.byteLength=m;function _(h,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(h||(h="utf8");;)switch(h){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: "+h);h=(h+"").toLowerCase(),B=!0}}o.prototype._isBuffer=!0;function x(h,k,A){let B=h[k];h[k]=h[A],h[A]=B}o.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},o.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},o.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},o.prototype.toString=function(){let h=this.length;return h===0?"":arguments.length===0?q(this,0,h):_.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(h){if(!o.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:o.compare(this,h)===0},o.prototype.inspect=function(){let h="",k=vt.INSPECT_MAX_BYTES;return h=this.toString("hex",0,k).replace(/(.{2})/g,"$1 ").trim(),this.length>k&&(h+=" ... "),"<Buffer "+h+">"},t&&(o.prototype[t]=o.prototype.inspect),o.prototype.compare=function(h,k,A,B,X){if(H(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),!o.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),A===void 0&&(A=h?h.length:0),B===void 0&&(B=0),X===void 0&&(X=this.length),k<0||A>h.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===h)return 0;let de=X-B,ke=A-k,z=Math.min(de,ke),ie=this.slice(B,X),Ee=h.slice(k,A);for(let Ae=0;Ae<z;++Ae)if(ie[Ae]!==Ee[Ae]){de=ie[Ae],ke=Ee[Ae];break}return de<ke?-1:ke<de?1:0};function v(h,k,A,B,X){if(h.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:h.length-1),A<0&&(A=h.length+A),A>=h.length){if(X)return-1;A=h.length-1}else if(A<0)if(X)A=0;else return-1;if(typeof k=="string"&&(k=o.from(k,B)),o.isBuffer(k))return k.length===0?-1:E(h,k,A,B,X);if(typeof k=="number")return k=k&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(h,k,A):Uint8Array.prototype.lastIndexOf.call(h,k,A):E(h,[k],A,B,X);throw new TypeError("val must be string, number or Buffer")}function E(h,k,A,B,X){let de=1,ke=h.length,z=k.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(h.length<2||k.length<2)return-1;de=2,ke/=2,z/=2,A/=2}function ie(Ae,Ie){return de===1?Ae[Ie]:Ae.readUInt16BE(Ie*de)}let Ee;if(X){let Ae=-1;for(Ee=A;Ee<ke;Ee++)if(ie(h,Ee)===ie(k,Ae===-1?0:Ee-Ae)){if(Ae===-1&&(Ae=Ee),Ee-Ae+1===z)return Ae*de}else Ae!==-1&&(Ee-=Ee-Ae),Ae=-1}else for(A+z>ke&&(A=ke-z),Ee=A;Ee>=0;Ee--){let Ae=!0;for(let Ie=0;Ie<z;Ie++)if(ie(h,Ee+Ie)!==ie(k,Ie)){Ae=!1;break}if(Ae)return Ee}return-1}o.prototype.includes=function(h,k,A){return this.indexOf(h,k,A)!==-1},o.prototype.indexOf=function(h,k,A){return v(this,h,k,A,!0)},o.prototype.lastIndexOf=function(h,k,A){return v(this,h,k,A,!1)};function S(h,k,A,B){A=Number(A)||0;let X=h.length-A;B?(B=Number(B),B>X&&(B=X)):B=X;let de=k.length;B>de/2&&(B=de/2);let ke;for(ke=0;ke<B;++ke){let z=parseInt(k.substr(ke*2,2),16);if(me(z))return ke;h[A+ke]=z}return ke}function I(h,k,A,B){return be($(k,h.length-A),h,A,B)}function P(h,k,A,B){return be(ee(k),h,A,B)}function O(h,k,A,B){return be(fe(k),h,A,B)}function j(h,k,A,B){return be(he(k,h.length-A),h,A,B)}o.prototype.write=function(h,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),h.length>0&&(A<0||k<0)||k>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let de=!1;for(;;)switch(B){case"hex":return S(this,h,k,A);case"utf8":case"utf-8":return I(this,h,k,A);case"ascii":case"latin1":case"binary":return P(this,h,k,A);case"base64":return O(this,h,k,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,h,k,A);default:if(de)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),de=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(h,k,A){return k===0&&A===h.length?s.fromByteArray(h):s.fromByteArray(h.slice(k,A))}function q(h,k,A){A=Math.min(h.length,A);let B=[],X=k;for(;X<A;){let de=h[X],ke=null,z=de>239?4:de>223?3:de>191?2:1;if(X+z<=A){let ie,Ee,Ae,Ie;switch(z){case 1:de<128&&(ke=de);break;case 2:ie=h[X+1],(ie&192)===128&&(Ie=(de&31)<<6|ie&63,Ie>127&&(ke=Ie));break;case 3:ie=h[X+1],Ee=h[X+2],(ie&192)===128&&(Ee&192)===128&&(Ie=(de&15)<<12|(ie&63)<<6|Ee&63,Ie>2047&&(Ie<55296||Ie>57343)&&(ke=Ie));break;case 4:ie=h[X+1],Ee=h[X+2],Ae=h[X+3],(ie&192)===128&&(Ee&192)===128&&(Ae&192)===128&&(Ie=(de&15)<<18|(ie&63)<<12|(Ee&63)<<6|Ae&63,Ie>65535&&Ie<1114112&&(ke=Ie))}}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(h){let k=h.length;if(k<=D)return String.fromCharCode.apply(String,h);let A="",B=0;for(;B<k;)A+=String.fromCharCode.apply(String,h.slice(B,B+=D));return A}function ae(h,k,A){let B="";A=Math.min(h.length,A);for(let X=k;X<A;++X)B+=String.fromCharCode(h[X]&127);return B}function Y(h,k,A){let B="";A=Math.min(h.length,A);for(let X=k;X<A;++X)B+=String.fromCharCode(h[X]);return B}function V(h,k,A){let B=h.length;(!k||k<0)&&(k=0),(!A||A<0||A>B)&&(A=B);let X="";for(let de=k;de<A;++de)X+=ve[h[de]];return X}function re(h,k,A){let B=h.slice(k,A),X="";for(let de=0;de<B.length-1;de+=2)X+=String.fromCharCode(B[de]+B[de+1]*256);return X}o.prototype.slice=function(h,k){let A=this.length;h=~~h,k=k===void 0?A:~~k,h<0?(h+=A,h<0&&(h=0)):h>A&&(h=A),k<0?(k+=A,k<0&&(k=0)):k>A&&(k=A),k<h&&(k=h);let B=this.subarray(h,k);return Object.setPrototypeOf(B,o.prototype),B};function F(h,k,A){if(h%1!==0||h<0)throw new RangeError("offset is not uint");if(h+k>A)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let B=this[h],X=1,de=0;for(;++de<k&&(X*=256);)B+=this[h+de]*X;return B},o.prototype.readUintBE=o.prototype.readUIntBE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let B=this[h+--k],X=1;for(;k>0&&(X*=256);)B+=this[h+--k]*X;return B},o.prototype.readUint8=o.prototype.readUInt8=function(h,k){return h=h>>>0,k||F(h,1,this.length),this[h]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(h,k){return h=h>>>0,k||F(h,2,this.length),this[h]|this[h+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(h,k){return h=h>>>0,k||F(h,2,this.length),this[h]<<8|this[h+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(h,k){return h=h>>>0,k||F(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(h,k){return h=h>>>0,k||F(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},o.prototype.readBigUInt64LE=se(function(h){h=h>>>0,J(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let B=k+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,X=this[++h]+this[++h]*2**8+this[++h]*2**16+A*2**24;return BigInt(B)+(BigInt(X)<<BigInt(32))}),o.prototype.readBigUInt64BE=se(function(h){h=h>>>0,J(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let B=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+A;return(BigInt(B)<<BigInt(32))+BigInt(X)}),o.prototype.readIntLE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let B=this[h],X=1,de=0;for(;++de<k&&(X*=256);)B+=this[h+de]*X;return X*=128,B>=X&&(B-=Math.pow(2,8*k)),B},o.prototype.readIntBE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let B=k,X=1,de=this[h+--B];for(;B>0&&(X*=256);)de+=this[h+--B]*X;return X*=128,de>=X&&(de-=Math.pow(2,8*k)),de},o.prototype.readInt8=function(h,k){return h=h>>>0,k||F(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},o.prototype.readInt16LE=function(h,k){h=h>>>0,k||F(h,2,this.length);let A=this[h]|this[h+1]<<8;return A&32768?A|4294901760:A},o.prototype.readInt16BE=function(h,k){h=h>>>0,k||F(h,2,this.length);let A=this[h+1]|this[h]<<8;return A&32768?A|4294901760:A},o.prototype.readInt32LE=function(h,k){return h=h>>>0,k||F(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},o.prototype.readInt32BE=function(h,k){return h=h>>>0,k||F(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},o.prototype.readBigInt64LE=se(function(h){h=h>>>0,J(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let B=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(k+this[++h]*256+this[++h]*65536+this[++h]*16777216)}),o.prototype.readBigInt64BE=se(function(h){h=h>>>0,J(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let B=(k<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(B)<<BigInt(32))+BigInt(this[++h]*16777216+this[++h]*65536+this[++h]*256+A)}),o.prototype.readFloatLE=function(h,k){return h=h>>>0,k||F(h,4,this.length),e.read(this,h,!0,23,4)},o.prototype.readFloatBE=function(h,k){return h=h>>>0,k||F(h,4,this.length),e.read(this,h,!1,23,4)},o.prototype.readDoubleLE=function(h,k){return h=h>>>0,k||F(h,8,this.length),e.read(this,h,!0,52,8)},o.prototype.readDoubleBE=function(h,k){return h=h>>>0,k||F(h,8,this.length),e.read(this,h,!1,52,8)};function Z(h,k,A,B,X,de){if(!o.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(A+B>h.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(h,k,A,B){if(h=+h,k=k>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,h,k,A,ke,0)}let X=1,de=0;for(this[k]=h&255;++de<A&&(X*=256);)this[k+de]=h/X&255;return k+A},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(h,k,A,B){if(h=+h,k=k>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,h,k,A,ke,0)}let X=A-1,de=1;for(this[k+X]=h&255;--X>=0&&(de*=256);)this[k+X]=h/de&255;return k+A},o.prototype.writeUint8=o.prototype.writeUInt8=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,1,255,0),this[k]=h&255,k+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,2,65535,0),this[k]=h&255,this[k+1]=h>>>8,k+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,2,65535,0),this[k]=h>>>8,this[k+1]=h&255,k+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(h,k,A){return h=+h,k=k>>>0,A||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},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(h,k,A){return h=+h,k=k>>>0,A||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,A,B,X){K(k,B,X,h,A,7);let de=Number(k&BigInt(4294967295));h[A++]=de,de=de>>8,h[A++]=de,de=de>>8,h[A++]=de,de=de>>8,h[A++]=de;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return h[A++]=ke,ke=ke>>8,h[A++]=ke,ke=ke>>8,h[A++]=ke,ke=ke>>8,h[A++]=ke,A}function Q(h,k,A,B,X){K(k,B,X,h,A,7);let de=Number(k&BigInt(4294967295));h[A+7]=de,de=de>>8,h[A+6]=de,de=de>>8,h[A+5]=de,de=de>>8,h[A+4]=de;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return h[A+3]=ke,ke=ke>>8,h[A+2]=ke,ke=ke>>8,h[A+1]=ke,ke=ke>>8,h[A]=ke,A+8}o.prototype.writeBigUInt64LE=se(function(h,k=0){return M(this,h,k,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=se(function(h,k=0){return Q(this,h,k,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(h,k,A,B){if(h=+h,k=k>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,h,k,A,z-1,-z)}let X=0,de=1,ke=0;for(this[k]=h&255;++X<A&&(de*=256);)h<0&&ke===0&&this[k+X-1]!==0&&(ke=1),this[k+X]=(h/de>>0)-ke&255;return k+A},o.prototype.writeIntBE=function(h,k,A,B){if(h=+h,k=k>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,h,k,A,z-1,-z)}let X=A-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+A},o.prototype.writeInt8=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,1,127,-128),h<0&&(h=255+h+1),this[k]=h&255,k+1},o.prototype.writeInt16LE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,2,32767,-32768),this[k]=h&255,this[k+1]=h>>>8,k+2},o.prototype.writeInt16BE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,2,32767,-32768),this[k]=h>>>8,this[k+1]=h&255,k+2},o.prototype.writeInt32LE=function(h,k,A){return h=+h,k=k>>>0,A||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},o.prototype.writeInt32BE=function(h,k,A){return h=+h,k=k>>>0,A||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},o.prototype.writeBigInt64LE=se(function(h,k=0){return M(this,h,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=se(function(h,k=0){return Q(this,h,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ye(h,k,A,B,X,de){if(A+B>h.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(h,k,A,B,X){return k=+k,A=A>>>0,X||ye(h,k,A,4),e.write(h,k,A,B,23,4),A+4}o.prototype.writeFloatLE=function(h,k,A){return te(this,h,k,!0,A)},o.prototype.writeFloatBE=function(h,k,A){return te(this,h,k,!1,A)};function we(h,k,A,B,X){return k=+k,A=A>>>0,X||ye(h,k,A,8),e.write(h,k,A,B,52,8),A+8}o.prototype.writeDoubleLE=function(h,k,A){return we(this,h,k,!0,A)},o.prototype.writeDoubleBE=function(h,k,A){return we(this,h,k,!1,A)},o.prototype.copy=function(h,k,A,B){if(!o.isBuffer(h))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),k>=h.length&&(k=h.length),k||(k=0),B>0&&B<A&&(B=A),B===A||h.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),h.length-k<B-A&&(B=h.length-k+A);let X=B-A;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(k,A,B):Uint8Array.prototype.set.call(h,this.subarray(A,B),k),X},o.prototype.fill=function(h,k,A,B){if(typeof h=="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"&&!o.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(h.length===1){let de=h.charCodeAt(0);(B==="utf8"&&de<128||B==="latin1")&&(h=de)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));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,h||(h=0);let X;if(typeof h=="number")for(X=k;X<A;++X)this[X]=h;else{let de=o.isBuffer(h)?h:o.from(h,B),ke=de.length;if(ke===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(X=0;X<A-k;++X)this[X+k]=de[X%ke]}return this};let G={};function N(h,k,A){G[h]=class extends A{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(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,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,A){let B=`The value of "${h}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),B+=` It must be ${k}. Received ${X}`,B},RangeError);function ne(h){let k="",A=h.length,B=h[0]==="-"?1:0;for(;A>=B+4;A-=3)k=`_${h.slice(A-3,A)}${k}`;return`${h.slice(0,A)}${k}`}function W(h,k,A){J(k,"offset"),(h[k]===void 0||h[k+A]===void 0)&&ge(k,h.length-(A+1))}function K(h,k,A,B,X,de){if(h>A||h<k){let ke=typeof k=="bigint"?"n":"",z;throw k===0||k===BigInt(0)?z=`>= 0${ke} and < 2${ke} ** ${(de+1)*8}${ke}`:z=`>= -(2${ke} ** ${(de+1)*8-1}${ke}) and < 2 ** ${(de+1)*8-1}${ke}`,new G.ERR_OUT_OF_RANGE("value",z,h)}W(B,X,de)}function J(h,k){if(typeof h!="number")throw new G.ERR_INVALID_ARG_TYPE(k,"number",h)}function ge(h,k,A){throw Math.floor(h)!==h?(J(h,A),new G.ERR_OUT_OF_RANGE("offset","an integer",h)):k<0?new G.ERR_BUFFER_OUT_OF_BOUNDS:new G.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${k}`,h)}let oe=/[^+/0-9A-Za-z-_]/g;function R(h){if(h=h.split("=")[0],h=h.trim().replace(oe,""),h.length<2)return"";for(;h.length%4!==0;)h=h+"=";return h}function $(h,k){k=k||1/0;let A,B=h.length,X=null,de=[];for(let ke=0;ke<B;++ke){if(A=h.charCodeAt(ke),A>55295&&A<57344){if(!X){if(A>56319){(k-=3)>-1&&de.push(239,191,189);continue}else if(ke+1===B){(k-=3)>-1&&de.push(239,191,189);continue}X=A;continue}if(A<56320){(k-=3)>-1&&de.push(239,191,189),X=A;continue}A=(X-55296<<10|A-56320)+65536}else X&&(k-=3)>-1&&de.push(239,191,189);if(X=null,A<128){if((k-=1)<0)break;de.push(A)}else if(A<2048){if((k-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((k-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((k-=4)<0)break;de.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return de}function ee(h){let k=[];for(let A=0;A<h.length;++A)k.push(h.charCodeAt(A)&255);return k}function he(h,k){let A,B,X,de=[];for(let ke=0;ke<h.length&&!((k-=2)<0);++ke)A=h.charCodeAt(ke),B=A>>8,X=A%256,de.push(X),de.push(B);return de}function fe(h){return s.toByteArray(R(h))}function be(h,k,A,B){let X;for(X=0;X<B&&!(X+A>=k.length||X>=h.length);++X)k[X+A]=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 A=0;A<16;++A){let B=A*16;for(let X=0;X<16;++X)k[B+X]=h[A]+h[X]}return k})();function se(h){return typeof BigInt>"u"?Te:h}function Te(){throw new Error("BigInt not supported")}return vt}var Bt,di,Qt,hi,vt,fi,qc=Ke(()=>{le(),ue(),ce(),Bt={},di=!1,Qt={},hi=!1,vt={},fi=!1}),Fe={};Ut(Fe,{Buffer:()=>pr,INSPECT_MAX_BYTES:()=>ns,default:()=>dt,kMaxLength:()=>is});var dt,pr,ns,is,$e=Ke(()=>{le(),ue(),ce(),qc(),dt=$c(),dt.Buffer,dt.SlowBuffer,dt.INSPECT_MAX_BYTES,dt.kMaxLength,pr=dt.Buffer,ns=dt.INSPECT_MAX_BYTES,is=dt.kMaxLength}),ue=Ke(()=>{$e()}),je=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 i="";for(let n=0;n<r.length;n++)i+=` ${r[n].stack}
2
- `;super(i),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,i){return r.includes(i)},ArrayPrototypeIndexOf(r,i){return r.indexOf(i)},ArrayPrototypeJoin(r,i){return r.join(i)},ArrayPrototypeMap(r,i){return r.map(i)},ArrayPrototypePop(r,i){return r.pop(i)},ArrayPrototypePush(r,i){return r.push(i)},ArrayPrototypeSlice(r,i,n){return r.slice(i,n)},Error,FunctionPrototypeCall(r,i,...n){return r.call(i,...n)},FunctionPrototypeSymbolHasInstance(r,i){return Function.prototype[Symbol.hasInstance].call(r,i)},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,i){return Object.defineProperties(r,i)},ObjectDefineProperty(r,i,n){return Object.defineProperty(r,i,n)},ObjectGetOwnPropertyDescriptor(r,i){return Object.getOwnPropertyDescriptor(r,i)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,i){return Object.setPrototypeOf(r,i)},Promise,PromisePrototypeCatch(r,i){return r.catch(i)},PromisePrototypeThen(r,i,n){return r.then(i,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,i){return r.test(i)},SafeSet:Set,String,StringPrototypeSlice(r,i,n){return r.slice(i,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,i,n){return r.set(i,n)},Boolean,Uint8Array}}),os=pe((s,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[i,n]){let o=r.shift();return n==="f"?o.toFixed(6):n==="j"?JSON.stringify(o):n==="s"&&typeof o=="object"?`${o.constructor!==Object?o.constructor.name:""} {}`.trim():o.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"{}"}}}}),Ve=pe((s,e)=>{le(),ue(),ce();var{format:t,inspect:r}=os(),{AggregateError:i}=je(),n=globalThis.AggregateError||i,o=Symbol("kIsNodeError"),l=["string","function","number","object","Function","Object","boolean","bigint","symbol"],a=/^([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 g(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(g(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[o]=!0,u[m]=v}function y(m){let _=c+m.name;return Object.defineProperty(m,"name",{value:_}),m}function b(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=[],I=[];for(let O of _)d(typeof O=="string","All expected entries have to be of type string"),l.includes(O)?E.push(O.toLowerCase()):a.test(O)?S.push(O):(d(O!=="object",'The value "object" should be written as "Object"'),I.push(O));if(S.length>0){let O=E.indexOf("object");O!==-1&&(E.splice(E,O,1),S.push("Object"))}if(E.length>0){switch(E.length){case 1:v+=`of type ${E[0]}`;break;case 2:v+=`one of type ${E[0]} or ${E[1]}`;break;default:{let O=E.pop();v+=`one of type ${E.join(", ")}, or ${O}`}}(S.length>0||I.length>0)&&(v+=" or ")}if(S.length>0){switch(S.length){case 1:v+=`an instance of ${S[0]}`;break;case 2:v+=`an instance of ${S[0]} or ${S[1]}`;break;default:{let O=S.pop();v+=`an instance of ${S.join(", ")}, or ${O}`}}I.length>0&&(v+=" or ")}switch(I.length){case 0:break;case 1:I[0].toLowerCase()!==I[0]&&(v+="an "),v+=`${I[0]}`;break;case 2:v+=`one of ${I[0]} or ${I[1]}`;break;default:{let O=I.pop();v+=`one of ${I.join(", ")}, or ${O}`}}if(x==null)v+=`. Received ${x}`;else if(typeof x=="function"&&x.name)v+=`. Received function ${x.name}`;else if(typeof x=="object"){var P;if((P=x.constructor)!==null&&P!==void 0&&P.name)v+=`. Received an instance of ${x.constructor.name}`;else{let O=r(x,{depth:-1});v+=`. Received ${O}`}}else{let O=r(x,{colors:!1});O.length>25&&(O=`${O.slice(0,25)}...`),v+=`. Received type ${typeof x} (${O})`}return v},TypeError),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:y(b),hideStackFrames:y,codes:u}}),Xt=pe((s,e)=>{le(),ue(),ce();var{AbortController:t,AbortSignal:r}=typeof self<"u"?self:typeof window<"u"?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t}),wt={};Ut(wt,{EventEmitter:()=>ss,default:()=>Dt,defaultMaxListeners:()=>as,init:()=>ls,listenerCount:()=>cs,on:()=>us,once:()=>ds});function Hc(){if(pi)return Zt;pi=!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 i=Number.isNaN||function(x){return x!==x};function n(){n.init.call(this)}Zt=n,Zt.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var o=10;function l(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 o},set:function(x){if(typeof x!="number"||x<0||i(x))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+x+".");o=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||i(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 a(x){return x._maxListeners===void 0?n.defaultMaxListeners:x._maxListeners}n.prototype.getMaxListeners=function(){return a(this)},n.prototype.emit=function(x){for(var v=[],E=1;E<arguments.length;E++)v.push(arguments[E]);var S=x==="error",I=this._events;if(I!==void 0)S=S&&I.error===void 0;else if(!S)return!1;if(S){var P;if(v.length>0&&(P=v[0]),P instanceof Error)throw P;var O=new Error("Unhandled error."+(P?" ("+P.message+")":""));throw O.context=P,O}var j=I[x];if(j===void 0)return!1;if(typeof j=="function")e(j,this,v);else for(var T=j.length,q=f(j,T),E=0;E<T;++E)e(q[E],this,v);return!0};function c(x,v,E,S){var I,P,O;if(l(E),P=x._events,P===void 0?(P=x._events=Object.create(null),x._eventsCount=0):(P.newListener!==void 0&&(x.emit("newListener",v,E.listener?E.listener:E),P=x._events),O=P[v]),O===void 0)O=P[v]=E,++x._eventsCount;else if(typeof O=="function"?O=P[v]=S?[E,O]:[O,E]:S?O.unshift(E):O.push(E),I=a(x),I>0&&O.length>I&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=x,j.type=v,j.count=O.length,r(j)}return x}n.prototype.addListener=function(x,v){return c(this,x,v,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(x,v){return c(this,x,v,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(x,v,E){var S={fired:!1,wrapFn:void 0,target:x,type:v,listener:E},I=u.bind(S);return I.listener=E,S.wrapFn=I,I}n.prototype.once=function(x,v){return l(v),this.on(x,d(this,x,v)),this},n.prototype.prependOnceListener=function(x,v){return l(v),this.prependListener(x,d(this,x,v)),this},n.prototype.removeListener=function(x,v){var E,S,I,P,O;if(l(v),S=this._events,S===void 0)return this;if(E=S[x],E===void 0)return this;if(E===v||E.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete S[x],S.removeListener&&this.emit("removeListener",x,E.listener||v));else if(typeof E!="function"){for(I=-1,P=E.length-1;P>=0;P--)if(E[P]===v||E[P].listener===v){O=E[P].listener,I=P;break}if(I<0)return this;I===0?E.shift():y(E,I),E.length===1&&(S[x]=E[0]),S.removeListener!==void 0&&this.emit("removeListener",x,O||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(x){var v,E,S;if(E=this._events,E===void 0)return this;if(E.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):E[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete E[x]),this;if(arguments.length===0){var I=Object.keys(E),P;for(S=0;S<I.length;++S)P=I[S],P!=="removeListener"&&this.removeAllListeners(P);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=E[x],typeof v=="function")this.removeListener(x,v);else if(v!==void 0)for(S=v.length-1;S>=0;S--)this.removeListener(x,v[S]);return this};function 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?b(I):f(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):g.call(x,v)},n.prototype.listenerCount=g;function g(x){var v=this._events;if(v!==void 0){var E=v[x];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(x,v){for(var E=new Array(v),S=0;S<v;++S)E[S]=x[S];return E}function y(x,v){for(;v+1<x.length;v++)x[v]=x[v+1];x.pop()}function b(x){for(var v=new Array(x.length),E=0;E<v.length;++E)v[E]=x[E].listener||x[E];return v}function w(x,v){return new Promise(function(E,S){function I(O){x.removeListener(v,P),S(O)}function P(){typeof x.removeListener=="function"&&x.removeListener("error",I),E([].slice.call(arguments))}_(x,v,P,{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(P){S.once&&x.removeEventListener(v,I),E(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return Zt}var Zt,pi,Dt,ss,as,ls,cs,us,ds,Tt=Ke(()=>{le(),ue(),ce(),Zt={},pi=!1,Dt=Hc(),Dt.once,Dt.once=function(s,e){return new Promise((t,r)=>{function i(...o){n!==void 0&&s.removeListener("error",n),t(o)}let n;e!=="error"&&(n=o=>{s.removeListener(name,i),r(o)},s.once("error",n)),s.once(e,i)})},Dt.on=function(s,e){let t=[],r=[],i=null,n=!1,o={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(i){let u=Promise.reject(i);return i=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){s.removeListener(e,l),s.removeListener("error",a),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){i=c,s.removeListener(e,l),s.removeListener("error",a)},[Symbol.asyncIterator](){return this}};return s.on(e,l),s.on("error",a),o;function l(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function a(c){n=!0;let u=r.shift();u?u.reject(c):i=c,o.return()}},{EventEmitter:ss,defaultMaxListeners:as,init:ls,listenerCount:cs,on:us,once:ds}=Dt}),Ye=pe((s,e)=>{le(),ue(),ce();var t=($e(),Re(Fe)),{format:r,inspect:i}=os(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ve(),{kResistStopPropagation:o,AggregateError:l,SymbolDispose:a}=je(),c=globalThis.AbortSignal||Xt().AbortSignal,u=globalThis.AbortController||Xt().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,g=typeof p<"u"?function(b){return b instanceof p}:function(b){return!1},f=(b,w)=>{if(b!==void 0&&(b===null||typeof b!="object"||!("aborted"in b)))throw new n(w,"AbortSignal",b)},y=(b,w)=>{if(typeof b!="function")throw new n(w,"Function",b)};e.exports={AggregateError:l,kEmptyObject:Object.freeze({}),once(b){let w=!1;return function(...m){w||(w=!0,b.apply(this,m))}},createDeferredPromise:function(){let b,w;return{promise:new Promise((m,_)=>{b=m,w=_}),resolve:b,reject:w}},promisify(b){return new Promise((w,m)=>{b((_,...x)=>_?m(_):w(...x))})},debuglog(){return function(){}},format:r,inspect:i,types:{isAsyncFunction(b){return b instanceof d},isArrayBufferView(b){return ArrayBuffer.isView(b)}},isBlob:g,deprecate(b,w){return b},addAbortListener:(Tt(),Re(wt)).addAbortListener||function(b,w){if(b===void 0)throw new n("signal","AbortSignal",b);f(b,"signal"),y(w,"listener");let m;return b.aborted?queueMicrotask(()=>w()):(b.addEventListener("abort",w,{__proto__:null,once:!0,[o]:!0}),m=()=>{b.removeEventListener("abort",w)}),{__proto__:null,[a](){var _;(_=m)===null||_===void 0||_()}}},AbortSignalAny:c.any||function(b){if(b.length===1)return b[0];let w=new u,m=()=>w.abort();return b.forEach(_=>{f(_,"signals"),_.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{b.forEach(_=>_.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),er=pe((s,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:i,ArrayPrototypeMap:n,NumberIsInteger:o,NumberIsNaN:l,NumberMAX_SAFE_INTEGER:a,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:g,StringPrototypeToUpperCase:f,StringPrototypeTrim:y}=je(),{hideStackFrames:b,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:_,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ve(),{normalizeEncoding:E}=Ye(),{isAsyncFunction:S,isArrayBufferView:I}=Ye().types,P={};function O(H){return H===(H|0)}function j(H){return H===H>>>0}var T=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function D(H,me,ve){if(typeof H>"u"&&(H=ve),typeof H=="string"){if(p(T,H)===null)throw new _(me,H,q);H=u(H,8)}return Y(H,me),H}var U=b((H,me,ve=c,se=a)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),ae=b((H,me,ve=-2147483648,se=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),Y=b((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new x(me,"an integer",H);let se=ve?1:0,Te=4294967295;if(H<se||H>Te)throw new x(me,`>= ${se} && <= ${Te}`,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)&&l(H))throw new x(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&se!=null?" && ":""}${se!=null?`<= ${se}`:""}`,H)}var F=b((H,me,ve)=>{if(!r(ve,H)){let se="must be one of: "+i(n(ve,Te=>typeof Te=="string"?`'${Te}'`:g(Te)),", ");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||!d(H,me)?ve:H[me]}var Q=b((H,me,ve=null)=>{let se=M(ve,"allowArray",!1),Te=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!se&&t(H)||typeof H!="object"&&(!Te||typeof H!="function"))throw new m(me,"Object",H)}),ye=b((H,me)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(me,"a dictionary",H)}),te=b((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 G(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],Te=`${me}[${ve}]`;if(se==null)throw new m(Te,"AbortSignal",se);ge(se,Te)}}function ne(H,me="signal"){if(V(H,me),P[H]===void 0)throw P[f(H)]!==void 0?new v(H+" (signals must use all capital letters)"):new v(H)}var W=b((H,me="buffer")=>{if(!I(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function K(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"&&y(H).length===0||+H!==+H>>>0||H>65535||H===0&&!ve)throw new w(me,H,ve);return H|0}var ge=b((H,me)=>{if(H!==void 0&&(H===null||typeof H!="object"||!("aborted"in H)))throw new m(me,"AbortSignal",H)}),oe=b((H,me)=>{if(typeof H!="function")throw new m(me,"Function",H)}),R=b((H,me)=>{if(typeof H!="function"||S(H))throw new m(me,"Function",H)}),$=b((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,`('${i(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 be(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 Te=H[se];fe(Te,"hints"),ve+=Te,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:O,isUint32:j,parseFileMode:D,validateArray:te,validateStringArray:we,validateBooleanArray:G,validateAbortSignalArray:N,validateBoolean:Z,validateBuffer:W,validateDictionary:ye,validateEncoding:K,validateFunction:oe,validateInt32:ae,validateInteger:U,validateNumber:re,validateObject:Q,validateOneOf:F,validatePlainFunction:R,validatePort:J,validateSignalName:ne,validateString:V,validateUint32:Y,validateUndefined:$,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:be}}),Ct=pe((s,e)=>{le(),ue(),ce();var t=e.exports={},r,i;function n(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?r=setTimeout:r=n}catch{r=n}try{typeof clearTimeout=="function"?i=clearTimeout:i=o}catch{i=o}})();function l(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 a(w){if(i===clearTimeout)return clearTimeout(w);if((i===o||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(w);try{return i(w)}catch{try{return i.call(null,w)}catch{return i.call(this,w)}}}var c=[],u=!1,d,p=-1;function g(){!u||!d||(u=!1,d.length?c=d.concat(c):p=-1,c.length&&f())}function f(){if(!u){var w=l(g);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,a(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 y(w,m)),c.length===1&&!u&&l(f)};function y(w,m){this.fun=w,this.array=m}y.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function b(){}t.on=b,t.addListener=b,t.once=b,t.off=b,t.removeListener=b,t.removeAllListeners=b,t.emit=b,t.prependListener=b,t.prependOnceListener=b,t.listeners=function(w){return[]},t.binding=function(w){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(w){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),ht=pe((s,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:i}=je(),n=i("nodejs.stream.destroyed"),o=i("nodejs.stream.errored"),l=i("nodejs.stream.readable"),a=i("nodejs.stream.writable"),c=i("nodejs.stream.disturbed"),u=i("nodejs.webstream.isClosedPromise"),d=i("nodejs.webstream.controllerErrorFunction");function p(M,Q=!1){var ye;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!Q||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((ye=M._readableState)===null||ye===void 0?void 0:ye.readable)!==!1)&&(!M._writableState||M._readableState))}function g(M){var Q;return!!(M&&typeof M.write=="function"&&typeof M.on=="function"&&(!M._readableState||((Q=M._writableState)===null||Q===void 0?void 0:Q.writable)!==!1))}function f(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function y(M){return M&&(M._readableState||M._writableState||typeof M.write=="function"&&typeof M.on=="function"||typeof M.pipe=="function"&&typeof M.on=="function")}function b(M){return!!(M&&!y(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function w(M){return!!(M&&!y(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!y(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function _(M){return b(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(!y(M))return null;let Q=M._writableState,ye=M._readableState,te=Q||ye;return!!(M.destroyed||M[n]||te!=null&&te.destroyed)}function E(M){if(!g(M))return null;if(M.writableEnded===!0)return!0;let Q=M._writableState;return Q!=null&&Q.errored?!1:typeof Q?.ended!="boolean"?null:Q.ended}function S(M,Q){if(!g(M))return null;if(M.writableFinished===!0)return!0;let ye=M._writableState;return ye!=null&&ye.errored?!1:typeof ye?.finished!="boolean"?null:!!(ye.finished||Q===!1&&ye.ended===!0&&ye.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 P(M,Q){if(!p(M))return null;let ye=M._readableState;return ye!=null&&ye.errored?!1:typeof ye?.endEmitted!="boolean"?null:!!(ye.endEmitted||Q===!1&&ye.ended===!0&&ye.length===0)}function O(M){return M&&M[l]!=null?M[l]:typeof M?.readable!="boolean"?null:v(M)?!1:p(M)&&M.readable&&!P(M)}function j(M){return M&&M[a]!=null?M[a]:typeof M?.writable!="boolean"?null:v(M)?!1:g(M)&&M.writable&&!E(M)}function T(M,Q){return y(M)?v(M)?!0:!(Q?.readable!==!1&&O(M)||Q?.writable!==!1&&j(M)):null}function q(M){var Q,ye;return y(M)?M.writableErrored?M.writableErrored:(Q=(ye=M._writableState)===null||ye===void 0?void 0:ye.errored)!==null&&Q!==void 0?Q:null:null}function D(M){var Q,ye;return y(M)?M.readableErrored?M.readableErrored:(Q=(ye=M._readableState)===null||ye===void 0?void 0:ye.errored)!==null&&Q!==void 0?Q:null:null}function U(M){if(!y(M))return null;if(typeof M.closed=="boolean")return M.closed;let Q=M._writableState,ye=M._readableState;return typeof Q?.closed=="boolean"||typeof ye?.closed=="boolean"?Q?.closed||ye?.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(!y(M))return null;let Q=M._writableState,ye=M._readableState,te=Q||ye;return!te&&Y(M)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function F(M){var Q;return!!(M&&((Q=M[c])!==null&&Q!==void 0?Q:M.readableDidRead||M.readableAborted))}function Z(M){var Q,ye,te,we,G,N,ne,W,K,J;return!!(M&&((Q=(ye=(te=(we=(G=(N=M[o])!==null&&N!==void 0?N:M.readableErrored)!==null&&G!==void 0?G: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&&ye!==void 0?ye:(K=M._readableState)===null||K===void 0?void 0:K.errored)!==null&&Q!==void 0?Q:!((J=M._writableState)===null||J===void 0)&&J.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:F,kIsDisturbed:c,isErrored:Z,kIsErrored:o,isReadable:O,kIsReadable:l,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:a,isClosed:U,isDuplexNodeStream:f,isFinished:T,isIterable:x,isReadableNodeStream:p,isReadableStream:b,isReadableEnded:I,isReadableFinished:P,isReadableErrored:D,isNodeStream:y,isWebStream:_,isWritable:j,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:E,isWritableFinished:S,isWritableErrored:q,isServerRequest:V,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),_t=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{AbortError:r,codes:i}=Ve(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:o}=i,{kEmptyObject:l,once:a}=Ye(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:p}=er(),{Promise:g,PromisePrototypeThen:f,SymbolDispose:y}=je(),{isClosed:b,isReadable:w,isReadableNodeStream:m,isReadableStream:_,isReadableFinished:x,isReadableErrored:v,isWritable:E,isWritableNodeStream:S,isWritableStream:I,isWritableFinished:P,isWritableErrored:O,isNodeStream:j,willEmitClose:T,kIsClosedPromise:q}=ht(),D;function U(F){return F.setHeader&&typeof F.abort=="function"}var ae=()=>{};function Y(F,Z,M){var Q,ye;if(arguments.length===2?(M=Z,Z=l):Z==null?Z=l:d(Z,"options"),u(M,"callback"),c(Z.signal,"options.signal"),M=a(M),_(F)||I(F))return V(F,Z,M);if(!j(F))throw new n("stream",["ReadableStream","WritableStream","Stream"],F);let te=(Q=Z.readable)!==null&&Q!==void 0?Q:m(F),we=(ye=Z.writable)!==null&&ye!==void 0?ye:S(F),G=F._writableState,N=F._readableState,ne=()=>{F.writable||J()},W=T(F)&&m(F)===te&&S(F)===we,K=P(F,!1),J=()=>{K=!0,F.destroyed&&(W=!1),!(W&&(!F.readable||te))&&(!te||ge)&&M.call(F)},ge=x(F,!1),oe=()=>{ge=!0,F.destroyed&&(W=!1),!(W&&(!F.writable||we))&&(!we||K)&&M.call(F)},R=H=>{M.call(F,H)},$=b(F),ee=()=>{$=!0;let H=O(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);if(te&&!ge&&m(F,!0)&&!x(F,!1))return M.call(F,new o);if(we&&!K&&!P(F,!1))return M.call(F,new o);M.call(F)},he=()=>{$=!0;let H=O(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);M.call(F)},fe=()=>{F.req.on("finish",J)};U(F)?(F.on("complete",J),W||F.on("abort",ee),F.req?fe():F.on("request",fe)):we&&!G&&(F.on("end",ne),F.on("close",ne)),!W&&typeof F.aborted=="boolean"&&F.on("aborted",ee),F.on("end",oe),F.on("finish",J),Z.error!==!1&&F.on("error",R),F.on("close",ee),$?t.nextTick(ee):G!=null&&G.errorEmitted||N!=null&&N.errorEmitted?W||t.nextTick(he):(!te&&(!W||w(F))&&(K||E(F)===!1)||!we&&(!W||E(F))&&(ge||w(F)===!1)||N&&F.req&&F.aborted)&&t.nextTick(he);let be=()=>{M=ae,F.removeListener("aborted",ee),F.removeListener("complete",J),F.removeListener("abort",ee),F.removeListener("request",fe),F.req&&F.req.removeListener("finish",J),F.removeListener("end",ne),F.removeListener("close",ne),F.removeListener("finish",J),F.removeListener("end",oe),F.removeListener("error",R),F.removeListener("close",ee)};if(Z.signal&&!$){let H=()=>{let me=M;be(),me.call(F,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=a((...se)=>{me[y](),ve.apply(F,se)})}}return be}function V(F,Z,M){let Q=!1,ye=ae;if(Z.signal)if(ye=()=>{Q=!0,M.call(F,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(ye);else{D=D||Ye().addAbortListener;let we=D(Z.signal,ye),G=M;M=a((...N)=>{we[y](),G.apply(F,N)})}let te=(...we)=>{Q||t.nextTick(()=>M.apply(F,we))};return f(F[q].promise,te,te),ae}function re(F,Z){var M;let Q=!1;return Z===null&&(Z=l),(M=Z)!==null&&M!==void 0&&M.cleanup&&(p(Z.cleanup,"cleanup"),Q=Z.cleanup),new g((ye,te)=>{let we=Y(F,Z,G=>{Q&&we(),G?te(G):ye()})})}e.exports=Y,e.exports.finished=re}),Ft=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:i},AbortError:n}=Ve(),{Symbol:o}=je(),{kIsDestroyed:l,isDestroyed:a,isFinished:c,isServerRequest:u}=ht(),d=o("kDestroy"),p=o("kConstruct");function g(T,q,D){T&&(T.stack,q&&!q.errored&&(q.errored=T),D&&!D.errored&&(D.errored=T))}function f(T,q){let D=this._readableState,U=this._writableState,ae=U||D;return U!=null&&U.destroyed||D!=null&&D.destroyed?(typeof q=="function"&&q(),this):(g(T,U,D),U&&(U.destroyed=!0),D&&(D.destroyed=!0),ae.constructed?y(this,T,q):this.once(d,function(Y){y(this,r(Y,T),q)}),this)}function y(T,q,D){let U=!1;function ae(Y){if(U)return;U=!0;let V=T._readableState,re=T._writableState;g(Y,re,V),re&&(re.closed=!0),V&&(V.closed=!0),typeof D=="function"&&D(Y),Y?t.nextTick(b,T,Y):t.nextTick(w,T)}try{T._destroy(q||null,ae)}catch(Y){ae(Y)}}function b(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 i);return}q=!0;let ae=T._readableState,Y=T._writableState,V=Y||ae;ae&&(ae.constructed=!0),Y&&(Y.constructed=!0),V.destroyed?T.emit(d,U):U?x(T,U,!0):t.nextTick(S,T)}try{T._construct(U=>{t.nextTick(D,U)})}catch(U){t.nextTick(D,U)}}function S(T){T.emit(p)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function P(T){T.emit("close")}function O(T,q){T.emit("error",q),t.nextTick(P,T)}function j(T,q){!T||a(T)||(!q&&!c(T)&&(q=new n),u(T)?(T.socket=null,T.destroy(q)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(q):typeof T.close=="function"?T.close():q?t.nextTick(O,T,q):t.nextTick(P,T),T.destroyed||(T[l]=!0))}e.exports={construct:v,destroyer:j,destroy:f,undestroy:_,errorOrDestroy:x}}),mi=pe((s,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=je(),{EventEmitter:i}=(Tt(),Re(wt));function n(l){i.call(this,l)}r(n.prototype,i.prototype),r(n,i),n.prototype.pipe=function(l,a){let c=this;function u(w){l.writable&&l.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function d(){c.readable&&c.resume&&c.resume()}l.on("drain",d),!l._isStdio&&(!a||a.end!==!1)&&(c.on("end",g),c.on("close",f));let p=!1;function g(){p||(p=!0,l.end())}function f(){p||(p=!0,typeof l.destroy=="function"&&l.destroy())}function y(w){b(),i.listenerCount(this,"error")===0&&this.emit("error",w)}o(c,"error",y),o(l,"error",y);function b(){c.removeListener("data",u),l.removeListener("drain",d),c.removeListener("end",g),c.removeListener("close",f),c.removeListener("error",y),l.removeListener("error",y),c.removeListener("end",b),c.removeListener("close",b),l.removeListener("close",b)}return c.on("end",b),c.on("close",b),l.on("close",b),l.emit("pipe",c),l};function o(l,a,c){if(typeof l.prependListener=="function")return l.prependListener(a,c);!l._events||!l._events[a]?l.on(a,c):t(l._events[a])?l._events[a].unshift(c):l._events[a]=[c,l._events[a]]}e.exports={Stream:n,prependListener:o}}),mr=pe((s,e)=>{le(),ue(),ce();var{SymbolDispose:t}=je(),{AbortError:r,codes:i}=Ve(),{isNodeStream:n,isWebStream:o,kControllerErrorFunction:l}=ht(),a=_t(),{ERR_INVALID_ARG_TYPE:c}=i,u,d=(p,g)=>{if(typeof p!="object"||!("aborted"in p))throw new c(g,"AbortSignal",p)};e.exports.addAbortSignal=function(p,g){if(d(p,"signal"),!n(g)&&!o(g))throw new c("stream",["ReadableStream","WritableStream","Stream"],g);return e.exports.addAbortSignalNoValidate(p,g)},e.exports.addAbortSignalNoValidate=function(p,g){if(typeof p!="object"||!("aborted"in p))return g;let f=n(g)?()=>{g.destroy(new r(void 0,{cause:p.reason}))}:()=>{g[l](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||Ye().addAbortListener;let y=u(p,f);a(g,y[t])}return g}}),Wc=pe((s,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:i,Uint8Array:n}=je(),{Buffer:o}=($e(),Re(Fe)),{inspect:l}=Ye();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(a){let c={data:a,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(a){let c={data:a,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let a=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,a}clear(){this.head=this.tail=null,this.length=0}join(a){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=a+c.data;return u}concat(a){if(this.length===0)return o.alloc(0);let c=o.allocUnsafe(a>>>0),u=this.head,d=0;for(;u;)i(c,u.data,d),d+=u.data.length,u=u.next;return c}consume(a,c){let u=this.head.data;if(a<u.length){let d=u.slice(0,a);return this.head.data=u.slice(a),d}return a===u.length?this.shift():c?this._getString(a):this._getBuffer(a)}first(){return this.head.data}*[r](){for(let a=this.head;a;a=a.next)yield a.data}_getString(a){let c="",u=this.head,d=0;do{let p=u.data;if(a>p.length)c+=p,a-=p.length;else{a===p.length?(c+=p,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,a),this.head=u,u.data=t(p,a));break}++d}while((u=u.next)!==null);return this.length-=d,c}_getBuffer(a){let c=o.allocUnsafe(a),u=a,d=this.head,p=0;do{let g=d.data;if(a>g.length)i(c,g,u-a),a-=g.length;else{a===g.length?(i(c,g,u-a),++p,d.next?this.head=d.next:this.head=this.tail=null):(i(c,new n(g.buffer,g.byteOffset,a),u-a),this.head=d,d.data=g.slice(a));break}++p}while((d=d.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](a,c){return l(this,{...c,depth:0,customInspect:!1})}}}),gr=pe((s,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=je(),{validateInteger:i}=er(),{ERR_INVALID_ARG_VALUE:n}=Ve().codes,o=16*1024,l=16;function a(p,g,f){return p.highWaterMark!=null?p.highWaterMark:g?p[f]:null}function c(p){return p?l:o}function u(p,g){i(g,"value",0),p?l=g:o=g}function d(p,g,f,y){let b=a(g,y,f);if(b!=null){if(!r(b)||b<0){let w=y?`options.${f}`:"options.highWaterMark";throw new n(w,b)}return t(b)}return c(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),zc=pe((s,e)=>{le(),ue(),ce();var t=($e(),Re(Fe)),r=t.Buffer;function i(o,l){for(var a in o)l[a]=o[a]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(i(t,s),s.Buffer=n);function n(o,l,a){return r(o,l,a)}n.prototype=Object.create(r.prototype),i(r,n),n.from=function(o,l,a){if(typeof o=="number")throw new TypeError("Argument must not be a number");return r(o,l,a)},n.alloc=function(o,l,a){if(typeof o!="number")throw new TypeError("Argument must be a number");var c=r(o);return l!==void 0?typeof a=="string"?c.fill(l,a):c.fill(l):c.fill(0),c},n.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r(o)},n.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(o)}}),Vc=pe(s=>{le(),ue(),ce();var e=zc().Buffer,t=e.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(m){if(!m)return"utf8";for(var _;;)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 i(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=i(m);var _;switch(this.encoding){case"utf16le":this.text=p,this.end=g,_=4;break;case"utf8":this.fillLast=c,_=4;break;case"base64":this.text=f,this.end=y,_=3;break;default:this.write=b,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 o(m){return m<=127?0:m>>5===6?2:m>>4===14?3:m>>3===30?4:m>>6===2?-1:-2}function l(m,_,x){var v=_.length-1;if(v<x)return 0;var E=o(_[v]);return E>=0?(E>0&&(m.lastNeed=E-1),E):--v<x||E===-2?0:(E=o(_[v]),E>=0?(E>0&&(m.lastNeed=E-2),E):--v<x||E===-2?0:(E=o(_[v]),E>=0?(E>0&&(E===2?E=0:m.lastNeed=E-3),E):0))}function a(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=a(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=l(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 g(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 y(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+this.lastChar.toString("base64",0,3-this.lastNeed):_}function b(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),hs=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{PromisePrototypeThen:r,SymbolAsyncIterator:i,SymbolIterator:n}=je(),{Buffer:o}=($e(),Re(Fe)),{ERR_INVALID_ARG_TYPE:l,ERR_STREAM_NULL_VALUES:a}=Ve().codes;function c(u,d,p){let g;if(typeof d=="string"||d instanceof o)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let f;if(d&&d[i])f=!0,g=d[i]();else if(d&&d[n])f=!1,g=d[n]();else throw new l("iterable",["Iterable"],d);let y=new u({objectMode:!0,highWaterMark:1,...p}),b=!1;y._read=function(){b||(b=!0,m())},y._destroy=function(_,x){r(w(_),()=>t.nextTick(x,_),v=>t.nextTick(x,v||_))};async function w(_){let x=_!=null,v=typeof g.throw=="function";if(x&&v){let{value:E,done:S}=await g.throw(_);if(await E,S)return}if(typeof g.return=="function"){let{value:E}=await g.return();await E}}async function m(){for(;;){try{let{value:_,done:x}=f?await g.next():g.next();if(x)y.push(null);else{let v=_&&typeof _.then=="function"?await _:_;if(v===null)throw b=!1,new a;if(y.push(v))continue;b=!1}}catch(_){y.destroy(_)}break}}return y}e.exports=c}),yr=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{ArrayPrototypeIndexOf:r,NumberIsInteger:i,NumberIsNaN:n,NumberParseInt:o,ObjectDefineProperties:l,ObjectKeys:a,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:g,Symbol:f}=je();e.exports=se,se.ReadableState=ve;var{EventEmitter:y}=(Tt(),Re(wt)),{Stream:b,prependListener:w}=mi(),{Buffer:m}=($e(),Re(Fe)),{addAbortSignal:_}=mr(),x=_t(),v=Ye().debuglog("stream",C=>{v=C}),E=Wc(),S=Ft(),{getHighWaterMark:I,getDefaultHighWaterMark:P}=gr(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:j,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:q,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:ae}=Ve(),{validateObject:Y}=er(),V=f("kPaused"),{StringDecoder:re}=Vc(),F=hs();c(se.prototype,b.prototype),c(se,b);var Z=()=>{},{errorOrDestroy:M}=S,Q=1,ye=2,te=4,we=8,G=16,N=32,ne=64,W=128,K=256,J=512,ge=1024,oe=2048,R=4096,$=8192,ee=16384,he=32768,fe=65536,be=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}}}l(ve.prototype,{objectMode:me(Q),ended:me(ye),endEmitted:me(te),reading:me(we),constructed:me(G),sync:me(N),needReadable:me(ne),emittedReadable:me(W),readableListening:me(K),resumeScheduled:me(J),errorEmitted:me(ge),emitClose:me(oe),autoDestroy:me(R),destroyed:me($),closed:me(ee),closeEmitted:me(he),multiAwaitDrain:me(fe),readingMore:me(be),dataEmitted:me(H)});function ve(C,L,_e){typeof _e!="boolean"&&(_e=L instanceof ft()),this.state=oe|R|G|N,C&&C.objectMode&&(this.state|=Q),_e&&C&&C.readableObjectMode&&(this.state|=Q),this.highWaterMark=C?I(this,C,"readableHighWaterMark",_e):P(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[V]=null,C&&C.emitClose===!1&&(this.state&=~oe),C&&C.autoDestroy===!1&&(this.state&=~R),this.errored=null,this.defaultEncoding=C&&C.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,C&&C.encoding&&(this.decoder=new re(C.encoding),this.encoding=C.encoding)}function se(C){if(!(this instanceof se))return new se(C);let L=this instanceof ft();this._readableState=new ve(C,this,L),C&&(typeof C.read=="function"&&(this._read=C.read),typeof C.destroy=="function"&&(this._destroy=C.destroy),typeof C.construct=="function"&&(this._construct=C.construct),C.signal&&!L&&_(C.signal,this)),b.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[y.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 Te(this,C,L,!1)},se.prototype.unshift=function(C,L){return Te(this,C,L,!0)};function Te(C,L,_e,xe){v("readableAddChunk",L);let Se=C._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="":b._isUint8Array(L)?(L=b._uint8ArrayToBuffer(L),_e=""):L!=null&&(De=new j("chunk",["string","Buffer","Uint8Array"],L))),De)M(C,De);else if(L===null)Se.state&=~we,X(C,Se);else if((Se.state&Q)!==0||L&&L.length>0)if(xe)if((Se.state&te)!==0)M(C,new U);else{if(Se.destroyed||Se.errored)return!1;h(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?h(C,Se,L,!1):z(C,Se)):h(C,Se,L,!1)}else xe||(Se.state&=~we,z(C,Se));return!Se.ended&&(Se.length<Se.highWaterMark||Se.length===0)}function h(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&&de(C)),z(C,L)}se.prototype.isPaused=function(){let C=this._readableState;return C[V]===!0||C.flowing===!1},se.prototype.setEncoding=function(C){let L=new re(C);this._readableState.decoder=L,this._readableState.encoding=this._readableState.decoder.encoding;let _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:i(C)||(C=o(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?st(this):de(this),null;if(C=B(C,L),C===0&&L.ended)return L.length===0&&st(this),null;let xe=(L.state&ne)!==0;if(v("need readable",xe),(L.length===0||L.length-C<L.highWaterMark)&&(xe=!0,v("length less than watermark",xe)),L.ended||L.reading||L.destroyed||L.errored||!L.constructed)xe=!1,v("reading, ended or constructing",xe);else if(xe){v("do read"),L.state|=we|N,L.length===0&&(L.state|=ne);try{this._read(L.highWaterMark)}catch(De){M(this,De)}L.state&=~N,L.reading||(C=B(_e,L))}let Se;return C>0?Se=Gt(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&&st(this)),Se!==null&&!L.errorEmitted&&!L.closeEmitted&&(L.dataEmitted=!0,this.emit("data",Se)),Se};function X(C,L){if(v("onEofChunk"),!L.ended){if(L.decoder){let _e=L.decoder.end();_e&&_e.length&&(L.buffer.push(_e),L.length+=L.objectMode?1:_e.length)}L.ended=!0,L.sync?de(C):(L.needReadable=!1,L.emittedReadable=!0,ke(C))}}function de(C){let L=C._readableState;v("emitReadable",L.needReadable,L.emittedReadable),L.needReadable=!1,L.emittedReadable||(v("emitReadable",L.flowing),L.emittedReadable=!0,t.nextTick(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,it(C)}function z(C,L){!L.readingMore&&L.constructed&&(L.readingMore=!0,t.nextTick(ie,C,L))}function ie(C,L){for(;!L.reading&&!L.ended&&(L.length<L.highWaterMark||L.flowing&&L.length===0);){let _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 d(xe.awaitDrainWriters?[xe.awaitDrainWriters]:[]))),xe.pipes.push(C),v("pipe count=%d opts=%j",xe.pipes.length,L);let Se=(!L||L.end!==!1)&&C!==t.stdout&&C!==t.stderr?Ge:jt;xe.endEmitted?t.nextTick(Se):_e.once("end",Se),C.on("unpipe",De);function De(lt,bt){v("onunpipe"),lt===_e&&bt&&bt.hasUnpiped===!1&&(bt.hasUnpiped=!0,ar())}function Ge(){v("onend"),C.end()}let et,sr=!1;function ar(){v("cleanup"),C.removeListener("close",at),C.removeListener("finish",Et),et&&C.removeListener("drain",et),C.removeListener("error",Nt),C.removeListener("unpipe",De),_e.removeListener("end",Ge),_e.removeListener("end",jt),_e.removeListener("data",Zr),sr=!0,et&&xe.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&et()}function lr(){sr||(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()),et||(et=Ee(_e,C),C.on("drain",et))}_e.on("data",Zr);function Zr(lt){v("ondata");let bt=C.write(lt);v("dest.write",bt),bt===!1&&lr()}function Nt(lt){if(v("onerror",lt),jt(),C.removeListener("error",Nt),C.listenerCount("error")===0){let bt=C._writableState||C._readableState;bt&&!bt.errorEmitted?M(C,lt):C.emit("error",lt)}}w(C,"error",Nt);function at(){C.removeListener("finish",Et),jt()}C.once("close",at);function Et(){v("onfinish"),C.removeListener("close",at),jt()}C.once("finish",Et);function jt(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?lr():xe.flowing||(v("pipe resume"),_e.resume()),C};function Ee(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 De=0;De<Se.length;De++)Se[De].emit("unpipe",this,{hasUnpiped:!1});return this}let xe=r(L.pipes,C);return xe===-1?this:(L.pipes.splice(xe,1),L.pipes.length===0&&this.pause(),C.emit("unpipe",this,_e),this)},se.prototype.on=function(C,L){let _e=b.prototype.on.call(this,C,L),xe=this._readableState;return C==="data"?(xe.readableListening=this.listenerCount("readable")>0,xe.flowing!==!1&&this.resume()):C==="readable"&&!xe.endEmitted&&!xe.readableListening&&(xe.readableListening=xe.needReadable=!0,xe.flowing=!1,xe.emittedReadable=!1,v("on readable",xe.length,xe.reading),xe.length?de(this):xe.reading||t.nextTick(Ie,this)),_e},se.prototype.addListener=se.prototype.on,se.prototype.removeListener=function(C,L){let _e=b.prototype.removeListener.call(this,C,L);return C==="readable"&&t.nextTick(Ae,this),_e},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(C){let L=b.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Ae,this),L};function Ae(C){let L=C._readableState;L.readableListening=C.listenerCount("readable")>0,L.resumeScheduled&&L[V]===!1?L.flowing=!0:C.listenerCount("data")>0?C.resume():L.readableListening||(L.flowing=null)}function Ie(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(nt,C,L))}function nt(C,L){v("resume",L.reading),L.reading||C.read(0),L.resumeScheduled=!1,C.emit("resume"),it(C),L.flowing&&!L.reading&&C.read(0)}se.prototype.pause=function(){return v("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(v("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[V]=!0,this};function it(C){let L=C._readableState;for(v("flow",L.flowing);L.flowing&&C.read()!==null;);}se.prototype.wrap=function(C){let L=!1;C.on("data",xe=>{!this.push(xe)&&C.pause&&(L=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",xe=>{M(this,xe)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{L&&C.resume&&(L=!1,C.resume())};let _e=a(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[g]=function(){return ze(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),ze(this,C)};function ze(C,L){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let _e=ot(C,L);return _e.stream=C,_e}async function*ot(C,L){let _e=Z;function xe(Ge){this===C?(_e(),_e=Z):_e=Ge}C.on("readable",xe);let Se,De=x(C,{writable:!1},Ge=>{Se=Ge?O(Se,Ge):null,_e(),_e=Z});try{for(;;){let Ge=C.destroyed?null:C.read();if(Ge!==null)yield Ge;else{if(Se)throw Se;if(Se===null)return;await new u(xe)}}}catch(Ge){throw Se=O(Se,Ge),Se}finally{(Se||L?.destroyOnReturn!==!1)&&(Se===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",xe),De())}}l(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}}}),l(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=Gt;function Gt(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 st(C){let L=C._readableState;v("endReadable",L.endEmitted),L.endEmitted||(L.ended=!0,t.nextTick(Xe,L,C))}function Xe(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(Xr,L);else if(C.autoDestroy){let _e=L._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&L.destroy()}}}function Xr(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,L){return F(se,C,L)};var Kt;function or(){return Kt===void 0&&(Kt={}),Kt}se.fromWeb=function(C,L){return or().newStreamReadableFromReadableStream(C,L)},se.toWeb=function(C,L){return or().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,De){S.destroyer(C,Se),De(Se)}}).wrap(C)}}),gi=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{ArrayPrototypeSlice:r,Error:i,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:o,ObjectDefineProperties:l,ObjectSetPrototypeOf:a,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=je();e.exports=Y,Y.WritableState=U;var{EventEmitter:p}=(Tt(),Re(wt)),g=mi().Stream,{Buffer:f}=($e(),Re(Fe)),y=Ft(),{addAbortSignal:b}=mr(),{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:P,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:j}=Ve().codes,{errorOrDestroy:T}=y;a(Y.prototype,g.prototype),a(Y,g);function q(){}var D=u("kOnFinished");function U(R,$,ee){typeof ee!="boolean"&&(ee=$ 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,$),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)},o(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Y(R){let $=this instanceof ft();if(!$&&!n(Y,this))return new Y(R);this._writableState=new U(R,this,$),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&&b(R.signal,this)),g.call(this,R),y.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),W(this,ee)})}o(Y,d,{__proto__:null,value:function(R){return n(this,R)?!0:this!==Y?!1:R&&R._writableState instanceof U}}),Y.prototype.pipe=function(){T(this,new E)};function V(R,$,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=q)}if($===null)throw new P;if(!fe.objectMode)if(typeof $=="string")fe.decodeStrings!==!1&&($=f.from($,ee),ee="buffer");else if($ instanceof f)ee="buffer";else if(g._isUint8Array($))$=g._uint8ArrayToBuffer($),ee="buffer";else throw new _("chunk",["string","Buffer","Uint8Array"],$);let be;return fe.ending?be=new O:fe.destroyed&&(be=new S("write")),be?(t.nextTick(he,be),T(R,be,!0),be):(fe.pendingcb++,re(R,fe,$,ee,he))}Y.prototype.write=function(R,$,ee){return V(this,R,$,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,$,ee,he,fe){let be=$.objectMode?1:ee.length;$.length+=be;let H=$.length<$.highWaterMark;return H||($.needDrain=!0),$.writing||$.corked||$.errored||!$.constructed?($.buffered.push({chunk:ee,encoding:he,callback:fe}),$.allBuffers&&he!=="buffer"&&($.allBuffers=!1),$.allNoop&&fe!==q&&($.allNoop=!1)):($.writelen=be,$.writecb=fe,$.writing=!0,$.sync=!0,R._write(ee,he,$.onwrite),$.sync=!1),H&&!$.errored&&!$.destroyed}function F(R,$,ee,he,fe,be,H){$.writelen=he,$.writecb=H,$.writing=!0,$.sync=!0,$.destroyed?$.onwrite(new S("write")):ee?R._writev(fe,$.onwrite):R._write(fe,be,$.onwrite),$.sync=!1}function Z(R,$,ee,he){--$.pendingcb,he(ee),te($),T(R,ee)}function M(R,$){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,$?($.stack,ee.errored||(ee.errored=$),R._readableState&&!R._readableState.errored&&(R._readableState.errored=$),he?t.nextTick(Z,R,ee,$,fe):Z(R,ee,$,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)):ye(R,ee,1,fe))}function Q({stream:R,state:$,count:ee,cb:he}){return $.afterWriteTickInfo=null,ye(R,$,ee,he)}function ye(R,$,ee,he){for(!$.ending&&!R.destroyed&&$.length===0&&$.needDrain&&($.needDrain=!1,R.emit("drain"));ee-- >0;)$.pendingcb--,he();$.destroyed&&te($),W(R,$)}function te(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var $;let{chunk:be,callback:H}=R.buffered[fe],me=R.objectMode?1:be.length;R.length-=me,H(($=R.errored)!==null&&$!==void 0?$:new S("write"))}let ee=R[D].splice(0);for(let fe=0;fe<ee.length;fe++){var he;ee[fe]((he=R.errored)!==null&&he!==void 0?he:new S("end"))}ae(R)}function we(R,$){if($.corked||$.bufferProcessing||$.destroyed||!$.constructed)return;let{buffered:ee,bufferedIndex:he,objectMode:fe}=$,be=ee.length-he;if(!be)return;let H=he;if($.bufferProcessing=!0,be>1&&R._writev){$.pendingcb-=be-1;let me=$.allNoop?q:se=>{for(let Te=H;Te<ee.length;++Te)ee[Te].callback(se)},ve=$.allNoop&&H===0?ee:r(ee,H);ve.allBuffers=$.allBuffers,F(R,$,!0,$.length,ve,"",me),ae($)}else{do{let{chunk:me,encoding:ve,callback:se}=ee[H];ee[H++]=null;let Te=fe?1:me.length;F(R,$,!1,Te,me,ve,se)}while(H<ee.length&&!$.writing);H===ee.length?ae($):H>256?(ee.splice(0,H),$.bufferedIndex=0):$.bufferedIndex=H}$.bufferProcessing=!1}Y.prototype._write=function(R,$,ee){if(this._writev)this._writev([{chunk:R,encoding:$}],ee);else throw new x("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,$,ee){let he=this._writableState;typeof R=="function"?(ee=R,R=null,$=null):typeof $=="function"&&(ee=$,$=null);let fe;if(R!=null){let be=V(this,R,$);be instanceof i&&(fe=be)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,W(this,he,!0),he.ended=!0):he.finished?fe=new I("end"):he.destroyed&&(fe=new S("end"))),typeof ee=="function"&&(fe||he.finished?t.nextTick(ee,fe):he[D].push(ee)),this};function G(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,$){let ee=!1;function he(fe){if(ee){T(R,fe??v());return}if(ee=!0,$.pendingcb--,fe){let be=$[D].splice(0);for(let H=0;H<be.length;H++)be[H](fe);T(R,fe,$.sync)}else G($)&&($.prefinished=!0,R.emit("prefinish"),$.pendingcb++,t.nextTick(K,R,$))}$.sync=!0,$.pendingcb++;try{R._final(he)}catch(fe){he(fe)}$.sync=!1}function ne(R,$){!$.prefinished&&!$.finalCalled&&(typeof R._final=="function"&&!$.destroyed?($.finalCalled=!0,N(R,$)):($.prefinished=!0,R.emit("prefinish")))}function W(R,$,ee){G($)&&(ne(R,$),$.pendingcb===0&&(ee?($.pendingcb++,t.nextTick((he,fe)=>{G(fe)?K(he,fe):fe.pendingcb--},R,$)):G($)&&($.pendingcb++,K(R,$))))}function K(R,$){$.pendingcb--,$.finished=!0;let ee=$[D].splice(0);for(let he=0;he<ee.length;he++)ee[he]();if(R.emit("finish"),$.autoDestroy){let he=R._readableState;(!he||he.autoDestroy&&(he.endEmitted||he.readable===!1))&&R.destroy()}}l(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=y.destroy;Y.prototype.destroy=function(R,$){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[D].length)&&t.nextTick(te,ee),J.call(this,R,$),this},Y.prototype._undestroy=y.undestroy,Y.prototype._destroy=function(R,$){$(R)},Y.prototype[p.captureRejectionSymbol]=function(R){this.destroy(R)};var ge;function oe(){return ge===void 0&&(ge={}),ge}Y.fromWeb=function(R,$){return oe().newStreamWritableFromWritableStream(R,$)},Y.toWeb=function(R){return oe().newWritableStreamFromStreamWritable(R)}}),Gc=pe((s,e)=>{le(),ue(),ce();var t=Ct(),r=($e(),Re(Fe)),{isReadable:i,isWritable:n,isIterable:o,isNodeStream:l,isReadableNodeStream:a,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=ht(),g=_t(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:y,ERR_INVALID_RETURN_VALUE:b}}=Ve(),{destroyer:w}=Ft(),m=ft(),_=yr(),x=gi(),{createDeferredPromise:v}=Ye(),E=hs(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},P=globalThis.AbortController||Xt().AbortController,{FunctionPrototypeCall:O}=je(),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(a(U))return q({readable:U});if(c(U))return q({writable:U});if(l(U))return q({writable:!1,readable:!1});if(d(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:F,destroy:Z}=T(U);if(o(V))return E(j,V,{objectMode:!0,write:re,final:F,destroy:Z});let M=V?.then;if(typeof M=="function"){let Q,ye=O(M,V,te=>{if(te!=null)throw new b("nully","body",te)},te=>{w(Q,te)});return Q=new j({objectMode:!0,readable:!1,write:re,final(te){F(async()=>{try{await ye,t.nextTick(te,null)}catch(we){t.nextTick(te,we)}})},destroy:Z})}throw new b("Iterable, AsyncIterable or AsyncFunction",ae,V)}if(I(U))return D(U.arrayBuffer());if(o(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 V=U!=null&&U.readable?a(U?.readable)?U?.readable:D(U.readable):void 0,re=U!=null&&U.writable?c(U?.writable)?U?.writable:D(U.writable):void 0;return q({readable:V,writable:re})}let Y=U?.then;if(typeof Y=="function"){let V;return O(Y,U,re=>{re!=null&&V.push(re),V.push(null)},re=>{w(V,re)}),V=new j({objectMode:!0,writable:!1,read(){}})}throw new y(ae,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(D){let{promise:U,resolve:ae}=v(),Y=new P,V=Y.signal;return{value:D((async function*(){for(;;){let re=U;U=null;let{chunk:F,done:Z,cb:M}=await re;if(t.nextTick(M),Z)return;if(V.aborted)throw new f(void 0,{cause:V.reason});({promise:U,resolve:ae}=v()),yield F}})(),{signal:V}),write(re,F,Z){let M=ae;ae=null,M({chunk:re,done:!1,cb:Z})},final(re){let F=ae;ae=null,F({done:!0,cb:re})},destroy(re,F){Y.abort(),F(re)}}}function q(D){let U=D.readable&&typeof D.readable.read!="function"?_.wrap(D.readable):D.readable,ae=D.writable,Y=!!i(U),V=!!n(ae),re,F,Z,M,Q;function ye(te){let we=M;M=null,we?we(te):te&&Q.destroy(te)}return Q=new j({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(ae!=null&&ae.writableObjectMode),readable:Y,writable:V}),V&&(g(ae,te=>{V=!1,te&&w(U,te),ye(te)}),Q._write=function(te,we,G){ae.write(te,we)?G():re=G},Q._final=function(te){ae.end(),F=te},ae.on("drain",function(){if(re){let te=re;re=null,te()}}),ae.on("finish",function(){if(F){let te=F;F=null,te()}})),Y&&(g(U,te=>{Y=!1,te&&w(U,te),ye(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,F=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:i,ObjectSetPrototypeOf:n}=je();e.exports=a;var o=yr(),l=gi();n(a.prototype,o.prototype),n(a,o);{let p=i(l.prototype);for(let g=0;g<p.length;g++){let f=p[g];a.prototype[f]||(a.prototype[f]=l.prototype[f])}}function a(p){if(!(this instanceof a))return new a(p);o.call(this,p),l.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(a.prototype,{writable:{__proto__:null,...r(l.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(l.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(l.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(l.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(l.prototype,"writableLength")},writableFinished:{__proto__:null,...r(l.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(l.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(l.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(l.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}a.fromWeb=function(p,g){return u().newStreamDuplexFromReadableWritablePair(p,g)},a.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var d;a.from=function(p){return d||(d=Gc()),d(p,"body")}}),fs=pe((s,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=je();e.exports=a;var{ERR_METHOD_NOT_IMPLEMENTED:i}=Ve().codes,n=ft(),{getHighWaterMark:o}=gr();t(a.prototype,n.prototype),t(a,n);var l=r("kCallback");function a(d){if(!(this instanceof a))return new a(d);let p=d?o(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[l]=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,g)=>{if(p){d?d(p):this.destroy(p);return}g!=null&&this.push(g),this.push(null),d&&d()}):(this.push(null),d&&d())}function u(){this._final!==c&&c.call(this)}a.prototype._final=c,a.prototype._transform=function(d,p,g){throw new i("_transform()")},a.prototype._write=function(d,p,g){let f=this._readableState,y=this._writableState,b=f.length;this._transform(d,p,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),y.ended||b===f.length||f.length<f.highWaterMark?g():this[l]=g})},a.prototype._read=function(){if(this[l]){let d=this[l];this[l]=null,d()}}}),ps=pe((s,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=je();e.exports=i;var r=fs();t(i.prototype,r.prototype),t(i,r);function i(n){if(!(this instanceof i))return new i(n);r.call(this,n)}i.prototype._transform=function(n,o,l){l(null,n)}}),yi=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{ArrayIsArray:r,Promise:i,SymbolAsyncIterator:n,SymbolDispose:o}=je(),l=_t(),{once:a}=Ye(),c=Ft(),u=ft(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:y,ERR_STREAM_PREMATURE_CLOSE:b},AbortError:w}=Ve(),{validateFunction:m,validateAbortSignal:_}=er(),{isIterable:x,isReadable:v,isReadableNodeStream:E,isNodeStream:S,isTransformStream:I,isWebStream:P,isReadableStream:O,isReadableFinished:j}=ht(),T=globalThis.AbortController||Xt().AbortController,q,D,U;function ae(te,we,G){let N=!1;te.on("close",()=>{N=!0});let ne=l(te,{readable:we,writable:G},W=>{N=!W});return{destroy:W=>{N||(N=!0,c.destroyer(te,W||new y("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 F(te,we,G,{end:N}){let ne,W=null,K=oe=>{if(oe&&(ne=oe),W){let R=W;W=null,R()}},J=()=>new i((oe,R)=>{ne?R(ne):W=()=>{ne?R(ne):oe()}});we.on("drain",K);let ge=l(we,{readable:!1},K);try{we.writableNeedDrain&&await J();for await(let oe of te)we.write(oe)||await J();N&&(we.end(),await J()),G()}catch(oe){G(ne!==oe?d(ne,oe):oe)}finally{ge(),we.off("drain",K)}}async function Z(te,we,G,{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(),G()}catch(W){try{await ne.abort(W),G(W)}catch(K){G(K)}}}function M(...te){return Q(te,a(Y(te)))}function Q(te,we,G){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new f("streams");let N=new T,ne=N.signal,W=G?.signal,K=[];_(W,"options.signal");function J(){fe(new w)}U=U||Ye().addAbortListener;let ge;W&&(ge=U(W,J));let oe,R,$=[],ee=0;function he(ve){fe(ve,--ee===0)}function fe(ve,se){var Te;if(ve&&(!oe||oe.code==="ERR_STREAM_PREMATURE_CLOSE")&&(oe=ve),!(!oe&&!se)){for(;$.length;)$.shift()(oe);(Te=ge)===null||Te===void 0||Te[o](),N.abort(),se&&(oe||K.forEach(h=>h()),t.nextTick(we,oe,R))}}let be;for(let ve=0;ve<te.length;ve++){let se=te[ve],Te=ve<te.length-1,h=ve>0,k=Te||G?.end!==!1,A=ve===te.length-1;if(S(se)){let B=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(X)};if(k){let{destroy:X,cleanup:de}=ae(se,Te,h);$.push(X),v(se)&&A&&K.push(de)}se.on("error",B),v(se)&&A&&K.push(()=>{se.removeListener("error",B)})}if(ve===0)if(typeof se=="function"){if(be=se({signal:ne}),!x(be))throw new g("Iterable, AsyncIterable or Stream","source",be)}else x(se)||E(se)||I(se)?be=se:be=u.from(se);else if(typeof se=="function"){if(I(be)){var H;be=V((H=be)===null||H===void 0?void 0:H.readable)}else be=V(be);if(be=se(be,{signal:ne}),Te){if(!x(be,!0))throw new g("AsyncIterable",`transform[${ve-1}]`,be)}else{var me;q||(q=ps());let B=new q({objectMode:!0}),X=(me=be)===null||me===void 0?void 0:me.then;if(typeof X=="function")ee++,X.call(be,z=>{R=z,z!=null&&B.write(z),k&&B.end(),t.nextTick(he)},z=>{B.destroy(z),t.nextTick(he,z)});else if(x(be,!0))ee++,F(be,B,he,{end:k});else if(O(be)||I(be)){let z=be.readable||be;ee++,F(z,B,he,{end:k})}else throw new g("AsyncIterable or Promise","destination",be);be=B;let{destroy:de,cleanup:ke}=ae(be,!1,!0);$.push(de),A&&K.push(ke)}}else if(S(se)){if(E(be)){ee+=2;let B=ye(be,se,he,{end:k});v(se)&&A&&K.push(B)}else if(I(be)||O(be)){let B=be.readable||be;ee++,F(B,se,he,{end:k})}else if(x(be))ee++,F(be,se,he,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],be);be=se}else if(P(se)){if(E(be))ee++,Z(V(be),se,he,{end:k});else if(O(be)||x(be))ee++,Z(be,se,he,{end:k});else if(I(be))ee++,Z(be.readable,se,he,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],be);be=se}else be=u.from(se)}return(ne!=null&&ne.aborted||W!=null&&W.aborted)&&t.nextTick(J),be}function ye(te,we,G,{end:N}){let ne=!1;if(we.on("close",()=>{ne||G(new b)}),te.pipe(we,{end:!1}),N){let W=function(){ne=!0,we.end()};j(te)?t.nextTick(W):te.once("end",W)}else G();return l(te,{readable:!0,writable:!1},W=>{let K=te._readableState;W&&W.code==="ERR_STREAM_PREMATURE_CLOSE"&&K&&K.ended&&!K.errored&&!K.errorEmitted?te.once("end",G).once("error",G):G(W)}),l(we,{readable:!1,writable:!0},G)}e.exports={pipelineImpl:Q,pipeline:M}}),ms=pe((s,e)=>{le(),ue(),ce();var{pipeline:t}=yi(),r=ft(),{destroyer:i}=Ft(),{isNodeStream:n,isReadable:o,isWritable:l,isWebStream:a,isTransformStream:c,isWritableStream:u,isReadableStream:d}=ht(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:f}}=Ve(),y=_t();e.exports=function(...b){if(b.length===0)throw new f("streams");if(b.length===1)return r.from(b[0]);let w=[...b];if(typeof b[0]=="function"&&(b[0]=r.from(b[0])),typeof b[b.length-1]=="function"){let T=b.length-1;b[T]=r.from(b[T])}for(let T=0;T<b.length;++T)if(!(!n(b[T])&&!a(b[T]))){if(T<b.length-1&&!(o(b[T])||d(b[T])||c(b[T])))throw new g(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(l(b[T])||u(b[T])||c(b[T])))throw new g(`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&&!O&&E.destroy()}let I=b[0],P=t(b,S),O=!!(l(I)||u(I)||c(I)),j=!!(o(P)||d(P)||c(P));if(E=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(P!=null&&P.readableObjectMode),writable:O,readable:j}),O){if(n(I))E._write=function(q,D,U){I.write(q,D)?U():m=U},E._final=function(q){I.end(),_=q},I.on("drain",function(){if(m){let q=m;m=null,q()}});else if(a(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(P)?P.readable:P;y(T,()=>{if(_){let q=_;_=null,q()}})}if(j){if(n(P))P.on("readable",function(){if(x){let T=x;x=null,T()}}),P.on("end",function(){E.push(null)}),E._read=function(){for(;;){let T=P.read();if(T===null){x=E._read;return}if(!E.push(T))return}};else if(a(P)){let T=(c(P)?P.readable:P).getReader();E._read=async function(){for(;;)try{let{value:q,done:D}=await T.read();if(!E.push(q))return;if(D){E.push(null);return}}catch{return}}}}return E._destroy=function(T,q){!T&&v!==null&&(T=new p),x=null,m=null,_=null,v===null?q(T):(v=q,n(P)&&i(P,T))},E}}),Kc=pe((s,e)=>{le(),ue(),ce();var t=globalThis.AbortController||Xt().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:i,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:o},AbortError:l}=Ve(),{validateAbortSignal:a,validateInteger:c,validateObject:u}=er(),d=je().Symbol("kWeak"),p=je().Symbol("kResistStopPropagation"),{finished:g}=_t(),f=ms(),{addAbortSignalNoValidate:y}=mr(),{isWritable:b,isNodeStream:w}=ht(),{deprecate:m}=Ye(),{ArrayPrototypePush:_,Boolean:x,MathFloor:v,Number:E,NumberIsNaN:S,Promise:I,PromiseReject:P,PromiseResolve:O,PromisePrototypeThen:j,Symbol:T}=je(),q=T("kEmpty"),D=T("kEof");function U(W,K){if(K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal"),w(W)&&!b(W))throw new r("stream",W,"must be writable");let J=f(this,W);return K!=null&&K.signal&&y(K.signal,J),J}function ae(W,K){if(typeof W!="function")throw new i("fn",["Function","AsyncFunction"],W);K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal");let J=1;K?.concurrency!=null&&(J=v(K.concurrency));let ge=J-1;return K?.highWaterMark!=null&&(ge=v(K.highWaterMark)),c(J,"options.concurrency",1),c(ge,"options.highWaterMark",0),ge+=J,(async function*(){let oe=Ye().AbortSignalAny([K?.signal].filter(x)),R=this,$=[],ee={signal:oe},he,fe,be=!1,H=0;function me(){be=!0,ve()}function ve(){H-=1,se()}function se(){fe&&!be&&H<J&&$.length<ge&&(fe(),fe=null)}async function Te(){try{for await(let h of R){if(be)return;if(oe.aborted)throw new l;try{if(h=W(h,ee),h===q)continue;h=O(h)}catch(k){h=P(k)}H+=1,j(h,ve,me),$.push(h),he&&(he(),he=null),!be&&($.length>=ge||H>=J)&&await new I(k=>{fe=k})}$.push(D)}catch(h){let k=P(h);j(k,ve,me),$.push(k)}finally{be=!0,he&&(he(),he=null)}}Te();try{for(;;){for(;$.length>0;){let h=await $[0];if(h===D)return;if(oe.aborted)throw new l;h!==q&&(yield h),$.shift(),se()}await new I(h=>{he=h})}}finally{be=!0,fe&&(fe(),fe=null)}}).call(this)}function Y(W=void 0){return W!=null&&u(W,"options"),W?.signal!=null&&a(W.signal,"options.signal"),(async function*(){let K=0;for await(let ge of this){var J;if(W!=null&&(J=W.signal)!==null&&J!==void 0&&J.aborted)throw new l({cause:W.signal.reason});yield[K++,ge]}}).call(this)}async function V(W,K=void 0){for await(let J of M.call(this,W,K))return!0;return!1}async function re(W,K=void 0){if(typeof W!="function")throw new i("fn",["Function","AsyncFunction"],W);return!await V.call(this,async(...J)=>!await W(...J),K)}async function F(W,K){for await(let J of M.call(this,W,K))return J}async function Z(W,K){if(typeof W!="function")throw new i("fn",["Function","AsyncFunction"],W);async function J(ge,oe){return await W(ge,oe),q}for await(let ge of ae.call(this,J,K));}function M(W,K){if(typeof W!="function")throw new i("fn",["Function","AsyncFunction"],W);async function J(ge,oe){return await W(ge,oe)?ge:q}return ae.call(this,J,K)}var Q=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function ye(W,K,J){var ge;if(typeof W!="function")throw new i("reducer",["Function","AsyncFunction"],W);J!=null&&u(J,"options"),J?.signal!=null&&a(J.signal,"options.signal");let oe=arguments.length>1;if(J!=null&&(ge=J.signal)!==null&&ge!==void 0&&ge.aborted){let fe=new l(void 0,{cause:J.signal.reason});throw this.once("error",()=>{}),await g(this.destroy(fe)),fe}let R=new t,$=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 l;oe?K=await W(K,fe,{signal:$}):(K=fe,oe=!0)}if(!ee&&!oe)throw new Q}finally{R.abort()}return K}async function te(W){W!=null&&u(W,"options"),W?.signal!=null&&a(W.signal,"options.signal");let K=[];for await(let ge of this){var J;if(W!=null&&(J=W.signal)!==null&&J!==void 0&&J.aborted)throw new l(void 0,{cause:W.signal.reason});_(K,ge)}return K}function we(W,K){let J=ae.call(this,W,K);return(async function*(){for await(let ge of J)yield*ge}).call(this)}function G(W){if(W=E(W),S(W))return 0;if(W<0)throw new o("number",">= 0",W);return W}function N(W,K=void 0){return K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal"),W=G(W),(async function*(){var J;if(K!=null&&(J=K.signal)!==null&&J!==void 0&&J.aborted)throw new l;for await(let oe of this){var ge;if(K!=null&&(ge=K.signal)!==null&&ge!==void 0&&ge.aborted)throw new l;W--<=0&&(yield oe)}}).call(this)}function ne(W,K=void 0){return K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal"),W=G(W),(async function*(){var J;if(K!=null&&(J=K.signal)!==null&&J!==void 0&&J.aborted)throw new l;for await(let oe of this){var ge;if(K!=null&&(ge=K.signal)!==null&&ge!==void 0&&ge.aborted)throw new l;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:ye,toArray:te,some:V,find:F}}),gs=pe((s,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=je(),{isIterable:i,isNodeStream:n,isWebStream:o}=ht(),{pipelineImpl:l}=yi(),{finished:a}=_t();ys();function c(...u){return new r((d,p)=>{let g,f,y=u[u.length-1];if(y&&typeof y=="object"&&!n(y)&&!i(y)&&!o(y)){let b=t(u);g=b.signal,f=b.end}l(u,(b,w)=>{b?p(b):d(w)},{signal:g,end:f})})}e.exports={finished:a,pipeline:c}}),ys=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Re(Fe)),{ObjectDefineProperty:r,ObjectKeys:i,ReflectApply:n}=je(),{promisify:{custom:o}}=Ye(),{streamReturningOperators:l,promiseReturningOperators:a}=Kc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ve(),u=ms(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=gr(),{pipeline:g}=yi(),{destroyer:f}=Ft(),y=_t(),b=gs(),w=ht(),m=e.exports=mi().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 i(l)){let v=function(...S){if(new.target)throw c();return m.Readable.from(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})}for(let x of i(a)){let v=function(...S){if(new.target)throw c();return 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})}m.Writable=gi(),m.Duplex=ft(),m.Transform=fs(),m.PassThrough=ps(),m.pipeline=g;var{addAbortSignal:_}=mr();m.addAbortSignal=_,m.finished=y,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return b}}),r(g,o,{__proto__:null,enumerable:!0,get(){return b.pipeline}}),r(y,o,{__proto__:null,enumerable:!0,get(){return b.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)}}),Pt=pe((s,e)=>{le(),ue(),ce();var t=ys(),r=gs(),i=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=i,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get(){return r}}),e.exports.Stream=t.Stream,e.exports.default=e.exports}),Yc=pe((s,e)=>{le(),ue(),ce(),typeof Object.create=="function"?e.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(t,r){if(r){t.super_=r;var i=function(){};i.prototype=r.prototype,t.prototype=new i,t.prototype.constructor=t}}}),Jc=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Re(Fe)),r=Symbol.for("BufferList");function i(n){if(!(this instanceof i))return new i(n);i._init.call(this,n)}i._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},i.prototype._new=function(n){return new i(n)},i.prototype._offset=function(n){if(n===0)return[0,0];let o=0;for(let l=0;l<this._bufs.length;l++){let a=o+this._bufs[l].length;if(n<a||l===this._bufs.length-1)return[l,n-o];o=a}},i.prototype._reverseOffset=function(n){let o=n[0],l=n[1];for(let a=0;a<o;a++)l+=this._bufs[a].length;return l},i.prototype.getBuffers=function(){return this._bufs},i.prototype.get=function(n){if(n>this.length||n<0)return;let o=this._offset(n);return this._bufs[o[0]][o[1]]},i.prototype.slice=function(n,o){return typeof n=="number"&&n<0&&(n+=this.length),typeof o=="number"&&o<0&&(o+=this.length),this.copy(null,0,n,o)},i.prototype.copy=function(n,o,l,a){if((typeof l!="number"||l<0)&&(l=0),(typeof a!="number"||a>this.length)&&(a=this.length),l>=this.length||a<=0)return n||t.alloc(0);let c=!!n,u=this._offset(l),d=a-l,p=d,g=c&&o||0,f=u[1];if(l===0&&a===this.length){if(!c)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let y=0;y<this._bufs.length;y++)this._bufs[y].copy(n,g),g+=this._bufs[y].length;return n}if(p<=this._bufs[u[0]].length-f)return c?this._bufs[u[0]].copy(n,o,f,f+p):this._bufs[u[0]].slice(f,f+p);c||(n=t.allocUnsafe(d));for(let y=u[0];y<this._bufs.length;y++){let b=this._bufs[y].length-f;if(p>b)this._bufs[y].copy(n,g,f),g+=b;else{this._bufs[y].copy(n,g,f,f+p),g+=b;break}p-=b,f&&(f=0)}return n.length>g?n.slice(0,g):n},i.prototype.shallowSlice=function(n,o){if(n=n||0,o=typeof o!="number"?this.length:o,n<0&&(n+=this.length),o<0&&(o+=this.length),n===o)return this._new();let l=this._offset(n),a=this._offset(o),c=this._bufs.slice(l[0],a[0]+1);return a[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,a[1]),l[1]!==0&&(c[0]=c[0].slice(l[1])),this._new(c)},i.prototype.toString=function(n,o,l){return this.slice(o,l).toString(n)},i.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},i.prototype.duplicate=function(){let n=this._new();for(let o=0;o<this._bufs.length;o++)n.append(this._bufs[o]);return n},i.prototype.append=function(n){return this._attach(n,i.prototype._appendBuffer)},i.prototype.prepend=function(n){return this._attach(n,i.prototype._prependBuffer,!0)},i.prototype._attach=function(n,o,l){if(n==null)return this;if(n.buffer)o.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[a,c]=l?[n.length-1,-1]:[0,1];for(let u=a;u>=0&&u<n.length;u+=c)this._attach(n[u],o,l)}else if(this._isBufferList(n)){let[a,c]=l?[n._bufs.length-1,-1]:[0,1];for(let u=a;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],o,l)}else typeof n=="number"&&(n=n.toString()),o.call(this,t.from(n));return this},i.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},i.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},i.prototype.indexOf=function(n,o,l){if(l===void 0&&typeof o=="string"&&(l=o,o=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,l):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)),o=Number(o||0),isNaN(o)&&(o=0),o<0&&(o=this.length+o),o<0&&(o=0),n.length===0)return o>this.length?this.length:o;let a=this._offset(o),c=a[0],u=a[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},i.prototype._match=function(n,o){if(this.length-n<o.length)return!1;for(let l=0;l<o.length;l++)if(this.get(n+l)!==o[l])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 o in n)(function(l){n[l]===null?i.prototype[l]=function(a,c){return this.slice(a,a+c)[l](0,c)}:i.prototype[l]=function(a=0){return this.slice(a,a+n[l])[l](0)}})(o)})(),i.prototype._isBufferList=function(n){return n instanceof i||i.isBufferList(n)},i.isBufferList=function(n){return n!=null&&n[r]},e.exports=i}),Qc=pe((s,e)=>{le(),ue(),ce();var t=Pt().Duplex,r=Yc(),i=Jc();function n(o){if(!(this instanceof n))return new n(o);if(typeof o=="function"){this._callback=o;let l=(function(a){this._callback&&(this._callback(a),this._callback=null)}).bind(this);this.on("pipe",function(a){a.on("error",l)}),this.on("unpipe",function(a){a.removeListener("error",l)}),o=null}i._init.call(this,o),t.call(this)}r(n,t),Object.assign(n.prototype,i.prototype),n.prototype._new=function(o){return new n(o)},n.prototype._write=function(o,l,a){this._appendBuffer(o),typeof a=="function"&&a()},n.prototype._read=function(o){if(!this.length)return this.push(null);o=Math.min(o,this.length),this.push(this.slice(0,o)),this.consume(o)},n.prototype.end=function(o){t.prototype.end.call(this,o),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(o,l){this._bufs.length=0,this.length=0,l(o)},n.prototype._isBufferList=function(o){return o instanceof n||o instanceof i||n.isBufferList(o)},n.isBufferList=i.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=i}),Xc=pe((s,e)=>{le(),ue(),ce();var t=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}};e.exports=t}),bs=pe((s,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=($e(),Re(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 o=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+o.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let o=t.types[n];t.codes[o]=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 o=t.properties[n];t.propertiesCodes[o]=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 i(n){return[0,1,2].map(o=>[0,1].map(l=>[0,1].map(a=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(l?t.DUP_MASK:0)|o<<t.QOS_SHIFT|a,0,!0),c})))}t.PUBLISH_HEADER=i("publish"),t.SUBSCRIBE_HEADER=i("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=i("unsubscribe"),t.ACKS={unsuback:i("unsuback"),puback:i("puback"),pubcomp:i("pubcomp"),pubrel:i("pubrel"),pubrec:i("pubrec")},t.SUBACK_HEADER=r.from([t.codes.suback<<t.CMD_SHIFT]),t.VERSION3=r.from([3]),t.VERSION4=r.from([4]),t.VERSION5=r.from([5]),t.VERSION131=r.from([131]),t.VERSION132=r.from([132]),t.QOS=[0,1,2].map(n=>r.from([n])),t.EMPTY={pingreq:r.from([t.codes.pingreq<<4,0]),pingresp:r.from([t.codes.pingresp<<4,0]),disconnect:r.from([t.codes.disconnect<<4,0])},t.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},t.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},t.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},t.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}}),Zc=pe((s,e)=>{le(),ue(),ce();var t=1e3,r=t*60,i=r*60,n=i*24,o=n*7,l=n*365.25;e.exports=function(p,g){g=g||{};var f=typeof p;if(f==="string"&&p.length>0)return a(p);if(f==="number"&&isFinite(p))return g.long?u(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function a(p){if(p=String(p),!(p.length>100)){var g=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(g){var f=parseFloat(g[1]),y=(g[2]||"ms").toLowerCase();switch(y){case"years":case"year":case"yrs":case"yr":case"y":return f*l;case"weeks":case"week":case"w":return f*o;case"days":case"day":case"d":return f*n;case"hours":case"hour":case"hrs":case"hr":case"h":return f*i;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 g=Math.abs(p);return g>=n?Math.round(p/n)+"d":g>=i?Math.round(p/i)+"h":g>=r?Math.round(p/r)+"m":g>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var g=Math.abs(p);return g>=n?d(p,g,n,"day"):g>=i?d(p,g,i,"hour"):g>=r?d(p,g,r,"minute"):g>=t?d(p,g,t,"second"):p+" ms"}function d(p,g,f,y){var b=g>=f*1.5;return Math.round(p/f)+" "+y+(b?"s":"")}}),eu=pe((s,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=d,n.disable=c,n.enable=l,n.enabled=u,n.humanize=Zc(),n.destroy=p,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function i(g){let f=0;for(let y=0;y<g.length;y++)f=(f<<5)-f+g.charCodeAt(y),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=i;function n(g){let f,y=null,b,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,(I,P)=>{if(I==="%%")return"%";S++;let O=n.formatters[P];if(typeof O=="function"){let j=_[S];I=O.call(x,j),_.splice(S,1),S--}return I}),n.formatArgs.call(x,_),(x.log||n.log).apply(x,_)}return m.namespace=g,m.useColors=n.useColors(),m.color=n.selectColor(g),m.extend=o,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(b!==n.namespaces&&(b=n.namespaces,w=n.enabled(g)),w),set:_=>{y=_}}),typeof n.init=="function"&&n.init(m),m}function o(g,f){let y=n(this.namespace+(typeof f>"u"?":":f)+g);return y.log=this.log,y}function l(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let f=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let y of f)y[0]==="-"?n.skips.push(y.slice(1)):n.names.push(y)}function a(g,f){let y=0,b=0,w=-1,m=0;for(;y<g.length;)if(b<f.length&&(f[b]===g[y]||f[b]==="*"))f[b]==="*"?(w=b,m=y,b++):(y++,b++);else if(w!==-1)b=w+1,m++,y=m;else return!1;for(;b<f.length&&f[b]==="*";)b++;return b===f.length}function c(){let g=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),g}function u(g){for(let f of n.skips)if(a(g,f))return!1;for(let f of n.names)if(a(g,f))return!0;return!1}function d(g){return g instanceof Error?g.stack||g.message:g}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=i,s.load=n,s.useColors=t,s.storage=o(),s.destroy=(()=>{let a=!1;return()=>{a||(a=!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 a;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&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;a.splice(1,0,c,"color: inherit");let u=0,d=0;a[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(d=u))}),a.splice(d,0,c)}s.log=console.debug||console.log||(()=>{});function i(a){try{a?s.storage.setItem("debug",a):s.storage.removeItem("debug")}catch{}}function n(){let a;try{a=s.storage.getItem("debug")||s.storage.getItem("DEBUG")}catch{}return!a&&typeof Le<"u"&&"env"in Le&&(a=Le.env.DEBUG),a}function o(){try{return localStorage}catch{}}e.exports=eu()(s);var{formatters:l}=e.exports;l.j=function(a){try{return JSON.stringify(a)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),tu=pe((s,e)=>{le(),ue(),ce();var t=Qc(),{EventEmitter:r}=(Tt(),Re(wt)),i=Xc(),n=bs(),o=pt()("mqtt-packet:parser"),l=class Ro extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof Ro?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new Ro().parser(c)}_resetState(){o("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new i,this.error=null,this._list=t(),this._stateCounter=0}parse(c){for(this.error&&this._resetState(),this._list.append(c),o("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++,o("parse: state complete. _stateCounter is now: %d",this._stateCounter),o("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return o("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,o("_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)),o("_parseLength %d",c.value),!!c}_parsePayload(){o("_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 o("_parsePayload complete result: %s",c),c}_parseConnect(){o("_parseConnect");let c,u,d,p,g={},f=this.packet,y=this._parseString();if(y===null)return this._emitError(new Error("Cannot parse protocolId"));if(y!=="MQTT"&&y!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=y,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"));g.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,g.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,g.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let b=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),w=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(g.will)f.will={},f.will.retain=b,f.will.qos=w;else{if(b)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,o("_parseConnect: packet.clientId: %s",f.clientId),g.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,o("_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,o("_parseConnect: packet.will.paylaod: %s",f.will.payload)}if(g.username){if(p=this._parseString(),p===null)return this._emitError(new Error("Cannot parse username"));f.username=p,o("_parseConnect: packet.username: %s",f.username)}if(g.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));f.password=d}return this.settings=f,o("_parseConnect: complete"),f}_parseConnack(){o("_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)}o("_parseConnack: complete")}_parsePublish(){o("_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),o("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){o("_parseSubscribe");let c=this.packet,u,d,p,g,f,y,b;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(y=(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,g=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,g>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));b={topic:u,qos:p},this.settings.protocolVersion===5?(b.nl=y,b.rap=f,b.rh=g):this.settings.bridgeMode&&(b.rh=0,b.rap=!0,b.nl=!0),o("_parseSubscribe: push subscription `%s` to subscription",b),c.subscriptions.push(b)}}}_parseSuback(){o("_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(){o("_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"));o("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){o("_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(){o("_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}o("_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(o("_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 o("_parseDisconnect result: true"),!0}_parseAuth(){o("_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),o("_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):(o("_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,o("_parseString: result: %s",p),p}_parseStringPair(){return o("_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,o("_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,o("_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,o("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){o("_parseVarByteNum");let u=4,d=0,p=1,g=0,f=!1,y,b=this._pos?this._pos:0;for(;d<u&&b+d<this._list.length;){if(y=this._list.readUInt8(b+d++),g+=p*(y&n.VARBYTEINT_MASK),p*=128,(y&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")),b&&(this._pos+=d),f?c?f={bytes:d,value:g}:f=g:f=!1,o("_parseVarByteNum: result: %o",f),f}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),o("_parseByte: result: %o",c),c}_parseByType(c){switch(o("_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(){o("_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 g=n.propertiesCodes[p];if(!g)return this._emitError(new Error("Unknown property")),!1;if(g==="userProperties"){d[g]||(d[g]=Object.create(null));let f=this._parseByType(n.propertiesTypes[g]);if(d[g][f.name])if(Array.isArray(d[g][f.name]))d[g][f.name].push(f.value);else{let y=d[g][f.name];d[g][f.name]=[y],d[g][f.name].push(f.value)}else d[g][f.name]=f.value;continue}d[g]?Array.isArray(d[g])?d[g].push(this._parseByType(n.propertiesTypes[g])):(d[g]=[d[g]],d[g].push(this._parseByType(n.propertiesTypes[g]))):d[g]=this._parseByType(n.propertiesTypes[g])}return d}_newPacket(){return o("_newPacket"),this.packet&&(this._list.consume(this.packet.length),o("_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)),o("_newPacket: new packet"),this.packet=new i,this._pos=0,!0}_emitError(c){o("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=l}),ru=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Re(Fe)),r=65536,i={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function o(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function l(){for(let u=0;u<r;u++)i[u]=o(u)}function a(u){let d=0,p=0,g=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),g.writeUInt8(d,p++);while(u>0&&p<4);return u>0&&(p=0),n?g.subarray(0,p):g.slice(0,p)}function c(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:i,generateCache:l,generateNumber:o,genBufVariableByteInt:a,generate4ByteBuffer:c}}),nu=pe((s,e)=>{le(),ue(),ce(),typeof Le>"u"||!Le.version||Le.version.indexOf("v0.")===0||Le.version.indexOf("v1.")===0&&Le.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Le;function t(r,i,n,o){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var l=arguments.length,a,c;switch(l){case 0:case 1:return Le.nextTick(r);case 2:return Le.nextTick(function(){r.call(null,i)});case 3:return Le.nextTick(function(){r.call(null,i,n)});case 4:return Le.nextTick(function(){r.call(null,i,n,o)});default:for(a=new Array(l-1),c=0;c<a.length;)a[c++]=arguments[c];return Le.nextTick(function(){r.apply(null,a)})}}}),vs=pe((s,e)=>{le(),ue(),ce();var t=bs(),{Buffer:r}=($e(),Re(Fe)),i=r.allocUnsafe(0),n=r.from([0]),o=ru(),l=nu().nextTick,a=pt()("mqtt-packet:writeToStream"),c=o.cache,u=o.generateNumber,d=o.generateCache,p=o.genBufVariableByteInt,g=o.generate4ByteBuffer,f=Y,y=!0;function b(G,N,ne){switch(a("generate called"),N.cork&&(N.cork(),l(w,N)),y&&(y=!1,d()),a("generate: packet.cmd: %s",G.cmd),G.cmd){case"connect":return m(G,N);case"connack":return _(G,N,ne);case"publish":return x(G,N,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(G,N,ne);case"subscribe":return E(G,N,ne);case"suback":return S(G,N,ne);case"unsubscribe":return I(G,N,ne);case"unsuback":return P(G,N,ne);case"pingreq":case"pingresp":return O(G,N);case"disconnect":return j(G,N,ne);case"auth":return T(G,N,ne);default:return N.destroy(new Error("Unknown command")),!1}}Object.defineProperty(b,"cacheNumbers",{get(){return f===Y},set(G){G?((!c||Object.keys(c).length===0)&&(y=!0),f=Y):(y=!1,f=V)}});function w(G){G.uncork()}function m(G,N,ne){let W=G||{},K=W.protocolId||"MQTT",J=W.protocolVersion||4,ge=W.will,oe=W.clean,R=W.keepalive||0,$=W.clientId||"",ee=W.username,he=W.password,fe=W.properties;oe===void 0&&(oe=!0);let be=0;if(typeof K!="string"&&!r.isBuffer(K))return N.destroy(new Error("Invalid protocolId")),!1;if(be+=K.length+2,J!==3&&J!==4&&J!==5)return N.destroy(new Error("Invalid protocol version")),!1;if(be+=1,(typeof $=="string"||r.isBuffer($))&&($||J>=4)&&($||oe))be+=r.byteLength($)+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;be+=2,be+=1;let H,me;if(J===5){if(H=Z(N,fe),!H)return!1;be+=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(be+=r.byteLength(ge.topic)+2,be+=2,ge.payload)if(ge.payload.length>=0)typeof ge.payload=="string"?be+=r.byteLength(ge.payload):be+=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;be+=me.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,be+=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))be+=te(he)+2;else return N.destroy(new Error("Invalid password")),!1}N.write(t.CONNECT_HEADER),D(N,be),F(N,K),W.bridgeMode&&(J+=128),N.write(J===131?t.VERSION131:J===132?t.VERSION132:J===4?t.VERSION4:J===5?t.VERSION5:t.VERSION3);let se=0;return se|=ee!=null?t.USERNAME_MASK:0,se|=he!=null?t.PASSWORD_MASK:0,se|=ge&&ge.retain?t.WILL_RETAIN_MASK:0,se|=ge&&ge.qos?ge.qos<<t.WILL_QOS_SHIFT:0,se|=ge?t.WILL_FLAG_MASK:0,se|=oe?t.CLEAN_SESSION_MASK:0,N.write(r.from([se])),f(N,R),J===5&&H.write(),F(N,$),ge&&(J===5&&me.write(),U(N,ge.topic),F(N,ge.payload)),ee!=null&&F(N,ee),he!=null&&F(N,he),!0}function _(G,N,ne){let W=ne?ne.protocolVersion:4,K=G||{},J=W===5?K.reasonCode:K.returnCode,ge=K.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(K.sessionPresent?t.SESSIONPRESENT_HEADER:n),N.write(r.from([J])),R?.write(),!0}function x(G,N,ne){a("publish: packet: %o",G);let W=ne?ne.protocolVersion:4,K=G||{},J=K.qos||0,ge=K.retain?t.RETAIN_MASK:0,oe=K.topic,R=K.payload||i,$=K.messageId,ee=K.properties,he=0;if(typeof oe=="string")he+=r.byteLength(oe)+2;else if(r.isBuffer(oe))he+=oe.length+2;else return N.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?he+=R.length:he+=r.byteLength(R),J&&typeof $!="number")return N.destroy(new Error("Invalid messageId")),!1;J&&(he+=2);let fe=null;if(W===5){if(fe=Z(N,ee),!fe)return!1;he+=fe.length}return N.write(t.PUBLISH_HEADER[J][K.dup?1:0][ge?1:0]),D(N,he),f(N,te(oe)),N.write(oe),J>0&&f(N,$),fe?.write(),a("publish: payload: %o",R),N.write(R)}function v(G,N,ne){let W=ne?ne.protocolVersion:4,K=G||{},J=K.cmd||"puback",ge=K.messageId,oe=K.dup&&J==="pubrel"?t.DUP_MASK:0,R=0,$=K.reasonCode,ee=K.properties,he=W===5?3:2;if(J==="pubrel"&&(R=1),typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;let fe=null;if(W===5&&typeof ee=="object"){if(fe=M(N,ee,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[J][R][oe][0]),he===3&&(he+=$!==0?1:-1),D(N,he),f(N,ge),W===5&&he!==2&&N.write(r.from([$])),fe!==null?fe.write():he===4&&N.write(r.from([0])),!0}function E(G,N,ne){a("subscribe: packet: ");let W=ne?ne.protocolVersion:4,K=G||{},J=K.dup?t.DUP_MASK:0,ge=K.messageId,oe=K.subscriptions,R=K.properties,$=0;if(typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;$+=2;let ee=null;if(W===5){if(ee=Z(N,R),!ee)return!1;$+=ee.length}if(typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){let be=oe[fe].topic,H=oe[fe].qos;if(typeof be!="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}$+=r.byteLength(be)+2+1}else return N.destroy(new Error("Invalid subscriptions")),!1;a("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),N.write(t.SUBSCRIBE_HEADER[1][J?1:0][0]),D(N,$),f(N,ge),ee!==null&&ee.write();let he=!0;for(let fe of oe){let be=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,se=fe.rh,Te;U(N,be),Te=t.SUBSCRIBE_OPTIONS_QOS[H],W===5&&(Te|=me?t.SUBSCRIBE_OPTIONS_NL:0,Te|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Te|=se?t.SUBSCRIBE_OPTIONS_RH[se]:0),he=N.write(r.from([Te]))}return he}function S(G,N,ne){let W=ne?ne.protocolVersion:4,K=G||{},J=K.messageId,ge=K.granted,oe=K.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 $=null;if(W===5){if($=M(N,oe,ne,R),!$)return!1;R+=$.length}return N.write(t.SUBACK_HEADER),D(N,R),f(N,J),$!==null&&$.write(),N.write(r.from(ge))}function I(G,N,ne){let W=ne?ne.protocolVersion:4,K=G||{},J=K.messageId,ge=K.dup?t.DUP_MASK:0,oe=K.unsubscriptions,R=K.properties,$=0;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if($+=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;$+=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;$+=ee.length}N.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),D(N,$),f(N,J),ee!==null&&ee.write();let he=!0;for(let fe=0;fe<oe.length;fe++)he=U(N,oe[fe]);return he}function P(G,N,ne){let W=ne?ne.protocolVersion:4,K=G||{},J=K.messageId,ge=K.dup?t.DUP_MASK:0,oe=K.granted,R=K.properties,$=K.cmd,ee=0,he=2;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(W===5)if(typeof oe=="object"&&oe.length)for(let be=0;be<oe.length;be+=1){if(typeof oe[be]!="number")return N.destroy(new Error("Invalid qos vector")),!1;he+=1}else return N.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(W===5){if(fe=M(N,R,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[$][ee][ge][0]),D(N,he),f(N,J),fe!==null&&fe.write(),W===5&&N.write(r.from(oe)),!0}function O(G,N,ne){return N.write(t.EMPTY[G.cmd])}function j(G,N,ne){let W=ne?ne.protocolVersion:4,K=G||{},J=K.reasonCode,ge=K.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(G,N,ne){let W=ne?ne.protocolVersion:4,K=G||{},J=K.reasonCode,ge=K.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(G,N){if(N>t.VARBYTEINT_MAX)return G.destroy(new Error(`Invalid variable byte integer: ${N}`)),!1;let ne=q[N];return ne||(ne=p(N),N<16384&&(q[N]=ne)),a("writeVarByteInt: writing to stream: %o",ne),G.write(ne)}function U(G,N){let ne=r.byteLength(N);return f(G,ne),a("writeString: %s",N),G.write(N,"utf8")}function ae(G,N,ne){U(G,N),U(G,ne)}function Y(G,N){return a("writeNumberCached: number: %d",N),a("writeNumberCached: %o",c[N]),G.write(c[N])}function V(G,N){let ne=u(N);return a("writeNumberGenerated: %o",ne),G.write(ne)}function re(G,N){let ne=g(N);return a("write4ByteNumber: %o",ne),G.write(ne)}function F(G,N){typeof N=="string"?U(G,N):N?(f(G,N.length),G.write(N)):f(G,0)}function Z(G,N){if(typeof N!="object"||N.length!=null)return{length:1,write(){ye(G,{},0)}};let ne=0;function W(K,J){let ge=t.propertiesTypes[K],oe=0;switch(ge){case"byte":{if(typeof J!="boolean")return G.destroy(new Error(`Invalid ${K}: ${J}`)),!1;oe+=2;break}case"int8":{if(typeof J!="number"||J<0||J>255)return G.destroy(new Error(`Invalid ${K}: ${J}`)),!1;oe+=2;break}case"binary":{if(J&&J===null)return G.destroy(new Error(`Invalid ${K}: ${J}`)),!1;oe+=1+r.byteLength(J)+2;break}case"int16":{if(typeof J!="number"||J<0||J>65535)return G.destroy(new Error(`Invalid ${K}: ${J}`)),!1;oe+=3;break}case"int32":{if(typeof J!="number"||J<0||J>4294967295)return G.destroy(new Error(`Invalid ${K}: ${J}`)),!1;oe+=5;break}case"var":{if(typeof J!="number"||J<0||J>268435455)return G.destroy(new Error(`Invalid ${K}: ${J}`)),!1;oe+=1+r.byteLength(p(J));break}case"string":{if(typeof J!="string")return G.destroy(new Error(`Invalid ${K}: ${J}`)),!1;oe+=3+r.byteLength(J.toString());break}case"pair":{if(typeof J!="object")return G.destroy(new Error(`Invalid ${K}: ${J}`)),!1;oe+=Object.getOwnPropertyNames(J).reduce((R,$)=>{let ee=J[$];return Array.isArray(ee)?R+=ee.reduce((he,fe)=>(he+=3+r.byteLength($.toString())+2+r.byteLength(fe.toString()),he),0):R+=3+r.byteLength($.toString())+2+r.byteLength(J[$].toString()),R},0);break}default:return G.destroy(new Error(`Invalid property ${K}: ${J}`)),!1}return oe}if(N)for(let K in N){let J=0,ge=0,oe=N[K];if(oe!==void 0){if(Array.isArray(oe))for(let R=0;R<oe.length;R++){if(ge=W(K,oe[R]),!ge)return!1;J+=ge}else{if(ge=W(K,oe),!ge)return!1;J=ge}if(!J)return!1;ne+=J}}return{length:r.byteLength(p(ne))+ne,write(){ye(G,N,ne)}}}function M(G,N,ne,W){let K=["reasonString","userProperties"],J=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=Z(G,N);if(J)for(;W+ge.length>J;){let oe=K.shift();if(oe&&N[oe])delete N[oe],ge=Z(G,N);else return!1}return ge}function Q(G,N,ne){switch(t.propertiesTypes[N]){case"byte":{G.write(r.from([t.properties[N]])),G.write(r.from([+ne]));break}case"int8":{G.write(r.from([t.properties[N]])),G.write(r.from([ne]));break}case"binary":{G.write(r.from([t.properties[N]])),F(G,ne);break}case"int16":{G.write(r.from([t.properties[N]])),f(G,ne);break}case"int32":{G.write(r.from([t.properties[N]])),re(G,ne);break}case"var":{G.write(r.from([t.properties[N]])),D(G,ne);break}case"string":{G.write(r.from([t.properties[N]])),U(G,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(W=>{let K=ne[W];Array.isArray(K)?K.forEach(J=>{G.write(r.from([t.properties[N]])),ae(G,W.toString(),J.toString())}):(G.write(r.from([t.properties[N]])),ae(G,W.toString(),K.toString()))});break}default:return G.destroy(new Error(`Invalid property ${N} value: ${ne}`)),!1}}function ye(G,N,ne){D(G,ne);for(let W in N)if(Object.prototype.hasOwnProperty.call(N,W)&&N[W]!=null){let K=N[W];if(Array.isArray(K))for(let J=0;J<K.length;J++)Q(G,W,K[J]);else Q(G,W,K)}}function te(G){return G?G instanceof r?G.length:r.byteLength(G):0}function we(G){return typeof G=="string"||G instanceof r}e.exports=b}),iu=pe((s,e)=>{le(),ue(),ce();var t=vs(),{EventEmitter:r}=(Tt(),Re(wt)),{Buffer:i}=($e(),Re(Fe));function n(l,a){let c=new o;return t(l,c,a),c.concat()}var o=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(l){return this._array[this._i++]=l,!0}concat(){let l=0,a=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"?a[d]=c[d].length:a[d]=i.byteLength(c[d]),l+=a[d];let p=i.allocUnsafe(l);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(p,u),u+=a[d]):(p.write(c[d],u),u+=a[d]);return p}destroy(l){l&&this.emit("error",l)}};e.exports=n}),ou=pe(s=>{le(),ue(),ce(),s.parser=tu().parser,s.generate=iu(),s.writeToStream=vs()}),su=pe((s,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof pr?pr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return i(n);let o=new Map;if(o.set(Date,d=>new Date(d)),o.set(Map,(d,p)=>new Map(a(Array.from(d),p))),o.set(Set,(d,p)=>new Set(a(Array.from(d),p))),n.constructorHandlers)for(let d of n.constructorHandlers)o.set(d[0],d[1]);let l=null;return n.proto?u:c;function a(d,p){let g=Object.keys(d),f=new Array(g.length);for(let y=0;y<g.length;y++){let b=g[y],w=d[b];typeof w!="object"||w===null?f[b]=w:w.constructor!==Object&&(l=o.get(w.constructor))?f[b]=l(w,p):ArrayBuffer.isView(w)?f[b]=t(w):f[b]=p(w)}return f}function c(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return a(d,c);if(d.constructor!==Object&&(l=o.get(d.constructor)))return l(d,c);let p={};for(let g in d){if(Object.hasOwnProperty.call(d,g)===!1)continue;let f=d[g];typeof f!="object"||f===null?p[g]=f:f.constructor!==Object&&(l=o.get(f.constructor))?p[g]=l(f,c):ArrayBuffer.isView(f)?p[g]=t(f):p[g]=c(f)}return p}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return a(d,u);if(d.constructor!==Object&&(l=o.get(d.constructor)))return l(d,u);let p={};for(let g in d){let f=d[g];typeof f!="object"||f===null?p[g]=f:f.constructor!==Object&&(l=o.get(f.constructor))?p[g]=l(f,u):ArrayBuffer.isView(f)?p[g]=t(f):p[g]=u(f)}return p}}function i(n){let o=[],l=[],a=new Map;if(a.set(Date,g=>new Date(g)),a.set(Map,(g,f)=>new Map(u(Array.from(g),f))),a.set(Set,(g,f)=>new Set(u(Array.from(g),f))),n.constructorHandlers)for(let g of n.constructorHandlers)a.set(g[0],g[1]);let c=null;return n.proto?p:d;function u(g,f){let y=Object.keys(g),b=new Array(y.length);for(let w=0;w<y.length;w++){let m=y[w],_=g[m];if(typeof _!="object"||_===null)b[m]=_;else if(_.constructor!==Object&&(c=a.get(_.constructor)))b[m]=c(_,f);else if(ArrayBuffer.isView(_))b[m]=t(_);else{let x=o.indexOf(_);x!==-1?b[m]=l[x]:b[m]=f(_)}}return b}function d(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,d);if(g.constructor!==Object&&(c=a.get(g.constructor)))return c(g,d);let f={};o.push(g),l.push(f);for(let y in g){if(Object.hasOwnProperty.call(g,y)===!1)continue;let b=g[y];if(typeof b!="object"||b===null)f[y]=b;else if(b.constructor!==Object&&(c=a.get(b.constructor)))f[y]=c(b,d);else if(ArrayBuffer.isView(b))f[y]=t(b);else{let w=o.indexOf(b);w!==-1?f[y]=l[w]:f[y]=d(b)}}return o.pop(),l.pop(),f}function p(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,p);if(g.constructor!==Object&&(c=a.get(g.constructor)))return c(g,p);let f={};o.push(g),l.push(f);for(let y in g){let b=g[y];if(typeof b!="object"||b===null)f[y]=b;else if(b.constructor!==Object&&(c=a.get(b.constructor)))f[y]=c(b,p);else if(ArrayBuffer.isView(b))f[y]=t(b);else{let w=o.indexOf(b);w!==-1?f[y]=l[w]:f[y]=p(b)}}return o.pop(),l.pop(),f}}}),au=pe((s,e)=>{le(),ue(),ce(),e.exports=su()()}),ws=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.validateTopic=e,s.validateTopics=t;function e(r){let i=r.split("/");for(let n=0;n<i.length;n++)if(i[n]!=="+"){if(i[n]==="#")return n===i.length-1;if(i[n].indexOf("+")!==-1||i[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let i=0;i<r.length;i++)if(!e(r[i]))return r[i];return null}}),_s=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Pt(),t={objectMode:!0},r={clean:!0},i=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,o){return this._inflights.set(n.messageId,n),o&&o(),this}createStream(){let n=new e.Readable(t),o=[],l=!1,a=0;return this._inflights.forEach((c,u)=>{o.push(c)}),n._read=()=>{!l&&a<o.length?n.push(o[a++]):n.push(null)},n.destroy=c=>{if(!l)return l=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,o){let l=this._inflights.get(n.messageId);return l?(this._inflights.delete(n.messageId),o(null,l)):o&&o(new Error("missing packet")),this}get(n,o){let l=this._inflights.get(n.messageId);return l?o(null,l):o&&o(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};s.default=i}),lu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,i,n)=>{r.log("handlePublish: packet %o",i),n=typeof n<"u"?n:r.noop;let o=i.topic.toString(),l=i.payload,{qos:a}=i,{messageId:c}=i,{options:u}=r;if(r.options.protocolVersion===5){let d;if(i.properties&&(d=i.properties.topicAlias),typeof d<"u")if(o.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)o=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",o,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(o,d))r.log("handlePublish :: registered topic: %s - alias: %d",o,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",a),a){case 2:{u.customHandleAcks(o,l,i,(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(i,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(o,l,i,(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",o,l,i),r.handleMessage(i,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",o,l,i),r.handleMessage(i,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};s.default=t}),cu=pe((s,e)=>{e.exports={version:"5.15.0"}}),$t=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.MQTTJS_VERSION=s.nextTick=s.ErrorWithSubackPacket=s.ErrorWithReasonCode=void 0,s.applyMixin=r;var e=class pc extends Error{code;constructor(n,o){super(n),this.code=o,Object.setPrototypeOf(this,pc.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};s.ErrorWithReasonCode=e;var t=class mc extends Error{packet;constructor(n,o){super(n),this.packet=o,Object.setPrototypeOf(this,mc.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};s.ErrorWithSubackPacket=t;function r(i,n,o=!1){let l=[n];for(;;){let a=l[0],c=Object.getPrototypeOf(a);if(c?.prototype)l.unshift(c);else break}for(let a of l)for(let c of Object.getOwnPropertyNames(a.prototype))(o||c!=="constructor")&&Object.defineProperty(i.prototype,c,Object.getOwnPropertyDescriptor(a.prototype,c)??Object.create(null))}s.nextTick=typeof Le?.nextTick=="function"?Le.nextTick:i=>{setTimeout(i,0)},s.MQTTJS_VERSION=cu().version}),br=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=void 0;var e=$t();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,i)=>{let{messageId:n}=i,o=i.cmd,l=null,a=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!a){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",o),o){case"pubcomp":case"puback":{let u=i.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${s.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{a(c,i)})):r._removeOutgoingAndStoreMessage(n,a);break}case"pubrec":{l={cmd:"pubrel",qos:2,messageId:n};let u=i.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${s.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{a(c,i)})):r._sendPacket(l);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=i.granted;for(let d=0;d<u.length;d++){let p=u[d];if((p&128)!==0){c=new Error(`Subscribe error: ${s.ReasonCodes[p]}`),c.code=p;let g=r.messageIdToTopic[n];g&&g.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),a(c,i);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),a(null,i);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};s.default=t}),uu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=$t(),t=br(),r=(i,n)=>{let{options:o}=i,l=o.protocolVersion,a=l===5?n.reasonCode:n.returnCode;if(l!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${l}`,a);i.emit("error",c);return}i.handleAuth(n,(c,u)=>{if(c){i.emit("error",c);return}if(a===24)i.reconnecting=!1,i._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[a]}`,a);i.emit("error",d)}})};s.default=r}),du=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof Le=="object"&&Le?Le:{},i=(g,f,y,b)=>{typeof r.emitWarning=="function"?r.emitWarning(g,f,y,b):console.error(`[${y}] ${f}: ${g}`)},n=globalThis.AbortController,o=globalThis.AbortSignal;if(typeof n>"u"){o=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(y,b){this._onabort.push(b)}},n=class{constructor(){f()}signal=new o;abort(y){if(!this.signal.aborted){this.signal.reason=y,this.signal.aborted=!0;for(let b of this.signal._onabort)b(y);this.signal.onabort?.(y)}}};let g=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{g&&(g=!1,i("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 l=g=>!t.has(g),a=g=>g&&g===Math.floor(g)&&g>0&&isFinite(g),c=g=>a(g)?g<=Math.pow(2,8)?Uint8Array:g<=Math.pow(2,16)?Uint16Array:g<=Math.pow(2,32)?Uint32Array:g<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(g){super(g),this.fill(0)}},d=class cr{heap;length;static#l=!1;static create(f){let y=c(f);if(!y)return[];cr.#l=!0;let b=new cr(f,y);return cr.#l=!1,b}constructor(f,y){if(!cr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new y(f),this.length=0}push(f){this.heap[this.length++]=f}pop(){return this.heap[--this.length]}},p=class gc{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#n;#r;#e;#c;#h;#a;#o;#b;#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.#b,isBackgroundFetch:y=>f.#t(y),backgroundFetch:(y,b,w,m)=>f.#L(y,b,w,m),moveToTail:y=>f.#C(y),indexes:y=>f.#k(y),rindexes:y=>f.#x(y),isStale:y=>f.#p(y)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#y}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:y=0,ttl:b,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:_,updateAgeOnHas:x,allowStale:v,dispose:E,disposeAfter:S,noDisposeOnSet:I,noUpdateTTL:P,maxSize:O=0,maxEntrySize:j=0,sizeCalculation:T,fetchMethod:q,memoMethod:D,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:V,ignoreFetchAbort:re}=f;if(y!==0&&!a(y))throw new TypeError("max option must be a nonnegative integer");let F=y?c(y):Array;if(!F)throw new Error("invalid max value: "+y);if(this.#l=y,this.#d=O,this.maxEntrySize=j||this.#d,this.sizeCalculation=T,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(D!==void 0&&typeof D!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=D,q!==void 0&&typeof q!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=q,this.#A=!!q,this.#n=new Map,this.#r=new Array(y).fill(void 0),this.#e=new Array(y).fill(void 0),this.#c=new F(y),this.#h=new F(y),this.#a=0,this.#o=0,this.#b=d.create(y),this.#i=0,this.#y=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=!!P,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!V,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#d!==0&&!a(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!a(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!ae,this.updateAgeOnGet=!!_,this.updateAgeOnHas=!!x,this.ttlResolution=a(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=b||0,this.ttl){if(!a(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";l(Z)&&(t.add(Z),i("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,gc))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#N(){let f=new u(this.#l),y=new u(this.#l);this.#f=f,this.#w=y,this.#j=(m,_,x=e.now())=>{if(y[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=>{y[m]=f[m]!==0?e.now():0},this.#E=(m,_)=>{if(f[_]){let x=f[_],v=y[_];if(!x||!v)return;m.ttl=x,m.start=v,m.now=b||w();let E=m.now-v;m.remainingTTL=x-E}};let b=0,w=()=>{let m=e.now();if(this.ttlResolution>0){b=m;let _=setTimeout(()=>b=0,this.ttlResolution);_.unref&&_.unref()}return m};this.getRemainingTTL=m=>{let _=this.#n.get(m);if(_===void 0)return 0;let x=f[_],v=y[_];if(!x||!v)return 1/0;let E=(b||w())-v;return x-E},this.#p=m=>{let _=y[m],x=f[m];return!!x&&!!_&&(b||w())-_>x}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#$(){let f=new u(this.#l);this.#y=0,this.#v=f,this.#T=y=>{this.#y-=f[y],f[y]=0},this.#U=(y,b,w,m)=>{if(this.#t(b))return 0;if(!a(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(b,y),!a(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=(y,b,w)=>{if(f[y]=b,this.#d){let m=this.#d-f[y];for(;this.#y>m;)this.#R(!0)}this.#y+=f[y],w&&(w.entrySize=b,w.totalCalculatedSize=this.#y)}}#T=f=>{};#M=(f,y,b)=>{};#U=(f,y,b,w)=>{if(b||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 y=this.#o;!(!this.#B(y)||((f||!this.#p(y))&&(yield y),y===this.#a));)y=this.#h[y]}*#x({allowStale:f=this.allowStale}={}){if(this.#i)for(let y=this.#a;!(!this.#B(y)||((f||!this.#p(y))&&(yield y),y===this.#o));)y=this.#c[y]}#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 y=this.#r[f];y!==void 0&&!this.#t(this.#e[f])&&(yield y)}}*rkeys(){for(let f of this.#x()){let y=this.#r[f];y!==void 0&&!this.#t(this.#e[f])&&(yield y)}}*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,y={}){for(let b of this.#k()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&f(m,this.#r[b],this))return this.get(this.#r[b],y)}}forEach(f,y=this){for(let b of this.#k()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(y,m,this.#r[b],this)}}rforEach(f,y=this){for(let b of this.#x()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(y,m,this.#r[b],this)}}purgeStale(){let f=!1;for(let y of this.#x({allowStale:!0}))this.#p(y)&&(this.#S(this.#r[y],"expire"),f=!0);return f}info(f){let y=this.#n.get(f);if(y===void 0)return;let b=this.#e[y],w=this.#t(b)?b.__staleWhileFetching:b;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let _=this.#f[y],x=this.#w[y];if(_&&x){let v=_-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[y]),m}dump(){let f=[];for(let y of this.#k({allowStale:!0})){let b=this.#r[y],w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||b===void 0)continue;let _={value:m};if(this.#f&&this.#w){_.ttl=this.#f[y];let x=e.now()-this.#w[y];_.start=Math.floor(Date.now()-x)}this.#v&&(_.size=this.#v[y]),f.unshift([b,_])}return f}load(f){this.clear();for(let[y,b]of f){if(b.start){let w=Date.now()-b.start;b.start=e.now()-w}this.set(y,b.value,b)}}set(f,y,b={}){if(y===void 0)return this.delete(f),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:_=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=b,{noUpdateTTL:E=this.noUpdateTTL}=b,S=this.#U(f,y,b.size||0,x);if(this.maxEntrySize&&S>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(f,"set"),this;let I=this.#i===0?void 0:this.#n.get(f);if(I===void 0)I=this.#i===0?this.#o:this.#b.length!==0?this.#b.pop():this.#i===this.#l?this.#R(!1):this.#i,this.#r[I]=f,this.#e[I]=y,this.#n.set(f,I),this.#c[this.#o]=I,this.#h[I]=this.#o,this.#o=I,this.#i++,this.#M(I,S,v),v&&(v.set="add"),E=!1;else{this.#C(I);let P=this.#e[I];if(y!==P){if(this.#A&&this.#t(P)){P.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:O}=P;O!==void 0&&!_&&(this.#_&&this.#m?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]))}else _||(this.#_&&this.#m?.(P,f,"set"),this.#u&&this.#s?.push([P,f,"set"]));if(this.#T(I),this.#M(I,S,v),this.#e[I]=y,v){v.set="replace";let O=P&&this.#t(P)?P.__staleWhileFetching:P;O!==void 0&&(v.oldValue=O)}}else v&&(v.set="update")}if(w!==0&&!this.#f&&this.#N(),this.#f&&(E||this.#j(I,w,m),v&&this.#E(v,I)),!_&&this.#u&&this.#s){let P=this.#s,O;for(;O=P?.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,y;for(;y=f?.shift();)this.#g?.(...y)}}}#R(f){let y=this.#a,b=this.#r[y],w=this.#e[y];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(w,b,"evict"),this.#u&&this.#s?.push([w,b,"evict"])),this.#T(y),f&&(this.#r[y]=void 0,this.#e[y]=void 0,this.#b.push(y)),this.#i===1?(this.#a=this.#o=0,this.#b.length=0):this.#a=this.#c[y],this.#n.delete(b),this.#i--,y}has(f,y={}){let{updateAgeOnHas:b=this.updateAgeOnHas,status:w}=y,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 b&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(f,y={}){let{allowStale:b=this.allowStale}=y,w=this.#n.get(f);if(w===void 0||!b&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#L(f,y,b,w){let m=y===void 0?void 0:this.#e[y];if(this.#t(m))return m;let _=new n,{signal:x}=b;x?.addEventListener("abort",()=>_.abort(x.reason),{signal:_.signal});let v={signal:_.signal,options:b,context:w},E=(T,q=!1)=>{let{aborted:D}=_.signal,U=b.ignoreFetchAbort&&T!==void 0;if(b.status&&(D&&!q?(b.status.fetchAborted=!0,b.status.fetchError=_.signal.reason,U&&(b.status.fetchAbortIgnored=!0)):b.status.fetchResolved=!0),D&&!U&&!q)return I(_.signal.reason);let ae=O;return this.#e[y]===O&&(T===void 0?ae.__staleWhileFetching?this.#e[y]=ae.__staleWhileFetching:this.#S(f,"fetch"):(b.status&&(b.status.fetchUpdated=!0),this.set(f,T,v.options))),T},S=T=>(b.status&&(b.status.fetchRejected=!0,b.status.fetchError=T),I(T)),I=T=>{let{aborted:q}=_.signal,D=q&&b.allowStaleOnFetchAbort,U=D||b.allowStaleOnFetchRejection,ae=U||b.noDeleteOnFetchRejection,Y=O;if(this.#e[y]===O&&(!ae||Y.__staleWhileFetching===void 0?this.#S(f,"fetch"):D||(this.#e[y]=Y.__staleWhileFetching)),U)return b.status&&Y.__staleWhileFetching!==void 0&&(b.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},P=(T,q)=>{let D=this.#P?.(f,m,v);D&&D instanceof Promise&&D.then(U=>T(U===void 0?void 0:U),q),_.signal.addEventListener("abort",()=>{(!b.ignoreFetchAbort||b.allowStaleOnFetchAbort)&&(T(void 0),b.allowStaleOnFetchAbort&&(T=U=>E(U,!0)))})};b.status&&(b.status.fetchDispatched=!0);let O=new Promise(P).then(E,S),j=Object.assign(O,{__abortController:_,__staleWhileFetching:m,__returned:void 0});return y===void 0?(this.set(f,j,{...v.options,status:void 0}),y=this.#n.get(f)):this.#e[y]=j,j}#t(f){if(!this.#A)return!1;let y=f;return!!y&&y instanceof Promise&&y.hasOwnProperty("__staleWhileFetching")&&y.__abortController instanceof n}async fetch(f,y={}){let{allowStale:b=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:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:j=this.allowStaleOnFetchAbort,context:T,forceRefresh:q=!1,status:D,signal:U}=y;if(!this.#A)return D&&(D.fetch="get"),this.get(f,{allowStale:b,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:D});let ae={allowStale:b,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:_,noDisposeOnSet:x,size:v,sizeCalculation:E,noUpdateTTL:S,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:j,ignoreFetchAbort:O,status:D,signal:U},Y=this.#n.get(f);if(Y===void 0){D&&(D.fetch="miss");let V=this.#L(f,Y,ae,T);return V.__returned=V}else{let V=this.#e[Y];if(this.#t(V)){let M=b&&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 F=this.#L(f,Y,ae,T),Z=F.__staleWhileFetching!==void 0&&b;return D&&(D.fetch=re?"stale":"refresh",Z&&re&&(D.returnedStale=!0)),Z?F.__staleWhileFetching:F.__returned=F}}async forceFetch(f,y={}){let b=await this.fetch(f,y);if(b===void 0)throw new Error("fetch() returned undefined");return b}memo(f,y={}){let b=this.#O;if(!b)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,..._}=y,x=this.get(f,_);if(!m&&x!==void 0)return x;let v=b(f,x,{options:_,context:w});return this.set(f,v,_),v}get(f,y={}){let{allowStale:b=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:_}=y,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?(_&&b&&v.__staleWhileFetching!==void 0&&(_.returnedStale=!0),b?v.__staleWhileFetching:void 0):(m||this.#S(f,"expire"),_&&b&&(_.returnedStale=!0),b?v:void 0)):(_&&(_.get="hit"),E?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else _&&(_.get="miss")}#D(f,y){this.#h[y]=f,this.#c[f]=y}#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,y){let b=!1;if(this.#i!==0){let w=this.#n.get(f);if(w!==void 0)if(b=!0,this.#i===1)this.#F(y);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,y),this.#u&&this.#s?.push([m,f,y])),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.#b.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.shift();)this.#g?.(...m)}return b}clear(){return this.#F("delete")}#F(f){for(let y of this.#x({allowStale:!0})){let b=this.#e[y];if(this.#t(b))b.__abortController.abort(new Error("deleted"));else{let w=this.#r[y];this.#_&&this.#m?.(b,w,f),this.#u&&this.#s?.push([b,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.#b.length=0,this.#y=0,this.#i=0,this.#u&&this.#s){let y=this.#s,b;for(;b=y?.shift();)this.#g?.(...b)}}};s.LRUCache=p}),mt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.ContainerIterator=s.Container=s.Base=void 0;var e=class{constructor(i=0){this.iteratorType=i}equals(i){return this.o===i.o}};s.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};s.Base=t;var r=class extends t{};s.Container=r}),hu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(i=[]){super(),this.S=[];let n=this;i.forEach(function(o){n.push(o)})}clear(){this.i=0,this.S=[]}push(i){return this.S.push(i),this.i+=1,this.i}pop(){if(this.i!==0)return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}},r=t;s.default=r}),fu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(i=[]){super(),this.j=0,this.q=[];let n=this;i.forEach(function(o){n.push(o)})}clear(){this.q=[],this.i=this.j=0}push(i){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let o=this.i;for(let l=0;l<o;++l)this.q[l]=this.q[this.j+l];this.j=0,this.q[this.i]=i}else this.q[this.j+this.i]=i;return++this.i}pop(){if(this.i===0)return;let i=this.q[this.j++];return this.i-=1,i}front(){if(this.i!==0)return this.q[this.j]}},r=t;s.default=r}),pu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(i=[],n=function(l,a){return l>a?-1:l<a?1:0},o=!0){if(super(),this.v=n,Array.isArray(i))this.C=o?[...i]:i;else{this.C=[];let a=this;i.forEach(function(c){a.C.push(c)})}this.i=this.C.length;let l=this.i>>1;for(let a=this.i-1>>1;a>=0;--a)this.k(a,l)}m(i){let n=this.C[i];for(;i>0;){let o=i-1>>1,l=this.C[o];if(this.v(l,n)<=0)break;this.C[i]=l,i=o}this.C[i]=n}k(i,n){let o=this.C[i];for(;i<n;){let l=i<<1|1,a=l+1,c=this.C[l];if(a<this.i&&this.v(c,this.C[a])>0&&(l=a,c=this.C[a]),this.v(c,o)>=0)break;this.C[i]=c,i=l}this.C[i]=o}clear(){this.i=0,this.C.length=0}push(i){this.C.push(i),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let i=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),i}top(){return this.C[0]}find(i){return this.C.indexOf(i)>=0}remove(i){let n=this.C.indexOf(i);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(i){let n=this.C.indexOf(i);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;s.default=r}),bi=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Container{},r=t;s.default=r}),gt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),ks=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.RandomIterator=void 0;var e=mt(),t=gt(),r=class extends e.ContainerIterator{constructor(i,n){super(n),this.o=i,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(i){this.container.setElementByPos(this.o,i)}};s.RandomIterator=r}),mu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=r(bi()),t=ks();function r(l){return l&&l.t?l:{default:l}}var i=class yc extends t.RandomIterator{constructor(a,c,u){super(a,u),this.container=c}copy(){return new yc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(l=[],a=!0){if(super(),Array.isArray(l))this.J=a?[...l]:l,this.i=l.length;else{this.J=[];let c=this;l.forEach(function(u){c.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new i(0,this)}end(){return new i(this.i,this)}rBegin(){return new i(this.i-1,this,1)}rEnd(){return new i(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;return this.J[l]}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;return this.J.splice(l,1),this.i-=1,this.i}eraseElementByValue(l){let a=0;for(let c=0;c<this.i;++c)this.J[c]!==l&&(this.J[a++]=this.J[c]);return this.i=this.J.length=a,this.i}eraseElementByIterator(l){let a=l.o;return l=l.next(),this.eraseElementByPos(a),l}pushBack(l){return this.J.push(l),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(l,a){if(l<0||l>this.i-1)throw new RangeError;this.J[l]=a}insert(l,a,c=1){if(l<0||l>this.i)throw new RangeError;return this.J.splice(l,0,...new Array(c).fill(a)),this.i+=c,this.i}find(l){for(let a=0;a<this.i;++a)if(this.J[a]===l)return new i(a,this);return this.end()}reverse(){this.J.reverse()}unique(){let l=1;for(let a=1;a<this.i;++a)this.J[a]!==this.J[a-1]&&(this.J[l++]=this.J[a]);return this.i=this.J.length=l,this.i}sort(l){this.J.sort(l)}forEach(l){for(let a=0;a<this.i;++a)l(this.J[a],a,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},o=n;s.default=o}),gu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=i(bi()),t=mt(),r=gt();function i(a){return a&&a.t?a:{default:a}}var n=class bc 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 bc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(a=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;a.forEach(function(u){c.pushBack(u)})}V(a){let{L:c,B:u}=a;c.B=u,u.L=c,a===this.p&&(this.p=u),a===this._&&(this._=c),this.i-=1}G(a,c){let u=c.B,d={l:a,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(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return c.l}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return this.V(c),this.i}eraseElementByValue(a){let c=this.p;for(;c!==this.h;)c.l===a&&this.V(c),c=c.B;return this.i}eraseElementByIterator(a){let c=a.o;return c===this.h&&(0,r.throwIteratorAccessError)(),a=a.next(),this.V(c),a}pushBack(a){return this.G(a,this._),this.i}popBack(){if(this.i===0)return;let a=this._.l;return this.V(this._),a}pushFront(a){return this.G(a,this.h),this.i}popFront(){if(this.i===0)return;let a=this.p.l;return this.V(this.p),a}setElementByPos(a,c){if(a<0||a>this.i-1)throw new RangeError;let u=this.p;for(;a--;)u=u.B;u.l=c}insert(a,c,u=1){if(a<0||a>this.i)throw new RangeError;if(u<=0)return this.i;if(a===0)for(;u--;)this.pushFront(c);else if(a===this.i)for(;u--;)this.pushBack(c);else{let d=this.p;for(let g=1;g<a;++g)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(a){let c=this.p;for(;c!==this.h;){if(c.l===a)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let a=this.p,c=this._,u=0;for(;u<<1<this.i;){let d=a.l;a.l=c.l,c.l=d,a=a.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let a=this.p;for(;a!==this.h;){let c=a;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;a.B=c.B,a.B.L=a,a=a.B}return this.i}sort(a){if(this.i<=1)return;let c=[];this.forEach(function(d){c.push(d)}),c.sort(a);let u=this.p;c.forEach(function(d){u.l=d,u=u.B})}merge(a){let c=this;if(this.i===0)a.forEach(function(u){c.pushBack(u)});else{let u=this.p;a.forEach(function(d){for(;u!==c.h&&u.l<=d;)u=u.B;c.G(d,u.L)})}return this.i}forEach(a){let c=this.p,u=0;for(;c!==this.h;)a(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let a=this.p;for(;a!==this.h;)yield a.l,a=a.B}).bind(this)()}},l=o;s.default=l}),yu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=r(bi()),t=ks();function r(l){return l&&l.t?l:{default:l}}var i=class vc extends t.RandomIterator{constructor(a,c,u){super(a,u),this.container=c}copy(){return new vc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(l=[],a=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof l.length=="number")return l.length;if(typeof l.size=="number")return l.size;if(typeof l.size=="function")return l.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=a,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;l.forEach(function(p){d.pushBack(p)})}T(){let l=[],a=Math.max(this.P>>1,1);for(let c=0;c<a;++c)l[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)l[l.length]=this.A[c];for(let c=0;c<this.R;++c)l[l.length]=this.A[c];l[l.length]=[...this.A[this.R]],this.j=a,this.R=l.length-1;for(let c=0;c<a;++c)l[l.length]=new Array(this.F);this.A=l,this.P=l.length}O(l){let a=this.D+l+1,c=a%this.F,u=c-1,d=this.j+(a-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 i(0,this)}end(){return new i(this.i,this)}rBegin(){return new i(this.i-1,this,1)}rEnd(){return new i(-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(l){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]=l,this.i}popBack(){if(this.i===0)return;let l=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,l}pushFront(l){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]=l,this.i}popFront(){if(this.i===0)return;let l=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,l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let{curNodeBucketIndex:a,curNodePointerIndex:c}=this.O(l);return this.A[a][c]}setElementByPos(l,a){if(l<0||l>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(l);this.A[c][u]=a}insert(l,a,c=1){if(l<0||l>this.i)throw new RangeError;if(l===0)for(;c--;)this.pushFront(a);else if(l===this.i)for(;c--;)this.pushBack(a);else{let u=[];for(let d=l;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(l-1);for(let d=0;d<c;++d)this.pushBack(a);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(l){if(l<0)return this.clear(),0;let{curNodeBucketIndex:a,curNodePointerIndex:c}=this.O(l);return this.R=a,this.N=c,this.i=l+1,this.i}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;if(l===0)this.popFront();else if(l===this.i-1)this.popBack();else{let a=[];for(let u=l+1;u<this.i;++u)a.push(this.getElementByPos(u));this.cut(l),this.popBack();let c=this;a.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(l){if(this.i===0)return 0;let a=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==l&&a.push(d)}let c=a.length;for(let u=0;u<c;++u)this.setElementByPos(u,a[u]);return this.cut(c-1)}eraseElementByIterator(l){let a=l.o;return this.eraseElementByPos(a),l=l.next(),l}find(l){for(let a=0;a<this.i;++a)if(this.getElementByPos(a)===l)return new i(a,this);return this.end()}reverse(){let l=0,a=this.i-1;for(;l<a;){let c=this.getElementByPos(l);this.setElementByPos(l,this.getElementByPos(a)),this.setElementByPos(a,c),l+=1,a-=1}}unique(){if(this.i<=1)return this.i;let l=1,a=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==a&&(a=u,this.setElementByPos(l++,u))}for(;this.i>l;)this.popBack();return this.i}sort(l){let a=[];for(let c=0;c<this.i;++c)a.push(this.getElementByPos(c));a.sort(l);for(let c=0;c<this.i;++c)this.setElementByPos(c,a[c])}shrinkToFit(){if(this.i===0)return;let l=[];this.forEach(function(a){l.push(a)}),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 a=0;a<this.P;++a)this.A.push(new Array(this.F));for(let a=0;a<l.length;++a)this.pushBack(l[a])}forEach(l){for(let a=0;a<this.i;++a)l(this.getElementByPos(a),a,this)}[Symbol.iterator](){return(function*(){for(let l=0;l<this.i;++l)yield this.getElementByPos(l)}).bind(this)()}},o=n;s.default=o}),bu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.TreeNodeEnableIndex=s.TreeNode=void 0;var e=class{constructor(r,i){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=i}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 i=r.tt;for(;i.U===r;)r=i,i=r.tt;r=i}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let i=r.tt;for(;i.W===r;)r=i,i=r.tt;return r.W!==i?i:r}}te(){let r=this.tt,i=this.W,n=i.U;return r.tt===this?r.tt=i:r.U===this?r.U=i:r.W=i,i.tt=r,i.U=this,this.tt=i,this.W=n,n&&(n.tt=this),i}se(){let r=this.tt,i=this.U,n=i.W;return r.tt===this?r.tt=i:r.U===this?r.U=i:r.W=i,i.tt=r,i.W=this,this.tt=i,this.U=n,n&&(n.tt=this),i}};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}),xs=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=bu(),t=mt(),r=gt(),i=class extends t.Container{constructor(o=function(a,c){return a<c?-1:a>c?1:0},l=!1){super(),this.Y=void 0,this.v=o,l?(this.re=e.TreeNodeEnableIndex,this.M=function(a,c,u){let d=this.ne(a,c,u);if(d){let p=d.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let g=this.he(d);if(g){let{parentNode:f,grandParent:y,curNode:b}=g;f.ie(),y.ie(),b.ie()}}return this.i},this.V=function(a){let c=this.fe(a);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(a,c,u){let d=this.ne(a,c,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(o,l){let a=this.h;for(;o;){let c=this.v(o.u,l);if(c<0)o=o.W;else if(c>0)a=o,o=o.U;else return o}return a}Z(o,l){let a=this.h;for(;o;)this.v(o.u,l)<=0?o=o.W:(a=o,o=o.U);return a}$(o,l){let a=this.h;for(;o;){let c=this.v(o.u,l);if(c<0)a=o,o=o.W;else if(c>0)o=o.U;else return o}return a}rr(o,l){let a=this.h;for(;o;)this.v(o.u,l)<0?(a=o,o=o.W):o=o.U;return a}ue(o){for(;;){let l=o.tt;if(l===this.h)return;if(o.ee===1){o.ee=0;return}if(o===l.U){let a=l.W;if(a.ee===1)a.ee=0,l.ee=1,l===this.Y?this.Y=l.te():l.te();else if(a.W&&a.W.ee===1){a.ee=l.ee,l.ee=0,a.W.ee=0,l===this.Y?this.Y=l.te():l.te();return}else a.U&&a.U.ee===1?(a.ee=1,a.U.ee=0,a.se()):(a.ee=1,o=l)}else{let a=l.U;if(a.ee===1)a.ee=0,l.ee=1,l===this.Y?this.Y=l.se():l.se();else if(a.U&&a.U.ee===1){a.ee=l.ee,l.ee=0,a.U.ee=0,l===this.Y?this.Y=l.se():l.se();return}else a.W&&a.W.ee===1?(a.ee=1,a.W.ee=0,a.te()):(a.ee=1,o=l)}}}fe(o){if(this.i===1)return this.clear(),this.h;let l=o;for(;l.U||l.W;){if(l.W)for(l=l.W;l.U;)l=l.U;else l=l.U;[o.u,l.u]=[l.u,o.u],[o.l,l.l]=[l.l,o.l],o=l}this.h.U===l?this.h.U=l.tt:this.h.W===l&&(this.h.W=l.tt),this.ue(l);let a=l.tt;return l===a.U?a.U=void 0:a.W=void 0,this.i-=1,this.Y.ee=0,a}oe(o,l){return o===void 0?!1:this.oe(o.U,l)||l(o)?!0:this.oe(o.W,l)}he(o){for(;;){let l=o.tt;if(l.ee===0)return;let a=l.tt;if(l===a.U){let c=a.W;if(c&&c.ee===1){if(c.ee=l.ee=0,a===this.Y)return;a.ee=1,o=a;continue}else if(o===l.W){if(o.ee=0,o.U&&(o.U.tt=l),o.W&&(o.W.tt=a),l.W=o.U,a.U=o.W,o.U=l,o.W=a,a===this.Y)this.Y=o,this.h.tt=o;else{let u=a.tt;u.U===a?u.U=o:u.W=o}return o.tt=a.tt,l.tt=o,a.tt=o,a.ee=1,{parentNode:l,grandParent:a,curNode:o}}else l.ee=0,a===this.Y?this.Y=a.se():a.se(),a.ee=1}else{let c=a.U;if(c&&c.ee===1){if(c.ee=l.ee=0,a===this.Y)return;a.ee=1,o=a;continue}else if(o===l.U){if(o.ee=0,o.U&&(o.U.tt=a),o.W&&(o.W.tt=l),a.W=o.U,l.U=o.W,o.U=a,o.W=l,a===this.Y)this.Y=o,this.h.tt=o;else{let u=a.tt;u.U===a?u.U=o:u.W=o}return o.tt=a.tt,l.tt=o,a.tt=o,a.ee=1,{parentNode:l,grandParent:a,curNode:o}}else l.ee=0,a===this.Y?this.Y=a.te():a.te(),a.ee=1}return}}ne(o,l,a){if(this.Y===void 0){this.i+=1,this.Y=new this.re(o,l),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,o);if(d===0){u.l=l;return}else if(d>0)u.U=new this.re(o,l),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,g=this.v(p.u,o);if(g===0){p.l=l;return}else if(g<0)p.W=new this.re(o,l),p.W.tt=p,c=p.W,this.h.W=c;else{if(a!==void 0){let f=a.o;if(f!==this.h){let y=this.v(f.u,o);if(y===0){f.l=l;return}else if(y>0){let b=f.L(),w=this.v(b.u,o);if(w===0){b.l=l;return}else w<0&&(c=new this.re(o,l),b.W===void 0?(b.W=c,c.tt=b):(f.U=c,c.tt=f))}}}if(c===void 0)for(c=this.Y;;){let f=this.v(c.u,o);if(f>0){if(c.U===void 0){c.U=new this.re(o,l),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(o,l),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=l;return}}}}return this.i+=1,c}I(o,l){for(;o;){let a=this.v(o.u,l);if(a<0)o=o.W;else if(a>0)o=o.U;else return o}return o||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(o,l){let a=o.o;if(a===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return a.u=l,!0;if(a===this.h.U)return this.v(a.B().u,l)>0?(a.u=l,!0):!1;if(a===this.h.W)return this.v(a.L().u,l)<0?(a.u=l,!0):!1;let c=a.L().u;if(this.v(c,l)>=0)return!1;let u=a.B().u;return this.v(u,l)<=0?!1:(a.u=l,!0)}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let l=0,a=this;return this.oe(this.Y,function(c){return o===l?(a.V(c),!0):(l+=1,!1)}),this.i}eraseElementByKey(o){if(this.i===0)return!1;let l=this.I(this.Y,o);return l===this.h?!1:(this.V(l),!0)}eraseElementByIterator(o){let l=o.o;l===this.h&&(0,r.throwIteratorAccessError)();let a=l.W===void 0;return o.iteratorType===0?a&&o.next():(!a||l.U===void 0)&&o.next(),this.V(l),o}forEach(o){let l=0;for(let a of this)o(a,l++,this)}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let l,a=0;for(let c of this){if(a===o){l=c;break}a+=1}return l}getHeight(){if(this.i===0)return 0;let o=function(l){return l?Math.max(o(l.U),o(l.W))+1:0};return o(this.Y)}},n=i;s.default=n}),Ss=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=gt(),r=class extends e.ContainerIterator{constructor(n,o,l){super(l),this.o=n,this.h=o,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,o=this.h.tt;if(n===this.h)return o?o.rt-1:0;let l=0;for(n.U&&(l+=n.U.rt);n!==o;){let a=n.tt;n===a.W&&(l+=1,a.U&&(l+=a.U.rt)),n=a}return l}},i=r;s.default=i}),vu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=i(xs()),t=i(Ss()),r=gt();function i(a){return a&&a.t?a:{default:a}}var n=class wc 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 wc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(a=[],c,u){super(c,u);let d=this;a.forEach(function(p){d.insert(p)})}*K(a){a!==void 0&&(yield*this.K(a.U),yield a.u,yield*this.K(a.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(a,c){return this.M(a,void 0,c)}find(a){let c=this.I(this.Y,a);return new n(c,this.h,this)}lowerBound(a){let c=this.X(this.Y,a);return new n(c,this.h,this)}upperBound(a){let c=this.Z(this.Y,a);return new n(c,this.h,this)}reverseLowerBound(a){let c=this.$(this.Y,a);return new n(c,this.h,this)}reverseUpperBound(a){let c=this.rr(this.Y,a);return new n(c,this.h,this)}union(a){let c=this;return a.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},l=o;s.default=l}),wu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=i(xs()),t=i(Ss()),r=gt();function i(a){return a&&a.t?a:{default:a}}var n=class _c 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 _c(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(a=[],c,u){super(c,u);let d=this;a.forEach(function(p){d.setElement(p[0],p[1])})}*K(a){a!==void 0&&(yield*this.K(a.U),yield[a.u,a.l],yield*this.K(a.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 a=this.h.U;return[a.u,a.l]}back(){if(this.i===0)return;let a=this.h.W;return[a.u,a.l]}lowerBound(a){let c=this.X(this.Y,a);return new n(c,this.h,this)}upperBound(a){let c=this.Z(this.Y,a);return new n(c,this.h,this)}reverseLowerBound(a){let c=this.$(this.Y,a);return new n(c,this.h,this)}reverseUpperBound(a){let c=this.rr(this.Y,a);return new n(c,this.h,this)}setElement(a,c,u){return this.M(a,c,u)}find(a){let c=this.I(this.Y,a);return new n(c,this.h,this)}getElementByKey(a){return this.I(this.Y,a).l}union(a){let c=this;return a.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},l=o;s.default=l}),Es=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"}}),As=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.HashContainerIterator=s.HashContainer=void 0;var e=mt(),t=i(Es()),r=gt();function i(l){return l&&l.t?l:{default:l}}var n=class extends e.ContainerIterator{constructor(l,a,c){super(c),this.o=l,this.h=a,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 o=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(l){let{L:a,B:c}=l;a.B=c,c.L=a,l===this.p&&(this.p=c),l===this._&&(this._=a),this.i-=1}M(l,a,c){c===void 0&&(c=(0,t.default)(l));let u;if(c){let d=l[this.HASH_TAG];if(d!==void 0)return this.H[d].l=a,this.i;Object.defineProperty(l,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:l,l:a,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[l];if(d)return d.l=a,this.i;u={u:l,l:a,L:this._,B:this.h},this.g[l]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(l,a){if(a===void 0&&(a=(0,t.default)(l)),a){let c=l[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[l]||this.h}clear(){let l=this.HASH_TAG;this.H.forEach(function(a){delete a.u[l]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(l,a){let c;if(a===void 0&&(a=(0,t.default)(l)),a){let u=l[this.HASH_TAG];if(u===void 0)return!1;delete l[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[l],c===void 0)return!1;delete this.g[l]}return this.V(c),!0}eraseElementByIterator(l){let a=l.o;return a===this.h&&(0,r.throwIteratorAccessError)(),this.V(a),l.next()}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let a=this.p;for(;l--;)a=a.B;return this.V(a),this.i}};s.HashContainer=o}),_u=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=As(),t=gt(),r=class kc extends e.HashContainerIterator{constructor(l,a,c,u){super(l,a,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new kc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(o=[]){super();let l=this;o.forEach(function(a){l.insert(a)})}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(o,l){return this.M(o,void 0,l)}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let l=this.p;for(;o--;)l=l.B;return l.u}find(o,l){let a=this.I(o,l);return new r(a,this.h,this)}forEach(o){let l=0,a=this.p;for(;a!==this.h;)o(a.u,l++,this),a=a.B}[Symbol.iterator](){return(function*(){let o=this.p;for(;o!==this.h;)yield o.u,o=o.B}).bind(this)()}},n=i;s.default=n}),ku=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=As(),t=i(Es()),r=gt();function i(a){return a&&a.t?a:{default:a}}var n=class xc 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 xc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.HashContainer{constructor(a=[]){super();let c=this;a.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(a,c,u){return this.M(a,c,u)}getElementByKey(a,c){if(c===void 0&&(c=(0,t.default)(a)),c){let d=a[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[a];return u?u.l:void 0}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return[c.u,c.l]}find(a,c){let u=this.I(a,c);return new n(u,this.h,this)}forEach(a){let c=0,u=this.p;for(;u!==this.h;)a([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let a=this.p;for(;a!==this.h;)yield[a.u,a.l],a=a.B}).bind(this)()}},l=o;s.default=l}),xu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),Object.defineProperty(s,"Deque",{enumerable:!0,get:function(){return o.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 a.default}}),Object.defineProperty(s,"OrderedSet",{enumerable:!0,get:function(){return l.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 i.default}});var e=d(hu()),t=d(fu()),r=d(pu()),i=d(mu()),n=d(gu()),o=d(yu()),l=d(vu()),a=d(wu()),c=d(_u()),u=d(ku());function d(p){return p&&p.t?p:{default:p}}}),Su=pe((s,e)=>{le(),ue(),ce();var t=xu().OrderedSet,r=pt()("number-allocator:trace"),i=pt()("number-allocator:error");function n(l,a){this.low=l,this.high=a}n.prototype.equals=function(l){return this.low===l.low&&this.high===l.high},n.prototype.compare=function(l){return this.low<l.low&&this.high<l.low?-1:l.low<this.low&&l.high<this.low?1:0};function o(l,a){if(!(this instanceof o))return new o(l,a);this.min=l,this.max=a,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}o.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},o.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let l=this.ss.begin(),a=l.pointer.low,c=l.pointer.high,u=a;return u+1<=c?this.ss.updateKeyByIterator(l,new n(a+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},o.prototype.use=function(l){let a=new n(l,l),c=this.ss.lowerBound(a);if(!c.equals(this.ss.end())){let u=c.pointer.low,d=c.pointer.high;return c.pointer.equals(a)?(this.ss.eraseElementByIterator(c),r("use():"+l),!0):u>l?!1:u===l?(this.ss.updateKeyByIterator(c,new n(u+1,d)),r("use():"+l),!0):d===l?(this.ss.updateKeyByIterator(c,new n(u,d-1)),r("use():"+l),!0):(this.ss.updateKeyByIterator(c,new n(l+1,d)),this.ss.insert(new n(u,l-1)),r("use():"+l),!0)}return r("use():failed"),!1},o.prototype.free=function(l){if(l<this.min||l>this.max){i("free():"+l+" is out of range");return}let a=new n(l,l),c=this.ss.upperBound(a);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(a);return}c.pre();let u=c.pointer.high;c.pointer.high+1===l?this.ss.updateKeyByIterator(c,new n(u,l)):this.ss.insert(a)}else if(c.equals(this.ss.begin()))if(l+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(l,u))}else this.ss.insert(a);else{let u=c.pointer.low,d=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===l?l+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,d))):this.ss.updateKeyByIterator(c,new n(p,l)):l+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(l,d))):this.ss.insert(a)}r("free():"+l)},o.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},o.prototype.intervalCount=function(){return this.ss.size()},o.prototype.dump=function(){console.log("length:"+this.ss.size());for(let l of this.ss)console.log(l)},e.exports=o}),Is=pe((s,e)=>{le(),ue(),ce();var t=Su();e.exports.NumberAllocator=t}),Eu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=du(),t=Is(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(i){i>0&&(this.aliasToTopic=new e.LRUCache({max:i}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,i),this.max=i,this.length=0)}put(i,n){if(n===0||n>this.max)return!1;let o=this.aliasToTopic.get(n);return o&&delete this.topicToAlias[o],this.aliasToTopic.set(n,i),this.topicToAlias[i]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(i){return this.aliasToTopic.get(i)}getAliasByTopic(i){let n=this.topicToAlias[i];return typeof n<"u"&&this.aliasToTopic.get(n),n}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){return this.numberAllocator.firstVacant()||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}};s.default=r}),Au=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(s,"__esModule",{value:!0});var t=br(),r=e(Eu()),i=$t(),n=(o,l)=>{o.log("_handleConnack");let{options:a}=o,c=a.protocolVersion===5?l.reasonCode:l.returnCode;if(clearTimeout(o.connackTimer),delete o.topicAliasSend,l.properties){if(l.properties.topicAliasMaximum){if(l.properties.topicAliasMaximum>65535){o.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}l.properties.topicAliasMaximum>0&&(o.topicAliasSend=new r.default(l.properties.topicAliasMaximum))}l.properties.serverKeepAlive&&a.keepalive&&(a.keepalive=l.properties.serverKeepAlive),l.properties.maximumPacketSize&&(a.properties||(a.properties={}),a.properties.maximumPacketSize=l.properties.maximumPacketSize)}if(c===0)o.reconnecting=!1,o._onConnect(l);else if(c>0){let u=new i.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);o.emit("error",u),o.options.reconnectOnConnackError&&o._cleanUp(!0)}};s.default=n}),Iu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(t,r,i)=>{t.log("handling pubrel packet");let n=typeof i<"u"?i:t.noop,{messageId:o}=r,l={cmd:"pubcomp",messageId:o};t.incomingStore.get(r,(a,c)=>{a?t._sendPacket(l,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(l,n)}))})};s.default=e}),Tu=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(lu()),r=e(uu()),i=e(Au()),n=e(br()),o=e(Iu()),l=(a,c,u)=>{let{options:d}=a;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<c.length)return a.emit("error",new Error(`exceeding packets size ${c.cmd}`)),a.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),a;switch(a.log("_handlePacket :: emitting packetreceive"),a.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(a,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":a.reschedulePing(),(0,n.default)(a,c),u();break;case"pubrel":a.reschedulePing(),(0,o.default)(a,c,u);break;case"connack":(0,i.default)(a,c),u();break;case"auth":a.reschedulePing(),(0,r.default)(a,c),u();break;case"pingresp":a.log("_handlePacket :: received pingresp"),a.reschedulePing(!0),u();break;case"disconnect":a.emit("disconnect",c),u();break;default:a.log("_handlePacket :: unknown command"),u();break}};s.default=l}),Ts=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=class{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let t=this.nextId++;return this.nextId===65536&&(this.nextId=1),t}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(t){return!0}deallocate(t){}clear(){}};s.default=e}),Cu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=class{aliasToTopic;max;length;constructor(t){this.aliasToTopic={},this.max=t}put(t,r){return r===0||r>this.max?!1:(this.aliasToTopic[r]=t,this.length=Object.keys(this.aliasToTopic).length,!0)}getTopicByAlias(t){return this.aliasToTopic[t]}clear(){this.aliasToTopic={}}};s.default=e}),Pu=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(s,"__esModule",{value:!0}),s.TypedEventEmitter=void 0;var t=e((Tt(),Re(wt))),r=$t(),i=class{};s.TypedEventEmitter=i,(0,r.applyMixin)(i,t.default)}),vr=pe((s,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ou=pe((s,e)=>{le(),ue(),ce();var t=vr().default;function r(i,n){if(t(i)!="object"||!i)return i;var o=i[Symbol.toPrimitive];if(o!==void 0){var l=o.call(i,n||"default");if(t(l)!="object")return l;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(i)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Mu=pe((s,e)=>{le(),ue(),ce();var t=vr().default,r=Ou();function i(n){var o=r(n,"string");return t(o)=="symbol"?o:o+""}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),Ru=pe((s,e)=>{le(),ue(),ce();var t=Mu();function r(i,n,o){return(n=t(n))in i?Object.defineProperty(i,n,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[n]=o,i}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Lu=pe((s,e)=>{le(),ue(),ce();function t(r){if(Array.isArray(r))return r}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Nu=pe((s,e)=>{le(),ue(),ce();function t(r,i){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var o,l,a,c,u=[],d=!0,p=!1;try{if(a=(n=n.call(r)).next,i===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(o=a.call(n)).done)&&(u.push(o.value),u.length!==i);d=!0);}catch(g){p=!0,l=g}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw l}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ju=pe((s,e)=>{le(),ue(),ce();function t(r,i){(i==null||i>r.length)&&(i=r.length);for(var n=0,o=Array(i);n<i;n++)o[n]=r[n];return o}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Uu=pe((s,e)=>{le(),ue(),ce();var t=ju();function r(i,n){if(i){if(typeof i=="string")return t(i,n);var o={}.toString.call(i).slice(8,-1);return o==="Object"&&i.constructor&&(o=i.constructor.name),o==="Map"||o==="Set"?Array.from(i):o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?t(i,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Bu=pe((s,e)=>{le(),ue(),ce();function t(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
3
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Du=pe((s,e)=>{le(),ue(),ce();var t=Lu(),r=Nu(),i=Uu(),n=Bu();function o(l,a){return t(l)||r(l,a)||i(l,a)||n()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Cs=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(s,function(t){var r=function(g){return function(f){var y=g(f);return f.add(y),y}},i=function(g){return function(f,y){return g.set(f,y),y}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,l=o*2,a=function(g,f){return function(y){var b=f.get(y),w=b===void 0?y.size:b<l?b+1:0;if(!y.has(w))return g(y,w);if(y.size<o){for(;y.has(w);)w=Math.floor(Math.random()*l);return g(y,w)}if(y.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;y.has(w);)w=Math.floor(Math.random()*n);return g(y,w)}},c=new WeakMap,u=i(c),d=a(u,c),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),Fu=pe((s,e)=>{le(),ue(),ce();function t(i,n,o,l,a,c,u){try{var d=i[c](u),p=d.value}catch(g){return void o(g)}d.done?n(p):Promise.resolve(p).then(l,a)}function r(i){return function(){var n=this,o=arguments;return new Promise(function(l,a){var c=i.apply(n,o);function u(p){t(c,l,a,u,d,"next",p)}function d(p){t(c,l,a,u,d,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ps=pe((s,e)=>{le(),ue(),ce();function t(r,i){this.v=r,this.k=i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Os=pe((s,e)=>{le(),ue(),ce();function t(r,i,n,o){var l=Object.defineProperty;try{l({},"",{})}catch{l=0}e.exports=t=function(a,c,u,d){function p(g,f){t(a,g,function(y){return this._invoke(g,f,y)})}c?l?l(a,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):a[c]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,i,n,o)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ms=pe((s,e)=>{le(),ue(),ce();var t=Os();function r(){var i,n,o=typeof Symbol=="function"?Symbol:{},l=o.iterator||"@@iterator",a=o.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,I,P){var O,j,T,q=0,D=P||[],U=!1,ae={p:0,n:0,v:i,a:Y,f:Y.bind(i,4),d:function(V,re){return O=V,j=0,T=i,ae.n=re,u}};function Y(V,re){for(j=V,T=re,n=0;!U&&q&&!F&&n<D.length;n++){var F,Z=D[n],M=ae.p,Q=Z[2];V>3?(F=Q===re)&&(T=Z[(j=Z[4])?5:(j=3,3)],Z[4]=Z[5]=i):Z[0]<=M&&((F=V<2&&M<Z[1])?(j=0,ae.v=re,ae.n=Z[1]):M<Q&&(F=V<3||Z[0]>re||re>Q)&&(Z[4]=V,Z[5]=re,ae.n=Q,j=0))}if(F||V>1)return u;throw U=!0,re}return function(V,re,F){if(q>1)throw TypeError("Generator is already running");for(U&&re===1&&Y(re,F),j=re,T=F;(n=j<2?i:T)||!U;){O||(j?j<3?(j>1&&(ae.n=-1),Y(j,T)):ae.n=T:ae.v=T);try{if(q=2,O){if(j||(V="next"),n=O[V]){if(!(n=n.call(O,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,j<2&&(j=0)}else j===1&&(n=O.return)&&n.call(O),j<2&&(T=TypeError("The iterator does not provide a '"+V+"' method"),j=1);O=i}else if((n=(U=ae.n<0)?T:S.call(I,ae))!==u)break}catch(Z){O=i,j=1,T=Z}finally{q=1}}return{value:n,done:U}}})(w,_,x),!0),E}var u={};function d(){}function p(){}function g(){}n=Object.getPrototypeOf;var f=[][l]?n(n([][l]())):(t(n={},l,function(){return this}),n),y=g.prototype=d.prototype=Object.create(f);function b(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,a,"GeneratorFunction")),w.prototype=Object.create(y),w}return p.prototype=g,t(y,"constructor",g),t(g,"constructor",p),p.displayName="GeneratorFunction",t(g,a,"GeneratorFunction"),t(y),t(y,a,"Generator"),t(y,l,function(){return this}),t(y,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:b}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Rs=pe((s,e)=>{le(),ue(),ce();var t=Ps(),r=Os();function i(n,o){function l(c,u,d,p){try{var g=n[c](u),f=g.value;return f instanceof t?o.resolve(f.v).then(function(y){l("next",y,d,p)},function(y){l("throw",y,d,p)}):o.resolve(f).then(function(y){g.value=y,d(g)},function(y){return l("throw",y,d,p)})}catch(y){p(y)}}var a;this.next||(r(i.prototype),r(i.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function p(){return new o(function(g,f){l(c,d,g,f)})}return a=a?a.then(p,p):p()},!0)}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),Ls=pe((s,e)=>{le(),ue(),ce();var t=Ms(),r=Rs();function i(n,o,l,a,c){return new r(t().w(n,o,l,a),c||Promise)}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),$u=pe((s,e)=>{le(),ue(),ce();var t=Ls();function r(i,n,o,l,a){var c=t(i,n,o,l,a);return c.next().then(function(u){return u.done?u.value:c.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),qu=pe((s,e)=>{le(),ue(),ce();function t(r){var i=Object(r),n=[];for(var o in i)n.unshift(o);return function l(){for(;n.length;)if((o=n.pop())in i)return l.value=o,l.done=!1,l;return l.done=!0,l}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Hu=pe((s,e)=>{le(),ue(),ce();var t=vr().default;function r(i){if(i!=null){var n=i[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],o=0;if(n)return n.call(i);if(typeof i.next=="function")return i;if(!isNaN(i.length))return{next:function(){return i&&o>=i.length&&(i=void 0),{value:i&&i[o++],done:!i}}}}throw new TypeError(t(i)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Wu=pe((s,e)=>{le(),ue(),ce();var t=Ps(),r=Ms(),i=$u(),n=Ls(),o=Rs(),l=qu(),a=Hu();function c(){var u=r(),d=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(b){var w=typeof b=="function"&&b.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function y(b){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,a(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 b.call(this,w)}finally{_.p=w.prev,_.n=w.next}}}return(e.exports=c=function(){return{wrap:function(b,w,m,_){return u.w(y(b),w,m,_&&_.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(b,w){return new t(b,w)},AsyncIterator:o,async:function(b,w,m,_,x){return(g(w)?n:i)(y(b),w,m,_,x)},keys:l,values:a}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),zu=pe((s,e)=>{le(),ue(),ce();var t=Wu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),Vu=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,Ru(),Du(),Cs(),Fu(),zu()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.brokerFactory={},t._defineProperty,t._slicedToArray,t.fastUniqueNumbers,t._asyncToGenerator,t._regeneratorRuntime))})(s,function(t,r,i,n,o,l){var a=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 o(l.mark(function v(){var E,S,I,P;return l.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return E=new MessageChannel,S=E.port1,I=E.port2,O.next=1,x("connect",{port:S},[S]);case 1:return P=O.sent,c.set(I,P),O.abrupt("return",I);case 2:case"end":return O.stop()}},v)}))},disconnect:function(_){var x=_.call;return(function(){var v=o(l.mark(function E(S){var I;return l.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:if(I=c.get(S),I!==void 0){P.next=1;break}throw new Error("The given port is not connected.");case 1:return P.next=2,x("disconnect",{portId:I});case 2:case"end":return P.stop()}},E)}));return function(E){return v.apply(this,arguments)}})()},isSupported:function(_){var x=_.call;return function(){return x("isSupported")}}})};function g(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?g(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):g(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var y=new WeakMap,b=function(m){if(y.has(m))return y.get(m);var _=new Map;return y.set(m,_),_},w=function(m){var _=p(m);return function(x){var v=b(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))}}),a(x)&&x.start();for(var E=function(D){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(Y,V){var re=n.generateUniqueNumber(v);v.set(re,{reject:V,resolve:Y}),U===null?x.postMessage({id:re,method:D},ae):x.postMessage({id:re,method:D,params:U},ae)})},S=function(D,U){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:D,params:U},ae)},I={},P=0,O=Object.entries(_);P<O.length;P++){var j=i(O[P],2),T=j[0],q=j[1];I=f(f({},I),{},r({},T,q({call:E,notify:S})))}return f({},I)}};t.createBroker=w})}),Gu=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,vr(),Vu(),Cs()):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,i,n){var o=new Map([[0,null]]),l=new Map([[0,null]]),a=i.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(o.get(p))==="symbol"&&(o.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){o.delete(p)}))}},clearTimeout:function(u){var d=u.call;return function(p){r(l.get(p))==="symbol"&&(l.set(p,null),d("clear",{timerId:p,timerType:"timeout"}).then(function(){l.delete(p)}))}},setInterval:function(u){var d=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,y=new Array(f>2?f-2:0),b=2;b<f;b++)y[b-2]=arguments[b];var w=Symbol(),m=n.generateUniqueNumber(o);o.set(m,w);var _=function(){return d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=o.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===w&&(p.apply(void 0,y),o.get(m)===w&&_())})};return _(),m}},setTimeout:function(u){var d=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,y=new Array(f>2?f-2:0),b=2;b<f;b++)y[b-2]=arguments[b];var w=Symbol(),m=n.generateUniqueNumber(l);return l.set(m,w),d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var _=l.get(m);if(_===void 0)throw new Error("The timer is in an undefined state.");_===w&&(l.delete(m),p.apply(void 0,y))}),m}}}),c=function(u){var d=new Worker(u);return a(d)};t.load=c,t.wrap=a})}),Ku=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,Gu()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(s,function(t,r){var i=function(d,p){var g=null;return function(){if(g!==null)return g;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),y=URL.createObjectURL(f);return g=d(y),setTimeout(function(){return URL.revokeObjectURL(y)}),g}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,o=i(r.load,n),l=function(d){return o().clearInterval(d)},a=function(d){return o().clearTimeout(d)},c=function(){var d;return(d=o()).setInterval.apply(d,arguments)},u=function(){var d;return(d=o()).setTimeout.apply(d,arguments)};t.clearInterval=l,t.clearTimeout=a,t.setInterval=c,t.setTimeout=u})}),wr=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&&Le?.versions?!Object.prototype.hasOwnProperty.call(Le.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",i=e()||t()||r();s.isWebWorker=t(),s.isReactNativeBrowser=r(),s.default=i}),Yu=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(c,u,d,p){p===void 0&&(p=d);var g=Object.getOwnPropertyDescriptor(u,d);(!g||("get"in g?!u.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,p,g)}:function(c,u,d,p){p===void 0&&(p=d),c[p]=u[d]}),t=s&&s.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=s&&s.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(d){var p=[];for(var g in d)Object.prototype.hasOwnProperty.call(d,g)&&(p[p.length]=g);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var p=c(u),g=0;g<p.length;g++)p[g]!=="default"&&e(d,u,p[g]);return t(d,u),d}})();Object.defineProperty(s,"__esModule",{value:!0});var i=Ku(),n=r(wr()),o={set:i.setInterval,clear:i.clearInterval},l={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},a=c=>{switch(c){case"native":return l;case"worker":return o;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?o:l}};s.default=a}),Ns=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=e(Yu()),r=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(i,n){this.client=i,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(i.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(i){if(i*=1e3,isNaN(i)||i<=0||i>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${i}`);this._keepalive=i,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${i}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let i=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+i,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}),vi=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(v,E,S,I){I===void 0&&(I=S);var P=Object.getOwnPropertyDescriptor(E,S);(!P||("get"in P?!E.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return E[S]}}),Object.defineProperty(v,I,P)}:function(v,E,S,I){I===void 0&&(I=S),v[I]=E[S]}),t=s&&s.__setModuleDefault||(Object.create?function(v,E){Object.defineProperty(v,"default",{enumerable:!0,value:E})}:function(v,E){v.default=E}),r=s&&s.__importStar||(function(){var v=function(E){return v=Object.getOwnPropertyNames||function(S){var I=[];for(var P in S)Object.prototype.hasOwnProperty.call(S,P)&&(I[I.length]=P);return I},v(E)};return function(E){if(E&&E.__esModule)return E;var S={};if(E!=null)for(var I=v(E),P=0;P<I.length;P++)I[P]!=="default"&&e(S,E,I[P]);return t(S,E),S}})(),i=s&&s.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(s,"__esModule",{value:!0});var n=i(ou()),o=Pt(),l=i(au()),a=i(pt()),c=r(ws()),u=i(_s()),d=i(Tu()),p=i(Ts()),g=i(Cu()),f=$t(),y=Pu(),b=i(Ns()),w=r(wr()),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 Lo extends y.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 I in _)typeof this.options[I]>"u"?this.options[I]=_[I]:this.options[I]=S[I];this.log=this.options.log||(0,a.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",Lo.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:Lo.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 g.default(S.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,P=()=>{let O=I.shift();this.log("deliver :: entry %o",O);let j=null;if(!O){this._resubscribe();return}j=O.packet,this.log("deliver :: call _sendPacket for %o",j);let T=!0;j.messageId&&j.messageId!==0&&(this.messageIdProvider.register(j.messageId)||(T=!1)),T?this._sendPacket(j,q=>{O.cb&&O.cb(q),P()}):(this.log("messageId: %d has already used. The message is skipped and removed.",j.messageId),P())};this.log("connect :: sending queued packets"),P()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(E,S){S()}handleMessage(E,S){S()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let E=new o.Writable,S=n.default.parser(this.options),I=null,P=[];this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting&&(this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1),this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),S.on("packet",D=>{this.log("parser :: on packet push to packets array."),P.push(D)});let O=()=>{this.log("work :: getting next packet in queue");let D=P.shift();if(D)this.log("work :: packet pulled from queue"),(0,d.default)(this,D,j);else{this.log("work :: no packets in queue");let U=I;I=null,this.log("work :: done flag is %s",!!U),U&&U()}},j=()=>{if(P.length)(0,f.nextTick)(O);else{let D=I;I=null,D()}};E._write=(D,U,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),S.parse(D),O()};let T=D=>{this.log("streamErrorHandler :: error",D.message),D.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",D)):this.noop(D)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(E),this.stream.on("error",T),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let q={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will&&(q.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(q.properties||(q.properties={}),this.topicAliasRecv&&(q.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(q),S.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"){let D={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(D)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(E,S,I,P){this.log("publish :: message `%s` to topic `%s`",S,E);let{options:O}=this;typeof I=="function"&&(P=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:j,retain:T,dup:q,properties:D,cbStorePut:U}=I;if(this._checkDisconnecting(P))return this;let ae=()=>{let Y=0;if((j===1||j===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let V={cmd:"publish",topic:E,payload:S,qos:j,retain:T,messageId:Y,dup:q};switch(O.protocolVersion===5&&(V.properties=D),this.log("publish :: qos",j),j){case 1:case 2:this.outgoing[V.messageId]={volatile:!1,cb:P||this.noop},this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,void 0,U);break;default:this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,P,U);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!ae())&&this._storeProcessingQueue.push({invoke:ae,cbStorePut:I.cbStorePut,callback:P}),this}publishAsync(E,S,I){return new Promise((P,O)=>{this.publish(E,S,I,(j,T)=>{j?O(j):P(T)})})}subscribe(E,S,I){let P=this.options.protocolVersion;typeof S=="function"&&(I=S),I=I||this.noop;let O=!1,j=[];typeof E=="string"?(E=[E],j=E):Array.isArray(E)?j=E:typeof E=="object"&&(O=E.resubscribe,delete E.resubscribe,j=Object.keys(E));let T=c.validateTopics(j);if(T!==null)return m(I,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(I))return this.log("subscribe: discconecting true"),this;let q={qos:0};P===5&&(q.nl=!1,q.rap=!1,q.rh=0),S={...q,...S};let{properties:D}=S,U=[],ae=(re,F)=>{if(F=F||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<F.qos||O){let Z={topic:re,qos:F.qos};P===5&&(Z.nl=F.nl,Z.rap=F.rap,Z.rh=F.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,F)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:F};if(D&&(Z.properties=D),this.options.resubscribe){this.log("subscribe :: resubscribe true");let Q=[];re.forEach(ye=>{if(this.options.reconnectPeriod>0){let te={qos:ye.qos};P===5&&(te.nl=ye.nl||!1,te.rap=ye.rap||!1,te.rh=ye.rh||0,te.properties=ye.properties),this._resubscribeTopics[ye.topic]=te,Q.push(ye.topic)}}),this.messageIdToTopic[Z.messageId]=Q}let M=new Promise((Q,ye)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:G}=we;for(let N=0;N<G.length;N+=1)re[N].qos=G[N]}te?ye(new f.ErrorWithSubackPacket(te.message,we)):Q(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),M},V=()=>{let re=this.options.subscribeBatchSize??U.length,F=[];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;F.push(Y(M,Q))}return Promise.all(F).then(Z=>{I(null,U,Z.at(-1))}).catch(Z=>{I(Z,U,Z.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!V())&&this._storeProcessingQueue.push({invoke:V,callback:I}),this}subscribeAsync(E,S){return new Promise((I,P)=>{this.subscribe(E,S,(O,j)=>{O?P(O):I(j)})})}unsubscribe(E,S,I){typeof E=="string"&&(E=[E]),typeof S=="function"&&(I=S),I=I||this.noop;let P=c.validateTopics(E);if(P!==null)return m(I,new Error(`Invalid topic ${P}`)),this;if(this._checkDisconnecting(I))return this;let O=()=>{let j=this._nextId();if(j===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:j,unsubscriptions:[]};return typeof E=="string"?T.unsubscriptions=[E]:Array.isArray(E)&&(T.unsubscriptions=E),this.options.resubscribe&&T.unsubscriptions.forEach(q=>{delete this._resubscribeTopics[q]}),typeof S=="object"&&S.properties&&(T.properties=S.properties),this.outgoing[T.messageId]={volatile:!0,cb:I},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!O())&&this._storeProcessingQueue.push({invoke:O,callback:I}),this}unsubscribeAsync(E,S){return new Promise((I,P)=>{this.unsubscribe(E,S,(O,j)=>{O?P(O):I(j)})})}end(E,S,I){this.log("end :: (%s)",this.options.clientId),(E==null||typeof E!="boolean")&&(I=I||S,S=E,E=!1),typeof S!="object"&&(I=I||S,S=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let P=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(j=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let q=j||T;this.log("end :: closeStores: invoking callback with args"),I(q)}})}),this._deferredReconnect?this._deferredReconnect():(this.options.reconnectPeriod===0||this.options.manualConnect)&&(this.disconnecting=!1)},O=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,E),this._cleanUp(E,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,f.nextTick)(P)},S)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!E&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,O,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),O()),this)}endAsync(E,S){return new Promise((I,P)=>{this.end(E,S,O=>{O?P(O):I()})})}removeOutgoingMessage(E){if(this.outgoing[E]){let{cb:S}=this.outgoing[E];this._removeOutgoingAndStoreMessage(E,()=>{S(new Error("Message removed"))})}return this}reconnect(E){this.log("client reconnect");let S=()=>{E?(this.options.incomingStore=E.incomingStore,this.options.outgoingStore=E.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=S:S(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(E=>{this.outgoing[E].volatile&&typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(E=>{typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_removeTopicAliasAndRecoverTopicName(E){let S;E.properties&&(S=E.properties.topicAlias);let I=E.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",S,I),I.length===0){if(typeof S>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(S),typeof I>"u")return new Error("Unregistered Topic Alias");E.topic=I}S&&delete E.properties.topicAlias}_checkDisconnecting(E){return this.disconnecting&&(E&&E!==this.noop?E(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(E,S,I={}){if(S&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",S)),this.log("_cleanUp :: forced? %s",E),E)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let P={cmd:"disconnect",...I};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(P,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),m(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}!this.disconnecting&&!this.reconnecting&&(this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this._destroyKeepaliveManager(),S&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",S),S())}_storeAndSend(E,S,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",E.cmd);let P=E,O;if(P.cmd==="publish"&&(P=(0,l.default)(E),O=this._removeTopicAliasAndRecoverTopicName(P),O))return S&&S(O);this.outgoingStore.put(P,j=>{if(j)return S&&S(j);I(),this._writePacket(E,S)})}_applyTopicAlias(E){if(this.options.protocolVersion===5&&E.cmd==="publish"){let S;E.properties&&(S=E.properties.topicAlias);let I=E.topic.toString();if(this.topicAliasSend)if(S){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,S),!this.topicAliasSend.put(I,S)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(S=this.topicAliasSend.getAliasByTopic(I),S?(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,S)):(S=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,S),E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,S))):this.options.autoUseTopicAlias&&(S=this.topicAliasSend.getAliasByTopic(I),S&&(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,S))));else if(S)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}}_noop(E){this.log("noop ::",E)}_writePacket(E,S){this.log("_writePacket :: packet: %O",E),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",E),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(E,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&S&&S!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",S)):S&&(this.log("_writePacket :: invoking cb"),S())}_sendPacket(E,S,I,P){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,S=S||this.noop;let O=this._applyTopicAlias(E);if(O){S(O);return}if(!this.connected){if(E.cmd==="auth"){this._writePacket(E,S);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(E,S,I);return}if(P){this._writePacket(E,S);return}switch(E.cmd){case"publish":break;case"pubrel":this._storeAndSend(E,S,I);return;default:this._writePacket(E,S);return}switch(E.qos){case 2:case 1:this._storeAndSend(E,S,I);break;default:this._writePacket(E,S);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(E,S,I){this.log("_storePacket :: packet: %o",E),this.log("_storePacket :: cb? %s",!!S),I=I||this.noop;let P=E;if(P.cmd==="publish"){P=(0,l.default)(E);let j=this._removeTopicAliasAndRecoverTopicName(P);if(j)return S&&S(j)}let O=P.qos||0;O===0&&this.queueQoSZero||P.cmd!=="publish"?this.queue.push({packet:P,cb:S}):O>0?(S=this.outgoing[P.messageId]?this.outgoing[P.messageId].cb:null,this.outgoingStore.put(P,j=>{if(j)return S&&S(j);I()})):S&&S(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new b.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(E=!1){this.keepaliveManager&&this.options.keepalive&&(E||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let E=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&E.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let S=0;S<E.length;S++){let I={};I[E[S]]=this._resubscribeTopics[E[S]],I.resubscribe=!0,this.subscribe(I,{properties:I[E[S]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(E){if(this.disconnected){this.emit("connect",E);return}this.connackPacket=E,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let S=()=>{let I=this.outgoingStore.createStream(),P=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),O()},O=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",P),I.on("error",T=>{O(),this._flushStoreProcessingQueue(),this.removeListener("close",P),this.emit("error",T)});let j=()=>{if(!I)return;let T=I.read(1),q;if(!T){I.once("readable",j);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){j();return}!this.disconnecting&&!this.reconnectTimer?(q=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(D,U){q&&q(D,U),j()}},this._packetIdsDuringStoreProcessing[T.messageId]=!0,this.messageIdProvider.register(T.messageId)?this._sendPacket(T,void 0,void 0,!0):this.log("messageId: %d has already used.",T.messageId)):I.destroy&&I.destroy()};I.on("end",()=>{let T=!0;for(let q in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[q]){T=!1;break}this.removeListener("close",P),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",E)):S()}),j()};S()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let E=this._storeProcessingQueue[0];if(E&&E.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let E of this._storeProcessingQueue)E.cbStorePut&&E.cbStorePut(new Error("Connection closed")),E.callback&&E.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(E,S){delete this.outgoing[E],this.outgoingStore.del({messageId:E},(I,P)=>{S(I,P),this.messageIdProvider.deallocate(E),this._invokeStoreProcessingQueue()})}};s.default=x}),Ju=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Is(),t=class{numberAllocator;lastId;constructor(){this.numberAllocator=new e.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(r){return this.numberAllocator.use(r)}deallocate(r){this.numberAllocator.free(r)}clear(){this.numberAllocator.clear()}};s.default=t});function Qu(){if(wi)return _r;wi=!0;let s=2147483647,e=36,t=1,r=26,i=38,n=700,o=72,l=128,a="-",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"},g=e-t,f=Math.floor,y=String.fromCharCode;function b(O){throw new RangeError(p[O])}function w(O,j){let T=[],q=O.length;for(;q--;)T[q]=j(O[q]);return T}function m(O,j){let T=O.split("@"),q="";T.length>1&&(q=T[0]+"@",O=T[1]),O=O.replace(d,".");let D=O.split("."),U=w(D,j).join(".");return q+U}function _(O){let j=[],T=0,q=O.length;for(;T<q;){let D=O.charCodeAt(T++);if(D>=55296&&D<=56319&&T<q){let U=O.charCodeAt(T++);(U&64512)==56320?j.push(((D&1023)<<10)+(U&1023)+65536):(j.push(D),T--)}else j.push(D)}return j}let x=O=>String.fromCodePoint(...O),v=function(O){return O>=48&&O<58?26+(O-48):O>=65&&O<91?O-65:O>=97&&O<123?O-97:e},E=function(O,j){return O+22+75*(O<26)-((j!=0)<<5)},S=function(O,j,T){let q=0;for(O=T?f(O/n):O>>1,O+=f(O/j);O>g*r>>1;q+=e)O=f(O/g);return f(q+(g+1)*O/(O+i))},I=function(O){let j=[],T=O.length,q=0,D=l,U=o,ae=O.lastIndexOf(a);ae<0&&(ae=0);for(let Y=0;Y<ae;++Y)O.charCodeAt(Y)>=128&&b("not-basic"),j.push(O.charCodeAt(Y));for(let Y=ae>0?ae+1:0;Y<T;){let V=q;for(let F=1,Z=e;;Z+=e){Y>=T&&b("invalid-input");let M=v(O.charCodeAt(Y++));M>=e&&b("invalid-input"),M>f((s-q)/F)&&b("overflow"),q+=M*F;let Q=Z<=U?t:Z>=U+r?r:Z-U;if(M<Q)break;let ye=e-Q;F>f(s/ye)&&b("overflow"),F*=ye}let re=j.length+1;U=S(q-V,re,V==0),f(q/re)>s-D&&b("overflow"),D+=f(q/re),q%=re,j.splice(q++,0,D)}return String.fromCodePoint(...j)},P=function(O){let j=[];O=_(O);let T=O.length,q=l,D=0,U=o;for(let V of O)V<128&&j.push(y(V));let ae=j.length,Y=ae;for(ae&&j.push(a);Y<T;){let V=s;for(let F of O)F>=q&&F<V&&(V=F);let re=Y+1;V-q>f((s-D)/re)&&b("overflow"),D+=(V-q)*re,q=V;for(let F of O)if(F<q&&++D>s&&b("overflow"),F===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 ye=Z-Q,te=e-Q;j.push(y(E(Q+ye%te,0))),Z=f(ye/te)}j.push(y(E(Z,0))),U=S(D,re,Y===ae),D=0,++Y}++D,++q}return j.join("")};return _r={version:"2.3.1",ucs2:{decode:_,encode:x},decode:I,encode:P,toASCII:function(O){return m(O,function(j){return u.test(j)?"xn--"+P(j):j})},toUnicode:function(O){return m(O,function(j){return c.test(j)?I(j.slice(4).toLowerCase()):j})}},_r}var _r,wi,kt,Xu=Ke(()=>{le(),ue(),ce(),_r={},wi=!1,kt=Qu(),kt.decode,kt.encode,kt.toASCII,kt.toUnicode,kt.ucs2,kt.version});function Zu(){return Si||(Si=!0,xi=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 i=Object.getOwnPropertySymbols(s);if(i.length!==1||i[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}),xi}function ed(){return Ai||(Ai=!0,Ei=Error),Ei}function td(){return Ti||(Ti=!0,Ii=EvalError),Ii}function rd(){return Pi||(Pi=!0,Ci=RangeError),Ci}function nd(){return Mi||(Mi=!0,Oi=ReferenceError),Oi}function js(){return Li||(Li=!0,Ri=SyntaxError),Ri}function tr(){return ji||(ji=!0,Ni=TypeError),Ni}function id(){return Bi||(Bi=!0,Ui=URIError),Ui}function od(){if(Di)return kr;Di=!0;var s=typeof Symbol<"u"&&Symbol,e=Zu();return kr=function(){return typeof s!="function"||typeof Symbol!="function"||typeof s("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},kr}function sd(){if(Fi)return xr;Fi=!0;var s={__proto__:null,foo:{}},e=Object;return xr=function(){return{__proto__:s}.foo===s.foo&&!(s instanceof e)},xr}function ad(){if($i)return Sr;$i=!0;var s="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",i=function(l,a){for(var c=[],u=0;u<l.length;u+=1)c[u]=l[u];for(var d=0;d<a.length;d+=1)c[d+l.length]=a[d];return c},n=function(l,a){for(var c=[],u=a,d=0;u<l.length;u+=1,d+=1)c[d]=l[u];return c},o=function(l,a){for(var c="",u=0;u<l.length;u+=1)c+=l[u],u+1<l.length&&(c+=a);return c};return Sr=function(l){var a=this;if(typeof a!="function"||e.apply(a)!==r)throw new TypeError(s+a);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var b=a.apply(this,i(c,arguments));return Object(b)===b?b:this}return a.apply(l,i(c,arguments))},p=t(0,a.length-c.length),g=[],f=0;f<p;f++)g[f]="$"+f;if(u=Function("binder","return function ("+o(g,",")+"){ return binder.apply(this,arguments); }")(d),a.prototype){var y=function(){};y.prototype=a.prototype,u.prototype=new y,y.prototype=null}return u},Sr}function _i(){if(qi)return Er;qi=!0;var s=ad();return Er=Function.prototype.bind||s,Er}function ld(){if(Hi)return Ar;Hi=!0;var s=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=_i();return Ar=t.call(s,e),Ar}function qt(){if(Wi)return Ir;Wi=!0;var s,e=ed(),t=td(),r=rd(),i=nd(),n=js(),o=tr(),l=id(),a=Function,c=function(Y){try{return a('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new o},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=od()(),f=sd()(),y=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),b={},w=typeof Uint8Array>"u"||!y?s:y(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?s:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?s:ArrayBuffer,"%ArrayIteratorPrototype%":g&&y?y([][Symbol.iterator]()):s,"%AsyncFromSyncIteratorPrototype%":s,"%AsyncFunction%":b,"%AsyncGenerator%":b,"%AsyncGeneratorFunction%":b,"%AsyncIteratorPrototype%":b,"%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%":a,"%GeneratorFunction%":b,"%Int8Array%":typeof Int8Array>"u"?s:Int8Array,"%Int16Array%":typeof Int16Array>"u"?s:Int16Array,"%Int32Array%":typeof Int32Array>"u"?s:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&y?y(y([][Symbol.iterator]())):s,"%JSON%":typeof JSON=="object"?JSON:s,"%Map%":typeof Map>"u"?s:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!y?s:y(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%":i,"%Reflect%":typeof Reflect>"u"?s:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?s:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!y?s:y(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?s:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&y?y(""[Symbol.iterator]()):s,"%Symbol%":g?Symbol:s,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":w,"%TypeError%":o,"%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%":l,"%WeakMap%":typeof WeakMap>"u"?s:WeakMap,"%WeakRef%":typeof WeakRef>"u"?s:WeakRef,"%WeakSet%":typeof WeakSet>"u"?s:WeakSet};if(y)try{null.error}catch(Y){var _=y(y(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 F=Y("%AsyncGeneratorFunction%");F&&(re=F.prototype)}else if(V==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&y&&(re=y(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=_i(),S=ld(),I=E.call(Function.call,Array.prototype.concat),P=E.call(Function.apply,Array.prototype.splice),O=E.call(Function.call,String.prototype.replace),j=E.call(Function.call,String.prototype.slice),T=E.call(Function.call,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,D=/\\(\\)?/g,U=function(Y){var V=j(Y,0,1),re=j(Y,-1);if(V==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&V!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var F=[];return O(Y,q,function(Z,M,Q,ye){F[F.length]=Q?O(ye,D,"$1"):M||Z}),F},ae=function(Y,V){var re=Y,F;if(S(v,re)&&(F=v[re],re="%"+F[0]+"%"),S(m,re)){var Z=m[re];if(Z===b&&(Z=x(re)),typeof Z>"u"&&!V)throw new o("intrinsic "+Y+" exists, but is not available. Please file an issue!");return{alias:F,name:re,value:Z}}throw new n("intrinsic "+Y+" does not exist!")};return Ir=function(Y,V){if(typeof Y!="string"||Y.length===0)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof V!="boolean")throw new o('"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),F=re.length>0?re[0]:"",Z=ae("%"+F+"%",V),M=Z.name,Q=Z.value,ye=!1,te=Z.alias;te&&(F=te[0],P(re,I([0,1],te)));for(var we=1,G=!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"||!G)&&(ye=!0),F+="."+N,M="%"+F+"%",S(m,M))Q=m[M];else if(Q!=null){if(!(N in Q)){if(!V)throw new o("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var K=u(Q,N);G=!!K,G&&"get"in K&&!("originalValue"in K.get)?Q=K.get:Q=Q[N]}else G=S(Q,N),Q=Q[N];G&&!ye&&(m[M]=Q)}}return Q},Ir}function ki(){if(zi)return Tr;zi=!0;var s=qt(),e=s("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Tr=e,Tr}function Us(){if(Vi)return Cr;Vi=!0;var s=qt(),e=s("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Cr=e,Cr}function cd(){if(Gi)return Pr;Gi=!0;var s=ki(),e=js(),t=tr(),r=Us();return Pr=function(i,n,o){if(!i||typeof i!="object"&&typeof i!="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 l=arguments.length>3?arguments[3]:null,a=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(i,n);if(s)s(i,n,{configurable:c===null&&d?d.configurable:!c,enumerable:l===null&&d?d.enumerable:!l,value:o,writable:a===null&&d?d.writable:!a});else if(u||!l&&!a&&!c)i[n]=o;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Pr}function ud(){if(Ki)return Or;Ki=!0;var s=ki(),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 dd(){if(Yi)return Mr;Yi=!0;var s=qt(),e=cd(),t=ud()(),r=Us(),i=tr(),n=s("%Math.floor%");return Mr=function(o,l){if(typeof o!="function")throw new i("`fn` is not a function");if(typeof l!="number"||l<0||l>4294967295||n(l)!==l)throw new i("`length` must be a positive 32-bit integer");var a=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in o&&r){var d=r(o,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!a)&&(t?e(o,"length",l,!0,!0):e(o,"length",l)),o},Mr}function hd(){if(Ji)return Ht;Ji=!0;var s=_i(),e=qt(),t=dd(),r=tr(),i=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),o=e("%Reflect.apply%",!0)||s.call(n,i),l=ki(),a=e("%Math.max%");Ht=function(u){if(typeof u!="function")throw new r("a function is required");var d=o(s,n,arguments);return t(d,1+a(0,u.length-(arguments.length-1)),!0)};var c=function(){return o(s,i,arguments)};return l?l(Ht,"apply",{value:c}):Ht.apply=c,Ht}function fd(){if(Qi)return Rr;Qi=!0;var s=qt(),e=hd(),t=e(s("String.prototype.indexOf"));return Rr=function(r,i){var n=s(r,!!i);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Rr}var xi,Si,Ei,Ai,Ii,Ti,Ci,Pi,Oi,Mi,Ri,Li,Ni,ji,Ui,Bi,kr,Di,xr,Fi,Sr,$i,Er,qi,Ar,Hi,Ir,Wi,Tr,zi,Cr,Vi,Pr,Gi,Or,Ki,Mr,Yi,Ht,Ji,Rr,Qi,pd=Ke(()=>{le(),ue(),ce(),xi={},Si=!1,Ei={},Ai=!1,Ii={},Ti=!1,Ci={},Pi=!1,Oi={},Mi=!1,Ri={},Li=!1,Ni={},ji=!1,Ui={},Bi=!1,kr={},Di=!1,xr={},Fi=!1,Sr={},$i=!1,Er={},qi=!1,Ar={},Hi=!1,Ir={},Wi=!1,Tr={},zi=!1,Cr={},Vi=!1,Pr={},Gi=!1,Or={},Ki=!1,Mr={},Yi=!1,Ht={},Ji=!1,Rr={},Qi=!1});function Xi(s){throw new Error("Node.js process "+s+" is not supported by JSPM core outside of Node.js")}function md(){!Ot||!Mt||(Ot=!1,Mt.length?rt=Mt.concat(rt):rr=-1,rt.length&&Bs())}function Bs(){if(!Ot){var s=setTimeout(md,0);Ot=!0;for(var e=rt.length;e;){for(Mt=rt,rt=[];++rr<e;)Mt&&Mt[rr].run();rr=-1,e=rt.length}Mt=null,Ot=!1,clearTimeout(s)}}function gd(s){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];rt.push(new Ds(s,e)),rt.length===1&&!Ot&&setTimeout(Bs,0)}function Ds(s,e){this.fun=s,this.array=e}function He(){}function yd(s){Xi("_linkedBinding")}function bd(s){Xi("dlopen")}function vd(){return[]}function wd(){return[]}function _d(s,e){if(!s)throw new Error(e||"assertion error")}function kd(){return!1}function xd(){return yt.now()/1e3}function Zi(s){var e=Math.floor((Date.now()-yt.now())*.001),t=yt.now()*.001,r=Math.floor(t)+e,i=Math.floor(t%1*1e9);return s&&(r=r-s[0],i=i-s[1],i<0&&(r--,i+=Nr)),[r,i]}function xt(){return to}function Sd(s){return[]}var rt,Ot,Mt,rr,Fs,$s,qs,Hs,Ws,zs,Vs,Gs,Ks,Ys,Js,Qs,Xs,Zs,ea,ta,ra,na,ia,oa,sa,Lr,aa,la,ca,ua,da,ha,fa,pa,ma,ga,ya,ba,va,wa,_a,ka,xa,Sa,Ea,Aa,Ia,Ta,Ca,Pa,Oa,yt,eo,Nr,Ma,Ra,La,Na,ja,Ua,Ba,Da,Fa,$a,qa,to,Ha=Ke(()=>{le(),ue(),ce(),rt=[],Ot=!1,rr=-1,Ds.prototype.run=function(){this.fun.apply(null,this.array)},Fs="browser",$s="x64",qs="browser",Hs={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Ws=["/usr/bin/node"],zs=[],Vs="v16.8.0",Gs={},Ks=function(s,e){console.warn((e?e+": ":"")+s)},Ys=function(s){Xi("binding")},Js=function(s){return 0},Qs=function(){return"/"},Xs=function(s){},Zs={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},ea=He,ta=[],ra={},na=!1,ia={},oa=He,sa=He,Lr=function(){return{}},aa=Lr,la=Lr,ca=He,ua=He,da=He,ha={},fa={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},pa=He,ma=He,ga=He,ya=He,ba=He,va=He,wa=He,_a=void 0,ka=void 0,xa=void 0,Sa=He,Ea=2,Aa=1,Ia="/bin/usr/node",Ta=9229,Ca="node",Pa=[],Oa=He,yt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},yt.now===void 0&&(eo=Date.now(),yt.timing&&yt.timing.navigationStart&&(eo=yt.timing.navigationStart),yt.now=()=>Date.now()-eo),Nr=1e9,Zi.bigint=function(s){var e=Zi(s);return typeof BigInt>"u"?e[0]*Nr+e[1]:BigInt(e[0]*Nr)+BigInt(e[1])},Ma=10,Ra={},La=0,Na=xt,ja=xt,Ua=xt,Ba=xt,Da=xt,Fa=He,$a=xt,qa=xt,to={version:Vs,versions:Gs,arch:$s,platform:qs,release:Zs,_rawDebug:ea,moduleLoadList:ta,binding:Ys,_linkedBinding:yd,_events:Ra,_eventsCount:La,_maxListeners:Ma,on:xt,addListener:Na,once:ja,off:Ua,removeListener:Ba,removeAllListeners:Da,emit:Fa,prependListener:$a,prependOnceListener:qa,listeners:Sd,domain:ra,_exiting:na,config:ia,dlopen:bd,uptime:xd,_getActiveRequests:vd,_getActiveHandles:wd,reallyExit:oa,_kill:sa,cpuUsage:Lr,resourceUsage:aa,memoryUsage:la,kill:ca,exit:ua,openStdin:da,allowedNodeEnvironmentFlags:ha,assert:_d,features:fa,_fatalExceptions:pa,setUncaughtExceptionCaptureCallback:ma,hasUncaughtExceptionCaptureCallback:kd,emitWarning:Ks,nextTick:gd,_tickCallback:ga,_debugProcess:ya,_debugEnd:ba,_startProfilerIdleNotifier:va,_stopProfilerIdleNotifier:wa,stdout:_a,stdin:xa,stderr:ka,abort:Sa,umask:Js,chdir:Xs,cwd:Qs,env:Hs,title:Fs,argv:Ws,execArgv:zs,pid:Ea,ppid:Aa,execPath:Ia,debugPort:Ta,hrtime:Zi,argv0:Ca,_preload_modules:Pa,setSourceMapsEnabled:Oa}});function Ed(){if(ro)return jr;ro=!0;var s=to;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,o){for(var l="",a=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(l.length<2||a!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var g=l.lastIndexOf("/");if(g!==l.length-1){g===-1?(l="",a=0):(l=l.slice(0,g),a=l.length-1-l.lastIndexOf("/")),c=p,u=0;continue}}else if(l.length===2||l.length===1){l="",a=0,c=p,u=0;continue}}o&&(l.length>0?l+="/..":l="..",a=2)}else l.length>0?l+="/"+n.slice(c+1,p):l=n.slice(c+1,p),a=p-c-1;c=p,u=0}else d===46&&u!==-1?++u:u=-1}return l}function r(n,o){var l=o.dir||o.root,a=o.base||(o.name||"")+(o.ext||"");return l?l===o.root?l+a:l+n+a:a}var i={resolve:function(){for(var n="",o=!1,l,a=arguments.length-1;a>=-1&&!o;a--){var c;a>=0?c=arguments[a]:(l===void 0&&(l=s.cwd()),c=l),e(c),c.length!==0&&(n=c+"/"+n,o=c.charCodeAt(0)===47)}return n=t(n,!o),o?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var o=n.charCodeAt(0)===47,l=n.charCodeAt(n.length-1)===47;return n=t(n,!o),n.length===0&&!o&&(n="."),n.length>0&&l&&(n+="/"),o?"/"+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,o=0;o<arguments.length;++o){var l=arguments[o];e(l),l.length>0&&(n===void 0?n=l:n+="/"+l)}return n===void 0?".":i.normalize(n)},relative:function(n,o){if(e(n),e(o),n===o||(n=i.resolve(n),o=i.resolve(o),n===o))return"";for(var l=1;l<n.length&&n.charCodeAt(l)===47;++l);for(var a=n.length,c=a-l,u=1;u<o.length&&o.charCodeAt(u)===47;++u);for(var d=o.length,p=d-u,g=c<p?c:p,f=-1,y=0;y<=g;++y){if(y===g){if(p>g){if(o.charCodeAt(u+y)===47)return o.slice(u+y+1);if(y===0)return o.slice(u+y)}else c>g&&(n.charCodeAt(l+y)===47?f=y:y===0&&(f=0));break}var b=n.charCodeAt(l+y),w=o.charCodeAt(u+y);if(b!==w)break;b===47&&(f=y)}var m="";for(y=l+f+1;y<=a;++y)(y===a||n.charCodeAt(y)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+o.slice(u+f):(u+=f,o.charCodeAt(u)===47&&++u,o.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var o=n.charCodeAt(0),l=o===47,a=-1,c=!0,u=n.length-1;u>=1;--u)if(o=n.charCodeAt(u),o===47){if(!c){a=u;break}}else c=!1;return a===-1?l?"/":".":l&&a===1?"//":n.slice(0,a)},basename:function(n,o){if(o!==void 0&&typeof o!="string")throw new TypeError('"ext" argument must be a string');e(n);var l=0,a=-1,c=!0,u;if(o!==void 0&&o.length>0&&o.length<=n.length){if(o.length===n.length&&o===n)return"";var d=o.length-1,p=-1;for(u=n.length-1;u>=0;--u){var g=n.charCodeAt(u);if(g===47){if(!c){l=u+1;break}}else p===-1&&(c=!1,p=u+1),d>=0&&(g===o.charCodeAt(d)?--d===-1&&(a=u):(d=-1,a=p))}return l===a?a=p:a===-1&&(a=n.length),n.slice(l,a)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){l=u+1;break}}else a===-1&&(c=!1,a=u+1);return a===-1?"":n.slice(l,a)}},extname:function(n){e(n);for(var o=-1,l=0,a=-1,c=!0,u=0,d=n.length-1;d>=0;--d){var p=n.charCodeAt(d);if(p===47){if(!c){l=d+1;break}continue}a===-1&&(c=!1,a=d+1),p===46?o===-1?o=d:u!==1&&(u=1):o!==-1&&(u=-1)}return o===-1||a===-1||u===0||u===1&&o===a-1&&o===l+1?"":n.slice(o,a)},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 o={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return o;var l=n.charCodeAt(0),a=l===47,c;a?(o.root="/",c=1):c=0;for(var u=-1,d=0,p=-1,g=!0,f=n.length-1,y=0;f>=c;--f){if(l=n.charCodeAt(f),l===47){if(!g){d=f+1;break}continue}p===-1&&(g=!1,p=f+1),l===46?u===-1?u=f:y!==1&&(y=1):u!==-1&&(y=-1)}return u===-1||p===-1||y===0||y===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&a?o.base=o.name=n.slice(1,p):o.base=o.name=n.slice(d,p)):(d===0&&a?(o.name=n.slice(1,u),o.base=n.slice(1,p)):(o.name=n.slice(d,u),o.base=n.slice(d,p)),o.ext=n.slice(u,p)),d>0?o.dir=n.slice(0,d-1):a&&(o.dir="/"),o},sep:"/",delimiter:":",win32:null,posix:null};return i.posix=i,jr=i,jr}var jr,ro,no,Ad=Ke(()=>{le(),ue(),ce(),Ha(),jr={},ro=!1,no=Ed()}),Wa={};Ut(Wa,{URL:()=>tl,Url:()=>Ja,default:()=>We,fileURLToPath:()=>Va,format:()=>Qa,parse:()=>el,pathToFileURL:()=>Ga,resolve:()=>Xa,resolveObject:()=>Za});function Id(){if(oo)return Ur;oo=!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,i=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,o=i&&n&&typeof n.get=="function"?n.get:null,l=i&&Set.prototype.forEach,a=typeof WeakMap=="function"&&WeakMap.prototype,c=a?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,g=p?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,y=Object.prototype.toString,b=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,P=Array.prototype.slice,O=Math.floor,j=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,q=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,D=typeof Symbol=="function"&&typeof Symbol.iterator=="object",U=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===D||!0)?Symbol.toStringTag:null,ae=Object.prototype.propertyIsEnumerable,Y=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(z){return z.__proto__}:null);function V(z,ie){if(z===1/0||z===-1/0||z!==z||z&&z>-1e3&&z<1e3||E.call(/e/,ie))return ie;var Ee=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof z=="number"){var Ae=z<0?-O(-z):O(z);if(Ae!==z){var Ie=String(Ae),Pe=m.call(ie,Ie.length+1);return _.call(Ie,Ee,"$&_")+"."+_.call(_.call(Pe,/([0-9]{3})/g,"$&_"),/_$/,"")}}return _.call(ie,Ee,"$&_")}var re=Ka,F=re.custom,Z=K(F)?F:null;Ur=function z(ie,Ee,Ae,Ie){var Pe=Ee||{};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 nt=oe(Pe,"customInspect")?Pe.customInspect:!0;if(typeof nt!="boolean"&&nt!=="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 it=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 ze=String(ie);return it?V(ie,ze):ze}if(typeof ie=="bigint"){var ot=String(ie)+"n";return it?V(ie,ot):ot}var Gt=typeof Pe.depth>"u"?5:Pe.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=Gt&&Gt>0&&typeof ie=="object")return ye(ie)?"[Array]":"[Object]";var st=X(Pe,Ae);if(typeof Ie>"u")Ie=[];else if(ee(Ie,ie)>=0)return"[Circular]";function Xe(at,Et,jt){if(Et&&(Ie=P.call(Ie),Ie.push(Et)),jt){var lt={depth:Pe.depth};return oe(Pe,"quoteStyle")&&(lt.quoteStyle=Pe.quoteStyle),z(at,lt,Ae+1,Ie)}return z(at,Pe,Ae+1,Ie)}if(typeof ie=="function"&&!we(ie)){var Xr=$(ie),Kt=ke(ie,Xe);return"[Function"+(Xr?": "+Xr:" (anonymous)")+"]"+(Kt.length>0?" { "+I.call(Kt,", ")+" }":"")}if(K(ie)){var or=D?_.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):q.call(ie);return typeof ie=="object"&&!D?h(or):or}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(ye(ie)){if(ie.length===0)return"[]";var xe=ke(ie,Xe);return st&&!B(xe)?"["+de(xe,st)+"]":"[ "+I.call(xe,", ")+" ]"}if(G(ie)){var Se=ke(ie,Xe);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(S.call("[cause]: "+Xe(ie.cause),Se),", ")+" }":Se.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Se,", ")+" }"}if(typeof ie=="object"&&nt){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Gt-Ae});if(nt!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var De=[];return r&&r.call(ie,function(at,Et){De.push(Xe(Et,ie,!0)+" => "+Xe(at,ie))}),A("Map",t.call(ie),De,st)}if(H(ie)){var Ge=[];return l&&l.call(ie,function(at){Ge.push(Xe(at,ie))}),A("Set",o.call(ie),Ge,st)}if(fe(ie))return k("WeakMap");if(me(ie))return k("WeakSet");if(be(ie))return k("WeakRef");if(ne(ie))return h(Xe(Number(ie)));if(J(ie))return h(Xe(j.call(ie)));if(W(ie))return h(f.call(ie));if(N(ie))return h(Xe(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Br<"u"&&ie===Br)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var et=ke(ie,Xe),sr=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,ar=ie instanceof Object?"":"null prototype",lr=!sr&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):ar?"Object":"",Zr=sr||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Nt=Zr+(lr||ar?"["+I.call(S.call([],lr||[],ar||[]),": ")+"] ":"");return et.length===0?Nt+"{}":st?Nt+"{"+de(et,st)+"}":Nt+"{ "+I.call(et,", ")+" }"}return String(ie)};function M(z,ie,Ee){var Ae=(Ee.quoteStyle||ie)==="double"?'"':"'";return Ae+z+Ae}function Q(z){return _.call(String(z),/"/g,"&quot;")}function ye(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 G(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 K(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||Br)};function oe(z,ie){return ge.call(z,ie)}function R(z){return y.call(z)}function $(z){if(z.name)return z.name;var ie=w.call(b.call(z),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(z,ie){if(z.indexOf)return z.indexOf(ie);for(var Ee=0,Ae=z.length;Ee<Ae;Ee++)if(z[Ee]===ie)return Ee;return-1}function he(z){if(!t||!z||typeof z!="object")return!1;try{t.call(z);try{o.call(z)}catch{return!0}return z instanceof Map}catch{}return!1}function fe(z){if(!c||!z||typeof z!="object")return!1;try{c.call(z,c);try{d.call(z,d)}catch{return!0}return z instanceof WeakMap}catch{}return!1}function be(z){if(!g||!z||typeof z!="object")return!1;try{return g.call(z),!0}catch{}return!1}function H(z){if(!o||!z||typeof z!="object")return!1;try{o.call(z);try{t.call(z)}catch{return!0}return z instanceof Set}catch{}return!1}function me(z){if(!d||!z||typeof z!="object")return!1;try{d.call(z,d);try{c.call(z,c)}catch{return!0}return z instanceof WeakSet}catch{}return!1}function ve(z){return!z||typeof z!="object"?!1:typeof HTMLElement<"u"&&z instanceof HTMLElement?!0:typeof z.nodeName=="string"&&typeof z.getAttribute=="function"}function se(z,ie){if(z.length>ie.maxStringLength){var Ee=z.length-ie.maxStringLength,Ae="... "+Ee+" more character"+(Ee>1?"s":"");return se(m.call(z,0,ie.maxStringLength),ie)+Ae}var Ie=_.call(_.call(z,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Te);return M(Ie,"single",ie)}function Te(z){var ie=z.charCodeAt(0),Ee={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ee?"\\"+Ee:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function h(z){return"Object("+z+")"}function k(z){return z+" { ? }"}function A(z,ie,Ee,Ae){var Ie=Ae?de(Ee,Ae):I.call(Ee,", ");return z+" ("+ie+") {"+Ie+"}"}function B(z){for(var ie=0;ie<z.length;ie++)if(ee(z[ie],`
4
- `)>=0)return!1;return!0}function X(z,ie){var Ee;if(z.indent===" ")Ee=" ";else if(typeof z.indent=="number"&&z.indent>0)Ee=I.call(Array(z.indent+1)," ");else return null;return{base:Ee,prev:I.call(Array(ie+1),Ee)}}function de(z,ie){if(z.length===0)return"";var Ee=`
1
+ var AikaaraChat=(function(Oe){"use strict";class jo{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 tn{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 jo(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 ur{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 xc=1e3,Sc=10,Ec=400,Ac=600,Uo="#6366f1",Ic=12,Tc="system-ui, -apple-system, sans-serif",Bo="Type a message...",Cc="bottom-right",Oc="light",Pc={x:20,y:20},rn="aikaara_conversation_id";class Do extends ur{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 tn(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??Sc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??xc)*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 tn(o),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const o=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${o}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class Fo{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,o){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=o}setAuthRefreshHook(e){this.refreshHook=e}getAuthToken(){return this.authToken}setAuthToken(e){this.authToken=e}async createConversation(e){const t={conversation:{...e.extUid&&{ext_uid:e.extUid},...e.systemPromptId&&{system_prompt_id:e.systemPromptId},...e.channel&&{channel:e.channel},...e.title&&{title:e.title}}};return this.request("POST","/api/v1/conversations",t)}async updateContext(e,t){const r=this.authToken?`/dashboard/sidekick_conversations/${e}`:`/api/v1/conversations/${e}`;await this.request("PATCH",r,t)}async getMessages(e){return(await this.request("GET",`/api/v1/conversations/${e}/messages`)).map(this.mapMessage)}mapMessage(e){return{id:String(e.id),conversationId:String(e.conversation_id),role:e.role,content:e.content||"",toolCalls:e.tool_calls?.map(t=>({id:t.id,type:t.type,function:t.function})),toolCallResults:e.tool_call_results,tokensInput:e.tokens_input,tokensOutput:e.tokens_output,metadata:e.metadata,createdAt:e.created_at,status:"complete"}}async request(e,t,r){const o=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(o,e,r);if(n.status===401&&this.refreshHook){let l=null;try{l=await this.refreshHook()}catch(a){console.warn("[aikaara-chat-sdk] auth refresh hook threw",a)}l&&(this.authToken=l,n=await this.fetchWithHeaders(o,e,r))}if(!n.ok){const l=await n.text();let a;try{const c=JSON.parse(l);a=c.error||c.message||l}catch{a=l}throw new Error(`API error ${n.status}: ${a}`)}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 $o{_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=qo(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=qo(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 qo(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),l=Ho(e),a=Wo(e);if(!i&&!l&&!a)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],g=(h.metadata??{}).attributes;if(!(!!p||!!(g&&g.fileMessage)))continue;const b=(h.content||"").trim().toLowerCase();if(b==="file_uploaded"||b==="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=Ho(h);if(l&&w&&l===w)return h;const m=Wo(h);if(a&&m&&a===m)return h}return null}function Ho(s){const e=s.attachments&&s.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=zo(s);if(t)return t}function Wo(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=zo(s);if(r){const o=/[?&]cloudFileId=([^&]+)/.exec(r);if(o)return decodeURIComponent(o[1])}}function zo(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 Vo{_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(rn)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(rn)}catch{return null}}saveToStorage(e){try{localStorage.setItem(rn,e)}catch{}}}var nn=Object.defineProperty,Mc=Object.getOwnPropertyDescriptor,Rc=Object.getOwnPropertyNames,Lc=Object.prototype.hasOwnProperty,Ge=(s,e)=>()=>(s&&(e=s(s=0)),e),pe=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ut=(s,e)=>{for(var t in e)nn(s,t,{get:e[t],enumerable:!0})},Nc=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Rc(e))!Lc.call(s,o)&&o!==t&&nn(s,o,{get:()=>e[o],enumerable:!(r=Mc(e,o))||r.enumerable});return s},Re=s=>Nc(nn({},"__esModule",{value:!0}),s),le=Ge(()=>{}),Le={};Ut(Le,{_debugEnd:()=>Dn,_debugProcess:()=>Bn,_events:()=>ti,_eventsCount:()=>ri,_exiting:()=>Sn,_fatalExceptions:()=>Nn,_getActiveHandles:()=>Zo,_getActiveRequests:()=>Xo,_kill:()=>In,_linkedBinding:()=>Jo,_maxListeners:()=>ei,_preload_modules:()=>Qn,_rawDebug:()=>_n,_startProfilerIdleNotifier:()=>Fn,_stopProfilerIdleNotifier:()=>$n,_tickCallback:()=>Un,abort:()=>zn,addListener:()=>ni,allowedNodeEnvironmentFlags:()=>Rn,arch:()=>an,argv:()=>un,argv0:()=>Jn,assert:()=>es,binding:()=>mn,browser:()=>wn,chdir:()=>yn,config:()=>En,cpuUsage:()=>Jt,cwd:()=>bn,debugPort:()=>Yn,default:()=>hi,dlopen:()=>Qo,domain:()=>xn,emit:()=>li,emitWarning:()=>pn,env:()=>cn,execArgv:()=>hn,execPath:()=>Gn,exit:()=>Pn,features:()=>Ln,hasUncaughtExceptionCaptureCallback:()=>ts,hrtime:()=>dr,kill:()=>On,listeners:()=>ns,memoryUsage:()=>Cn,moduleLoadList:()=>kn,nextTick:()=>Go,off:()=>oi,on:()=>ct,once:()=>ii,openStdin:()=>Mn,pid:()=>Vn,platform:()=>ln,ppid:()=>Kn,prependListener:()=>ci,prependOnceListener:()=>ui,reallyExit:()=>An,release:()=>vn,removeAllListeners:()=>ai,removeListener:()=>si,resourceUsage:()=>Tn,setSourceMapsEnabled:()=>Xn,setUncaughtExceptionCaptureCallback:()=>jn,stderr:()=>Hn,stdin:()=>Wn,stdout:()=>qn,title:()=>sn,umask:()=>gn,uptime:()=>rs,version:()=>dn,versions:()=>fn});function on(s){throw new Error("Node.js process "+s+" is not supported by JSPM core outside of Node.js")}function jc(){!At||!It||(At=!1,It.length?tt=It.concat(tt):Yt=-1,tt.length&&Ko())}function Ko(){if(!At){var s=setTimeout(jc,0);At=!0;for(var e=tt.length;e;){for(It=tt,tt=[];++Yt<e;)It&&It[Yt].run();Yt=-1,e=tt.length}It=null,At=!1,clearTimeout(s)}}function Go(s){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];tt.push(new Yo(s,e)),tt.length===1&&!At&&setTimeout(Ko,0)}function Yo(s,e){this.fun=s,this.array=e}function qe(){}function Jo(s){on("_linkedBinding")}function Qo(s){on("dlopen")}function Xo(){return[]}function Zo(){return[]}function es(s,e){if(!s)throw new Error(e||"assertion error")}function ts(){return!1}function rs(){return ut.now()/1e3}function dr(s){var e=Math.floor((Date.now()-ut.now())*.001),t=ut.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return s&&(r=r-s[0],o=o-s[1],o<0&&(r--,o+=fr)),[r,o]}function ct(){return hi}function ns(s){return[]}var tt,At,It,Yt,sn,an,ln,cn,un,hn,dn,fn,pn,mn,gn,bn,yn,vn,wn,_n,kn,xn,Sn,En,An,In,Jt,Tn,Cn,On,Pn,Mn,Rn,Ln,Nn,jn,Un,Bn,Dn,Fn,$n,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,ut,Zn,fr,ei,ti,ri,ni,ii,oi,si,ai,li,ci,ui,hi,Uc=Ge(()=>{le(),ue(),ce(),tt=[],At=!1,Yt=-1,Yo.prototype.run=function(){this.fun.apply(null,this.array)},sn="browser",an="x64",ln="browser",cn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},un=["/usr/bin/node"],hn=[],dn="v16.8.0",fn={},pn=function(s,e){console.warn((e?e+": ":"")+s)},mn=function(s){on("binding")},gn=function(s){return 0},bn=function(){return"/"},yn=function(s){},vn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},wn=!0,_n=qe,kn=[],xn={},Sn=!1,En={},An=qe,In=qe,Jt=function(){return{}},Tn=Jt,Cn=Jt,On=qe,Pn=qe,Mn=qe,Rn={},Ln={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Nn=qe,jn=qe,Un=qe,Bn=qe,Dn=qe,Fn=qe,$n=qe,qn=void 0,Hn=void 0,Wn=void 0,zn=qe,Vn=2,Kn=1,Gn="/bin/usr/node",Yn=9229,Jn="node",Qn=[],Xn=qe,ut={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ut.now===void 0&&(Zn=Date.now(),ut.timing&&ut.timing.navigationStart&&(Zn=ut.timing.navigationStart),ut.now=()=>Date.now()-Zn),fr=1e9,dr.bigint=function(s){var e=dr(s);return typeof BigInt>"u"?e[0]*fr+e[1]:BigInt(e[0]*fr)+BigInt(e[1])},ei=10,ti={},ri=0,ni=ct,ii=ct,oi=ct,si=ct,ai=ct,li=qe,ci=ct,ui=ct,hi={version:dn,versions:fn,arch:an,platform:ln,browser:wn,release:vn,_rawDebug:_n,moduleLoadList:kn,binding:mn,_linkedBinding:Jo,_events:ti,_eventsCount:ri,_maxListeners:ei,on:ct,addListener:ni,once:ii,off:oi,removeListener:si,removeAllListeners:ai,emit:li,prependListener:ci,prependOnceListener:ui,listeners:ns,domain:xn,_exiting:Sn,config:En,dlopen:Qo,uptime:rs,_getActiveRequests:Xo,_getActiveHandles:Zo,reallyExit:An,_kill:In,cpuUsage:Jt,resourceUsage:Tn,memoryUsage:Cn,kill:On,exit:Pn,openStdin:Mn,allowedNodeEnvironmentFlags:Rn,assert:es,features:Ln,_fatalExceptions:Nn,setUncaughtExceptionCaptureCallback:jn,hasUncaughtExceptionCaptureCallback:ts,emitWarning:pn,nextTick:Go,_tickCallback:Un,_debugProcess:Bn,_debugEnd:Dn,_startProfilerIdleNotifier:Fn,_stopProfilerIdleNotifier:$n,stdout:qn,stdin:Wn,stderr:Hn,abort:zn,umask:gn,chdir:yn,cwd:bn,env:cn,title:sn,argv:un,execArgv:hn,pid:Vn,ppid:Kn,execPath:Gn,debugPort:Yn,hrtime:dr,argv0:Jn,_preload_modules:Qn,setSourceMapsEnabled:Xn}}),ce=Ge(()=>{Uc()});function Bc(){if(di)return Bt;di=!0,Bt.byteLength=l,Bt.toByteArray=c,Bt.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(g){var f=g.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=g.indexOf("=");b===-1&&(b=f);var y=b===f?0:4-b%4;return[b,y]}function l(g){var f=i(g),b=f[0],y=f[1];return(b+y)*3/4-y}function a(g,f,b){return(f+b)*3/4-b}function c(g){var f,b=i(g),y=b[0],w=b[1],m=new t(a(g,y,w)),_=0,x=w>0?y-4:y,v;for(v=0;v<x;v+=4)f=e[g.charCodeAt(v)]<<18|e[g.charCodeAt(v+1)]<<12|e[g.charCodeAt(v+2)]<<6|e[g.charCodeAt(v+3)],m[_++]=f>>16&255,m[_++]=f>>8&255,m[_++]=f&255;return w===2&&(f=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[_++]=f&255),w===1&&(f=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[_++]=f>>8&255,m[_++]=f&255),m}function u(g){return s[g>>18&63]+s[g>>12&63]+s[g>>6&63]+s[g&63]}function h(g,f,b){for(var y,w=[],m=f;m<b;m+=3)y=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(y));return w.join("")}function p(g){for(var f,b=g.length,y=b%3,w=[],m=16383,_=0,x=b-y;_<x;_+=m)w.push(h(g,_,_+m>x?x:_+m));return y===1?(f=g[b-1],w.push(s[f>>2]+s[f<<4&63]+"==")):y===2&&(f=(g[b-2]<<8)+g[b-1],w.push(s[f>>10]+s[f>>4&63]+s[f<<2&63]+"=")),w.join("")}return Bt}function Dc(){return fi?Qt:(fi=!0,Qt.read=function(s,e,t,r,o){var n,i,l=o*8-r-1,a=(1<<l)-1,c=a>>1,u=-7,h=t?o-1:0,p=t?-1:1,g=s[e+h];for(h+=p,n=g&(1<<-u)-1,g>>=-u,u+=l;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===a)return i?NaN:(g?-1:1)*(1/0);i=i+Math.pow(2,r),n=n-c}return(g?-1:1)*i*Math.pow(2,n-r)},Qt.write=function(s,e,t,r,o,n){var i,l,a,c=n*8-o-1,u=(1<<c)-1,h=u>>1,p=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,f=r?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,i=u):(i=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-i))<1&&(i--,a*=2),i+h>=1?e+=p/a:e+=p*Math.pow(2,1-h),e*a>=2&&(i++,a/=2),i+h>=u?(l=0,i=u):i+h>=1?(l=(e*a-1)*Math.pow(2,o),i=i+h):(l=e*Math.pow(2,h-1)*Math.pow(2,o),i=0));o>=8;s[t+g]=l&255,g+=f,l/=256,o-=8);for(i=i<<o|l,c+=o;c>0;s[t+g]=i&255,g+=f,i/=256,c-=8);s[t+g-f]|=b*128},Qt)}function Fc(){if(pi)return vt;pi=!0;let s=Bc(),e=Dc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;vt.Buffer=i,vt.SlowBuffer=w,vt.INSPECT_MAX_BYTES=50;let r=2147483647;vt.kMaxLength=r,i.TYPED_ARRAY_SUPPORT=o(),!i.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function o(){try{let d=new Uint8Array(1),k={foo:function(){return 42}};return Object.setPrototypeOf(k,Uint8Array.prototype),Object.setPrototypeOf(d,k),d.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(d){if(d>r)throw new RangeError('The value "'+d+'" is invalid for option "size"');let k=new Uint8Array(d);return Object.setPrototypeOf(k,i.prototype),k}function i(d,k,A){if(typeof d=="number"){if(typeof k=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(d)}return l(d,k,A)}i.poolSize=8192;function l(d,k,A){if(typeof d=="string")return h(d,k);if(ArrayBuffer.isView(d))return g(d);if(d==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof d);if(H(d,ArrayBuffer)||d&&H(d.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(d,SharedArrayBuffer)||d&&H(d.buffer,SharedArrayBuffer)))return f(d,k,A);if(typeof d=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=d.valueOf&&d.valueOf();if(B!=null&&B!==d)return i.from(B,k,A);let X=b(d);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof d[Symbol.toPrimitive]=="function")return i.from(d[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 d)}i.from=function(d,k,A){return l(d,k,A)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function a(d){if(typeof d!="number")throw new TypeError('"size" argument must be of type number');if(d<0)throw new RangeError('The value "'+d+'" is invalid for option "size"')}function c(d,k,A){return a(d),d<=0?n(d):k!==void 0?typeof A=="string"?n(d).fill(k,A):n(d).fill(k):n(d)}i.alloc=function(d,k,A){return c(d,k,A)};function u(d){return a(d),n(d<0?0:y(d)|0)}i.allocUnsafe=function(d){return u(d)},i.allocUnsafeSlow=function(d){return u(d)};function h(d,k){if((typeof k!="string"||k==="")&&(k="utf8"),!i.isEncoding(k))throw new TypeError("Unknown encoding: "+k);let A=m(d,k)|0,B=n(A),X=B.write(d,k);return X!==A&&(B=B.slice(0,X)),B}function p(d){let k=d.length<0?0:y(d.length)|0,A=n(k);for(let B=0;B<k;B+=1)A[B]=d[B]&255;return A}function g(d){if(H(d,Uint8Array)){let k=new Uint8Array(d);return f(k.buffer,k.byteOffset,k.byteLength)}return p(d)}function f(d,k,A){if(k<0||d.byteLength<k)throw new RangeError('"offset" is outside of buffer bounds');if(d.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(d):A===void 0?B=new Uint8Array(d,k):B=new Uint8Array(d,k,A),Object.setPrototypeOf(B,i.prototype),B}function b(d){if(i.isBuffer(d)){let k=y(d.length)|0,A=n(k);return A.length===0||d.copy(A,0,0,k),A}if(d.length!==void 0)return typeof d.length!="number"||me(d.length)?n(0):p(d);if(d.type==="Buffer"&&Array.isArray(d.data))return p(d.data)}function y(d){if(d>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return d|0}function w(d){return+d!=d&&(d=0),i.alloc(+d)}i.isBuffer=function(d){return d!=null&&d._isBuffer===!0&&d!==i.prototype},i.compare=function(d,k){if(H(d,Uint8Array)&&(d=i.from(d,d.offset,d.byteLength)),H(k,Uint8Array)&&(k=i.from(k,k.offset,k.byteLength)),!i.isBuffer(d)||!i.isBuffer(k))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(d===k)return 0;let A=d.length,B=k.length;for(let X=0,he=Math.min(A,B);X<he;++X)if(d[X]!==k[X]){A=d[X],B=k[X];break}return A<B?-1:B<A?1:0},i.isEncoding=function(d){switch(String(d).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(d,k){if(!Array.isArray(d))throw new TypeError('"list" argument must be an Array of Buffers');if(d.length===0)return i.alloc(0);let A;if(k===void 0)for(k=0,A=0;A<d.length;++A)k+=d[A].length;let B=i.allocUnsafe(k),X=0;for(A=0;A<d.length;++A){let he=d[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(d,k){if(i.isBuffer(d))return d.length;if(ArrayBuffer.isView(d)||H(d,ArrayBuffer))return d.byteLength;if(typeof d!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof d);let A=d.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 $(d).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(d).length;default:if(X)return B?-1:$(d).length;k=(""+k).toLowerCase(),X=!0}}i.byteLength=m;function _(d,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(d||(d="utf8");;)switch(d){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: "+d);d=(d+"").toLowerCase(),B=!0}}i.prototype._isBuffer=!0;function x(d,k,A){let B=d[k];d[k]=d[A],d[A]=B}i.prototype.swap16=function(){let d=this.length;if(d%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let k=0;k<d;k+=2)x(this,k,k+1);return this},i.prototype.swap32=function(){let d=this.length;if(d%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let k=0;k<d;k+=4)x(this,k,k+3),x(this,k+1,k+2);return this},i.prototype.swap64=function(){let d=this.length;if(d%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let k=0;k<d;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 d=this.length;return d===0?"":arguments.length===0?q(this,0,d):_.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(d){if(!i.isBuffer(d))throw new TypeError("Argument must be a Buffer");return this===d?!0:i.compare(this,d)===0},i.prototype.inspect=function(){let d="",k=vt.INSPECT_MAX_BYTES;return d=this.toString("hex",0,k).replace(/(.{2})/g,"$1 ").trim(),this.length>k&&(d+=" ... "),"<Buffer "+d+">"},t&&(i.prototype[t]=i.prototype.inspect),i.prototype.compare=function(d,k,A,B,X){if(H(d,Uint8Array)&&(d=i.from(d,d.offset,d.byteLength)),!i.isBuffer(d))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof d);if(k===void 0&&(k=0),A===void 0&&(A=d?d.length:0),B===void 0&&(B=0),X===void 0&&(X=this.length),k<0||A>d.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===d)return 0;let he=X-B,ke=A-k,z=Math.min(he,ke),ie=this.slice(B,X),Ee=d.slice(k,A);for(let Ae=0;Ae<z;++Ae)if(ie[Ae]!==Ee[Ae]){he=ie[Ae],ke=Ee[Ae];break}return he<ke?-1:ke<he?1:0};function v(d,k,A,B,X){if(d.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:d.length-1),A<0&&(A=d.length+A),A>=d.length){if(X)return-1;A=d.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(d,k,A,B,X);if(typeof k=="number")return k=k&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(d,k,A):Uint8Array.prototype.lastIndexOf.call(d,k,A):E(d,[k],A,B,X);throw new TypeError("val must be string, number or Buffer")}function E(d,k,A,B,X){let he=1,ke=d.length,z=k.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(d.length<2||k.length<2)return-1;he=2,ke/=2,z/=2,A/=2}function ie(Ae,Ie){return he===1?Ae[Ie]:Ae.readUInt16BE(Ie*he)}let Ee;if(X){let Ae=-1;for(Ee=A;Ee<ke;Ee++)if(ie(d,Ee)===ie(k,Ae===-1?0:Ee-Ae)){if(Ae===-1&&(Ae=Ee),Ee-Ae+1===z)return Ae*he}else Ae!==-1&&(Ee-=Ee-Ae),Ae=-1}else for(A+z>ke&&(A=ke-z),Ee=A;Ee>=0;Ee--){let Ae=!0;for(let Ie=0;Ie<z;Ie++)if(ie(d,Ee+Ie)!==ie(k,Ie)){Ae=!1;break}if(Ae)return Ee}return-1}i.prototype.includes=function(d,k,A){return this.indexOf(d,k,A)!==-1},i.prototype.indexOf=function(d,k,A){return v(this,d,k,A,!0)},i.prototype.lastIndexOf=function(d,k,A){return v(this,d,k,A,!1)};function S(d,k,A,B){A=Number(A)||0;let X=d.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;d[A+ke]=z}return ke}function I(d,k,A,B){return ye($(k,d.length-A),d,A,B)}function O(d,k,A,B){return ye(ee(k),d,A,B)}function P(d,k,A,B){return ye(fe(k),d,A,B)}function j(d,k,A,B){return ye(de(k,d.length-A),d,A,B)}i.prototype.write=function(d,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),d.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,d,k,A);case"utf8":case"utf-8":return I(this,d,k,A);case"ascii":case"latin1":case"binary":return O(this,d,k,A);case"base64":return P(this,d,k,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,d,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(d,k,A){return k===0&&A===d.length?s.fromByteArray(d):s.fromByteArray(d.slice(k,A))}function q(d,k,A){A=Math.min(d.length,A);let B=[],X=k;for(;X<A;){let he=d[X],ke=null,z=he>239?4:he>223?3:he>191?2:1;if(X+z<=A){let ie,Ee,Ae,Ie;switch(z){case 1:he<128&&(ke=he);break;case 2:ie=d[X+1],(ie&192)===128&&(Ie=(he&31)<<6|ie&63,Ie>127&&(ke=Ie));break;case 3:ie=d[X+1],Ee=d[X+2],(ie&192)===128&&(Ee&192)===128&&(Ie=(he&15)<<12|(ie&63)<<6|Ee&63,Ie>2047&&(Ie<55296||Ie>57343)&&(ke=Ie));break;case 4:ie=d[X+1],Ee=d[X+2],Ae=d[X+3],(ie&192)===128&&(Ee&192)===128&&(Ae&192)===128&&(Ie=(he&15)<<18|(ie&63)<<12|(Ee&63)<<6|Ae&63,Ie>65535&&Ie<1114112&&(ke=Ie))}}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(d){let k=d.length;if(k<=D)return String.fromCharCode.apply(String,d);let A="",B=0;for(;B<k;)A+=String.fromCharCode.apply(String,d.slice(B,B+=D));return A}function ae(d,k,A){let B="";A=Math.min(d.length,A);for(let X=k;X<A;++X)B+=String.fromCharCode(d[X]&127);return B}function Y(d,k,A){let B="";A=Math.min(d.length,A);for(let X=k;X<A;++X)B+=String.fromCharCode(d[X]);return B}function V(d,k,A){let B=d.length;(!k||k<0)&&(k=0),(!A||A<0||A>B)&&(A=B);let X="";for(let he=k;he<A;++he)X+=ve[d[he]];return X}function re(d,k,A){let B=d.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(d,k){let A=this.length;d=~~d,k=k===void 0?A:~~k,d<0?(d+=A,d<0&&(d=0)):d>A&&(d=A),k<0?(k+=A,k<0&&(k=0)):k>A&&(k=A),k<d&&(k=d);let B=this.subarray(d,k);return Object.setPrototypeOf(B,i.prototype),B};function F(d,k,A){if(d%1!==0||d<0)throw new RangeError("offset is not uint");if(d+k>A)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(d,k,A){d=d>>>0,k=k>>>0,A||F(d,k,this.length);let B=this[d],X=1,he=0;for(;++he<k&&(X*=256);)B+=this[d+he]*X;return B},i.prototype.readUintBE=i.prototype.readUIntBE=function(d,k,A){d=d>>>0,k=k>>>0,A||F(d,k,this.length);let B=this[d+--k],X=1;for(;k>0&&(X*=256);)B+=this[d+--k]*X;return B},i.prototype.readUint8=i.prototype.readUInt8=function(d,k){return d=d>>>0,k||F(d,1,this.length),this[d]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(d,k){return d=d>>>0,k||F(d,2,this.length),this[d]|this[d+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(d,k){return d=d>>>0,k||F(d,2,this.length),this[d]<<8|this[d+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(d,k){return d=d>>>0,k||F(d,4,this.length),(this[d]|this[d+1]<<8|this[d+2]<<16)+this[d+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(d,k){return d=d>>>0,k||F(d,4,this.length),this[d]*16777216+(this[d+1]<<16|this[d+2]<<8|this[d+3])},i.prototype.readBigUInt64LE=se(function(d){d=d>>>0,J(d,"offset");let k=this[d],A=this[d+7];(k===void 0||A===void 0)&&ge(d,this.length-8);let B=k+this[++d]*2**8+this[++d]*2**16+this[++d]*2**24,X=this[++d]+this[++d]*2**8+this[++d]*2**16+A*2**24;return BigInt(B)+(BigInt(X)<<BigInt(32))}),i.prototype.readBigUInt64BE=se(function(d){d=d>>>0,J(d,"offset");let k=this[d],A=this[d+7];(k===void 0||A===void 0)&&ge(d,this.length-8);let B=k*2**24+this[++d]*2**16+this[++d]*2**8+this[++d],X=this[++d]*2**24+this[++d]*2**16+this[++d]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(X)}),i.prototype.readIntLE=function(d,k,A){d=d>>>0,k=k>>>0,A||F(d,k,this.length);let B=this[d],X=1,he=0;for(;++he<k&&(X*=256);)B+=this[d+he]*X;return X*=128,B>=X&&(B-=Math.pow(2,8*k)),B},i.prototype.readIntBE=function(d,k,A){d=d>>>0,k=k>>>0,A||F(d,k,this.length);let B=k,X=1,he=this[d+--B];for(;B>0&&(X*=256);)he+=this[d+--B]*X;return X*=128,he>=X&&(he-=Math.pow(2,8*k)),he},i.prototype.readInt8=function(d,k){return d=d>>>0,k||F(d,1,this.length),this[d]&128?(255-this[d]+1)*-1:this[d]},i.prototype.readInt16LE=function(d,k){d=d>>>0,k||F(d,2,this.length);let A=this[d]|this[d+1]<<8;return A&32768?A|4294901760:A},i.prototype.readInt16BE=function(d,k){d=d>>>0,k||F(d,2,this.length);let A=this[d+1]|this[d]<<8;return A&32768?A|4294901760:A},i.prototype.readInt32LE=function(d,k){return d=d>>>0,k||F(d,4,this.length),this[d]|this[d+1]<<8|this[d+2]<<16|this[d+3]<<24},i.prototype.readInt32BE=function(d,k){return d=d>>>0,k||F(d,4,this.length),this[d]<<24|this[d+1]<<16|this[d+2]<<8|this[d+3]},i.prototype.readBigInt64LE=se(function(d){d=d>>>0,J(d,"offset");let k=this[d],A=this[d+7];(k===void 0||A===void 0)&&ge(d,this.length-8);let B=this[d+4]+this[d+5]*2**8+this[d+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(k+this[++d]*256+this[++d]*65536+this[++d]*16777216)}),i.prototype.readBigInt64BE=se(function(d){d=d>>>0,J(d,"offset");let k=this[d],A=this[d+7];(k===void 0||A===void 0)&&ge(d,this.length-8);let B=(k<<24)+this[++d]*2**16+this[++d]*2**8+this[++d];return(BigInt(B)<<BigInt(32))+BigInt(this[++d]*16777216+this[++d]*65536+this[++d]*256+A)}),i.prototype.readFloatLE=function(d,k){return d=d>>>0,k||F(d,4,this.length),e.read(this,d,!0,23,4)},i.prototype.readFloatBE=function(d,k){return d=d>>>0,k||F(d,4,this.length),e.read(this,d,!1,23,4)},i.prototype.readDoubleLE=function(d,k){return d=d>>>0,k||F(d,8,this.length),e.read(this,d,!0,52,8)},i.prototype.readDoubleBE=function(d,k){return d=d>>>0,k||F(d,8,this.length),e.read(this,d,!1,52,8)};function Z(d,k,A,B,X,he){if(!i.isBuffer(d))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>d.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(d,k,A,B){if(d=+d,k=k>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,d,k,A,ke,0)}let X=1,he=0;for(this[k]=d&255;++he<A&&(X*=256);)this[k+he]=d/X&255;return k+A},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(d,k,A,B){if(d=+d,k=k>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,d,k,A,ke,0)}let X=A-1,he=1;for(this[k+X]=d&255;--X>=0&&(he*=256);)this[k+X]=d/he&255;return k+A},i.prototype.writeUint8=i.prototype.writeUInt8=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,1,255,0),this[k]=d&255,k+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,2,65535,0),this[k]=d&255,this[k+1]=d>>>8,k+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,2,65535,0),this[k]=d>>>8,this[k+1]=d&255,k+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,4,4294967295,0),this[k+3]=d>>>24,this[k+2]=d>>>16,this[k+1]=d>>>8,this[k]=d&255,k+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,4,4294967295,0),this[k]=d>>>24,this[k+1]=d>>>16,this[k+2]=d>>>8,this[k+3]=d&255,k+4};function M(d,k,A,B,X){G(k,B,X,d,A,7);let he=Number(k&BigInt(4294967295));d[A++]=he,he=he>>8,d[A++]=he,he=he>>8,d[A++]=he,he=he>>8,d[A++]=he;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return d[A++]=ke,ke=ke>>8,d[A++]=ke,ke=ke>>8,d[A++]=ke,ke=ke>>8,d[A++]=ke,A}function Q(d,k,A,B,X){G(k,B,X,d,A,7);let he=Number(k&BigInt(4294967295));d[A+7]=he,he=he>>8,d[A+6]=he,he=he>>8,d[A+5]=he,he=he>>8,d[A+4]=he;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return d[A+3]=ke,ke=ke>>8,d[A+2]=ke,ke=ke>>8,d[A+1]=ke,ke=ke>>8,d[A]=ke,A+8}i.prototype.writeBigUInt64LE=se(function(d,k=0){return M(this,d,k,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=se(function(d,k=0){return Q(this,d,k,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(d,k,A,B){if(d=+d,k=k>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,d,k,A,z-1,-z)}let X=0,he=1,ke=0;for(this[k]=d&255;++X<A&&(he*=256);)d<0&&ke===0&&this[k+X-1]!==0&&(ke=1),this[k+X]=(d/he>>0)-ke&255;return k+A},i.prototype.writeIntBE=function(d,k,A,B){if(d=+d,k=k>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,d,k,A,z-1,-z)}let X=A-1,he=1,ke=0;for(this[k+X]=d&255;--X>=0&&(he*=256);)d<0&&ke===0&&this[k+X+1]!==0&&(ke=1),this[k+X]=(d/he>>0)-ke&255;return k+A},i.prototype.writeInt8=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,1,127,-128),d<0&&(d=255+d+1),this[k]=d&255,k+1},i.prototype.writeInt16LE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,2,32767,-32768),this[k]=d&255,this[k+1]=d>>>8,k+2},i.prototype.writeInt16BE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,2,32767,-32768),this[k]=d>>>8,this[k+1]=d&255,k+2},i.prototype.writeInt32LE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,4,2147483647,-2147483648),this[k]=d&255,this[k+1]=d>>>8,this[k+2]=d>>>16,this[k+3]=d>>>24,k+4},i.prototype.writeInt32BE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,4,2147483647,-2147483648),d<0&&(d=4294967295+d+1),this[k]=d>>>24,this[k+1]=d>>>16,this[k+2]=d>>>8,this[k+3]=d&255,k+4},i.prototype.writeBigInt64LE=se(function(d,k=0){return M(this,d,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=se(function(d,k=0){return Q(this,d,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(d,k,A,B,X,he){if(A+B>d.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(d,k,A,B,X){return k=+k,A=A>>>0,X||be(d,k,A,4),e.write(d,k,A,B,23,4),A+4}i.prototype.writeFloatLE=function(d,k,A){return te(this,d,k,!0,A)},i.prototype.writeFloatBE=function(d,k,A){return te(this,d,k,!1,A)};function we(d,k,A,B,X){return k=+k,A=A>>>0,X||be(d,k,A,8),e.write(d,k,A,B,52,8),A+8}i.prototype.writeDoubleLE=function(d,k,A){return we(this,d,k,!0,A)},i.prototype.writeDoubleBE=function(d,k,A){return we(this,d,k,!1,A)},i.prototype.copy=function(d,k,A,B){if(!i.isBuffer(d))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),k>=d.length&&(k=d.length),k||(k=0),B>0&&B<A&&(B=A),B===A||d.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),d.length-k<B-A&&(B=d.length-k+A);let X=B-A;return this===d&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(k,A,B):Uint8Array.prototype.set.call(d,this.subarray(A,B),k),X},i.prototype.fill=function(d,k,A,B){if(typeof d=="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(d.length===1){let he=d.charCodeAt(0);(B==="utf8"&&he<128||B==="latin1")&&(d=he)}}else typeof d=="number"?d=d&255:typeof d=="boolean"&&(d=Number(d));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,d||(d=0);let X;if(typeof d=="number")for(X=k;X<A;++X)this[X]=d;else{let he=i.isBuffer(d)?d:i.from(d,B),ke=he.length;if(ke===0)throw new TypeError('The value "'+d+'" is invalid for argument "value"');for(X=0;X<A-k;++X)this[X+k]=he[X%ke]}return this};let K={};function N(d,k,A){K[d]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:k.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${d}]`,this.stack,delete this.name}get code(){return d}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${d}]: ${this.message}`}}}N("ERR_BUFFER_OUT_OF_BOUNDS",function(d){return d?`${d} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),N("ERR_INVALID_ARG_TYPE",function(d,k){return`The "${d}" argument must be of type number. Received type ${typeof k}`},TypeError),N("ERR_OUT_OF_RANGE",function(d,k,A){let B=`The value of "${d}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),B+=` It must be ${k}. Received ${X}`,B},RangeError);function ne(d){let k="",A=d.length,B=d[0]==="-"?1:0;for(;A>=B+4;A-=3)k=`_${d.slice(A-3,A)}${k}`;return`${d.slice(0,A)}${k}`}function W(d,k,A){J(k,"offset"),(d[k]===void 0||d[k+A]===void 0)&&ge(k,d.length-(A+1))}function G(d,k,A,B,X,he){if(d>A||d<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,d)}W(B,X,he)}function J(d,k){if(typeof d!="number")throw new K.ERR_INVALID_ARG_TYPE(k,"number",d)}function ge(d,k,A){throw Math.floor(d)!==d?(J(d,A),new K.ERR_OUT_OF_RANGE("offset","an integer",d)):k<0?new K.ERR_BUFFER_OUT_OF_BOUNDS:new K.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${k}`,d)}let oe=/[^+/0-9A-Za-z-_]/g;function R(d){if(d=d.split("=")[0],d=d.trim().replace(oe,""),d.length<2)return"";for(;d.length%4!==0;)d=d+"=";return d}function $(d,k){k=k||1/0;let A,B=d.length,X=null,he=[];for(let ke=0;ke<B;++ke){if(A=d.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(d){let k=[];for(let A=0;A<d.length;++A)k.push(d.charCodeAt(A)&255);return k}function de(d,k){let A,B,X,he=[];for(let ke=0;ke<d.length&&!((k-=2)<0);++ke)A=d.charCodeAt(ke),B=A>>8,X=A%256,he.push(X),he.push(B);return he}function fe(d){return s.toByteArray(R(d))}function ye(d,k,A,B){let X;for(X=0;X<B&&!(X+A>=k.length||X>=d.length);++X)k[X+A]=d[X];return X}function H(d,k){return d instanceof k||d!=null&&d.constructor!=null&&d.constructor.name!=null&&d.constructor.name===k.name}function me(d){return d!==d}let ve=(function(){let d="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]=d[A]+d[X]}return k})();function se(d){return typeof BigInt>"u"?Ce:d}function Ce(){throw new Error("BigInt not supported")}return vt}var Bt,di,Qt,fi,vt,pi,$c=Ge(()=>{le(),ue(),ce(),Bt={},di=!1,Qt={},fi=!1,vt={},pi=!1}),Fe={};Ut(Fe,{Buffer:()=>pr,INSPECT_MAX_BYTES:()=>is,default:()=>ht,kMaxLength:()=>os});var ht,pr,is,os,$e=Ge(()=>{le(),ue(),ce(),$c(),ht=Fc(),ht.Buffer,ht.SlowBuffer,ht.INSPECT_MAX_BYTES,ht.kMaxLength,pr=ht.Buffer,is=ht.INSPECT_MAX_BYTES,os=ht.kMaxLength}),ue=Ge(()=>{$e()}),je=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}}),ss=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"{}"}}}}),Ve=pe((s,e)=>{le(),ue(),ce();var{format:t,inspect:r}=ss(),{AggregateError:o}=je(),n=globalThis.AggregateError||o,i=Symbol("kIsNodeError"),l=["string","function","number","object","Function","Object","boolean","bigint","symbol"],a=/^([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 g(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 f(m,_,x){x||(x=Error);class v extends x{constructor(...S){super(g(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 b(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)=>{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"),l.includes(P)?E.push(P.toLowerCase()):a.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),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)=>{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),f("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),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:b(y),hideStackFrames:b,codes:u}}),Xt=pe((s,e)=>{le(),ue(),ce();var{AbortController:t,AbortSignal:r}=typeof self<"u"?self:typeof window<"u"?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t}),wt={};Ut(wt,{EventEmitter:()=>as,default:()=>Dt,defaultMaxListeners:()=>ls,init:()=>cs,listenerCount:()=>us,on:()=>hs,once:()=>ds});function qc(){if(mi)return Zt;mi=!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)}Zt=n,Zt.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var i=10;function l(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 a(x){return x._maxListeners===void 0?n.defaultMaxListeners:x._maxListeners}n.prototype.getMaxListeners=function(){return a(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=f(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(l(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=a(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 l(v),this.on(x,h(this,x,v)),this},n.prototype.prependOnceListener=function(x,v){return l(v),this.prependListener(x,h(this,x,v)),this},n.prototype.removeListener=function(x,v){var E,S,I,O,P;if(l(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():b(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):f(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):g.call(x,v)},n.prototype.listenerCount=g;function g(x){var v=this._events;if(v!==void 0){var E=v[x];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(x,v){for(var E=new Array(v),S=0;S<v;++S)E[S]=x[S];return E}function b(x,v){for(;v+1<x.length;v++)x[v]=x[v+1];x.pop()}function y(x){for(var v=new Array(x.length),E=0;E<v.length;++E)v[E]=x[E].listener||x[E];return v}function w(x,v){return new Promise(function(E,S){function I(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 Zt}var Zt,mi,Dt,as,ls,cs,us,hs,ds,Tt=Ge(()=>{le(),ue(),ce(),Zt={},mi=!1,Dt=qc(),Dt.once,Dt.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)})},Dt.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,l),s.removeListener("error",a),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,l),s.removeListener("error",a)},[Symbol.asyncIterator](){return this}};return s.on(e,l),s.on("error",a),i;function l(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function a(c){n=!0;let u=r.shift();u?u.reject(c):o=c,i.return()}},{EventEmitter:as,defaultMaxListeners:ls,init:cs,listenerCount:us,on:hs,once:ds}=Dt}),Ye=pe((s,e)=>{le(),ue(),ce();var t=($e(),Re(Fe)),{format:r,inspect:o}=ss(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ve(),{kResistStopPropagation:i,AggregateError:l,SymbolDispose:a}=je(),c=globalThis.AbortSignal||Xt().AbortSignal,u=globalThis.AbortController||Xt().AbortController,h=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,g=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)},b=(y,w)=>{if(typeof y!="function")throw new n(w,"Function",y)};e.exports={AggregateError:l,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:g,deprecate(y,w){return y},addAbortListener:(Tt(),Re(wt)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);f(y,"signal"),b(w,"listener");let m;return y.aborted?queueMicrotask(()=>w()):(y.addEventListener("abort",w,{__proto__:null,once:!0,[i]:!0}),m=()=>{y.removeEventListener("abort",w)}),{__proto__:null,[a](){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")}),er=pe((s,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:o,ArrayPrototypeMap:n,NumberIsInteger:i,NumberIsNaN:l,NumberMAX_SAFE_INTEGER:a,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:h,RegExpPrototypeExec:p,String:g,StringPrototypeToUpperCase:f,StringPrototypeTrim:b}=je(),{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}}=Ve(),{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=a)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),ae=y((H,me,ve=-2147483648,se=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),Y=y((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);let se=ve?1:0,Ce=4294967295;if(H<se||H>Ce)throw new x(me,`>= ${se} && <= ${Ce}`,H)});function V(H,me){if(typeof H!="string")throw new m(me,"string",H)}function re(H,me,ve=void 0,se){if(typeof H!="number")throw new m(me,"number",H);if(ve!=null&&H<ve||se!=null&&H>se||(ve!=null||se!=null)&&l(H))throw new x(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&se!=null?" && ":""}${se!=null?`<= ${se}`:""}`,H)}var F=y((H,me,ve)=>{if(!r(ve,H)){let se="must be one of: "+o(n(ve,Ce=>typeof Ce=="string"?`'${Ce}'`:g(Ce)),", ");throw new _(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),Ce=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!se&&t(H)||typeof H!="object"&&(!Ce||typeof H!="function"))throw new m(me,"Object",H)}),be=y((H,me)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(me,"a dictionary",H)}),te=y((H,me,ve=0)=>{if(!t(H))throw new m(me,"Array",H);if(H.length<ve){let se=`must be longer than ${ve}`;throw new _(me,H,se)}});function we(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)V(H[ve],`${me}[${ve}]`)}function K(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)Z(H[ve],`${me}[${ve}]`)}function N(H,me){te(H,me);for(let ve=0;ve<H.length;ve++){let se=H[ve],Ce=`${me}[${ve}]`;if(se==null)throw new m(Ce,"AbortSignal",se);ge(se,Ce)}}function ne(H,me="signal"){if(V(H,me),O[H]===void 0)throw O[f(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"&&b(H).length===0||+H!==+H>>>0||H>65535||H===0&&!ve)throw new w(me,H,ve);return H|0}var ge=y((H,me)=>{if(H!==void 0&&(H===null||typeof H!="object"||!("aborted"in H)))throw new m(me,"AbortSignal",H)}),oe=y((H,me)=>{if(typeof H!="function")throw new m(me,"Function",H)}),R=y((H,me)=>{if(typeof H!="function"||S(H))throw new m(me,"Function",H)}),$=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 Ce=H[se];fe(Ce,"hints"),ve+=Ce,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:F,validatePlainFunction:R,validatePort:J,validateSignalName:ne,validateString:V,validateUint32:Y,validateUndefined:$,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:ye}}),Ct=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 l(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 a(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 g(){!u||!h||(u=!1,h.length?c=h.concat(c):p=-1,c.length&&f())}function f(){if(!u){var w=l(g);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,a(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 b(w,m)),c.length===1&&!u&&l(f)};function b(w,m){this.fun=w,this.array=m}b.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function y(){}t.on=y,t.addListener=y,t.once=y,t.off=y,t.removeListener=y,t.removeAllListeners=y,t.emit=y,t.prependListener=y,t.prependOnceListener=y,t.listeners=function(w){return[]},t.binding=function(w){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(w){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),dt=pe((s,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:o}=je(),n=o("nodejs.stream.destroyed"),i=o("nodejs.stream.errored"),l=o("nodejs.stream.readable"),a=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 g(M){var Q;return!!(M&&typeof M.write=="function"&&typeof M.on=="function"&&(!M._readableState||((Q=M._writableState)===null||Q===void 0?void 0:Q.writable)!==!1))}function f(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function b(M){return M&&(M._readableState||M._writableState||typeof M.write=="function"&&typeof M.on=="function"||typeof M.pipe=="function"&&typeof M.on=="function")}function y(M){return!!(M&&!b(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function w(M){return!!(M&&!b(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!b(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function _(M){return y(M)||w(M)||m(M)}function x(M,Q){return M==null?!1:Q===!0?typeof M[t]=="function":Q===!1?typeof M[r]=="function":typeof M[t]=="function"||typeof M[r]=="function"}function v(M){if(!b(M))return null;let Q=M._writableState,be=M._readableState,te=Q||be;return!!(M.destroyed||M[n]||te!=null&&te.destroyed)}function E(M){if(!g(M))return null;if(M.writableEnded===!0)return!0;let Q=M._writableState;return Q!=null&&Q.errored?!1:typeof Q?.ended!="boolean"?null:Q.ended}function S(M,Q){if(!g(M))return null;if(M.writableFinished===!0)return!0;let be=M._writableState;return be!=null&&be.errored?!1:typeof be?.finished!="boolean"?null:!!(be.finished||Q===!1&&be.ended===!0&&be.length===0)}function I(M){if(!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[l]!=null?M[l]:typeof M?.readable!="boolean"?null:v(M)?!1:p(M)&&M.readable&&!O(M)}function j(M){return M&&M[a]!=null?M[a]:typeof M?.writable!="boolean"?null:v(M)?!1:g(M)&&M.writable&&!E(M)}function T(M,Q){return b(M)?v(M)?!0:!(Q?.readable!==!1&&P(M)||Q?.writable!==!1&&j(M)):null}function q(M){var Q,be;return b(M)?M.writableErrored?M.writableErrored:(Q=(be=M._writableState)===null||be===void 0?void 0:be.errored)!==null&&Q!==void 0?Q:null:null}function D(M){var Q,be;return b(M)?M.readableErrored?M.readableErrored:(Q=(be=M._readableState)===null||be===void 0?void 0:be.errored)!==null&&Q!==void 0?Q:null:null}function U(M){if(!b(M))return null;if(typeof M.closed=="boolean")return M.closed;let Q=M._writableState,be=M._readableState;return typeof Q?.closed=="boolean"||typeof be?.closed=="boolean"?Q?.closed||be?.closed:typeof M._closed=="boolean"&&ae(M)?M._closed:null}function ae(M){return typeof M._closed=="boolean"&&typeof M._defaultKeepAlive=="boolean"&&typeof M._removedConnection=="boolean"&&typeof M._removedContLen=="boolean"}function Y(M){return typeof M._sent100=="boolean"&&ae(M)}function V(M){var Q;return typeof M._consuming=="boolean"&&typeof M._dumped=="boolean"&&((Q=M.req)===null||Q===void 0?void 0:Q.upgradeOrConnect)===void 0}function re(M){if(!b(M))return null;let Q=M._writableState,be=M._readableState,te=Q||be;return!te&&Y(M)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function F(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:F,kIsDisturbed:c,isErrored:Z,kIsErrored:i,isReadable:P,kIsReadable:l,kIsClosedPromise:u,kControllerErrorFunction:h,kIsWritable:a,isClosed:U,isDuplexNodeStream:f,isFinished:T,isIterable:x,isReadableNodeStream:p,isReadableStream:y,isReadableEnded:I,isReadableFinished:O,isReadableErrored:D,isNodeStream:b,isWebStream:_,isWritable:j,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:E,isWritableFinished:S,isWritableErrored:q,isServerRequest:V,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),_t=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{AbortError:r,codes:o}=Ve(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=o,{kEmptyObject:l,once:a}=Ye(),{validateAbortSignal:c,validateFunction:u,validateObject:h,validateBoolean:p}=er(),{Promise:g,PromisePrototypeThen:f,SymbolDispose:b}=je(),{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}=dt(),D;function U(F){return F.setHeader&&typeof F.abort=="function"}var ae=()=>{};function Y(F,Z,M){var Q,be;if(arguments.length===2?(M=Z,Z=l):Z==null?Z=l:h(Z,"options"),u(M,"callback"),c(Z.signal,"options.signal"),M=a(M),_(F)||I(F))return V(F,Z,M);if(!j(F))throw new n("stream",["ReadableStream","WritableStream","Stream"],F);let te=(Q=Z.readable)!==null&&Q!==void 0?Q:m(F),we=(be=Z.writable)!==null&&be!==void 0?be:S(F),K=F._writableState,N=F._readableState,ne=()=>{F.writable||J()},W=T(F)&&m(F)===te&&S(F)===we,G=O(F,!1),J=()=>{G=!0,F.destroyed&&(W=!1),!(W&&(!F.readable||te))&&(!te||ge)&&M.call(F)},ge=x(F,!1),oe=()=>{ge=!0,F.destroyed&&(W=!1),!(W&&(!F.writable||we))&&(!we||G)&&M.call(F)},R=H=>{M.call(F,H)},$=y(F),ee=()=>{$=!0;let H=P(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);if(te&&!ge&&m(F,!0)&&!x(F,!1))return M.call(F,new i);if(we&&!G&&!O(F,!1))return M.call(F,new i);M.call(F)},de=()=>{$=!0;let H=P(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);M.call(F)},fe=()=>{F.req.on("finish",J)};U(F)?(F.on("complete",J),W||F.on("abort",ee),F.req?fe():F.on("request",fe)):we&&!K&&(F.on("end",ne),F.on("close",ne)),!W&&typeof F.aborted=="boolean"&&F.on("aborted",ee),F.on("end",oe),F.on("finish",J),Z.error!==!1&&F.on("error",R),F.on("close",ee),$?t.nextTick(ee):K!=null&&K.errorEmitted||N!=null&&N.errorEmitted?W||t.nextTick(de):(!te&&(!W||w(F))&&(G||E(F)===!1)||!we&&(!W||E(F))&&(ge||w(F)===!1)||N&&F.req&&F.aborted)&&t.nextTick(de);let ye=()=>{M=ae,F.removeListener("aborted",ee),F.removeListener("complete",J),F.removeListener("abort",ee),F.removeListener("request",fe),F.req&&F.req.removeListener("finish",J),F.removeListener("end",ne),F.removeListener("close",ne),F.removeListener("finish",J),F.removeListener("end",oe),F.removeListener("error",R),F.removeListener("close",ee)};if(Z.signal&&!$){let H=()=>{let me=M;ye(),me.call(F,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=a((...se)=>{me[b](),ve.apply(F,se)})}}return ye}function V(F,Z,M){let Q=!1,be=ae;if(Z.signal)if(be=()=>{Q=!0,M.call(F,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=a((...N)=>{we[b](),K.apply(F,N)})}let te=(...we)=>{Q||t.nextTick(()=>M.apply(F,we))};return f(F[q].promise,te,te),ae}function re(F,Z){var M;let Q=!1;return Z===null&&(Z=l),(M=Z)!==null&&M!==void 0&&M.cleanup&&(p(Z.cleanup,"cleanup"),Q=Z.cleanup),new g((be,te)=>{let we=Y(F,Z,K=>{Q&&we(),K?te(K):be()})})}e.exports=Y,e.exports.finished=re}),Ft=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:n}=Ve(),{Symbol:i}=je(),{kIsDestroyed:l,isDestroyed:a,isFinished:c,isServerRequest:u}=dt(),h=i("kDestroy"),p=i("kConstruct");function g(T,q,D){T&&(T.stack,q&&!q.errored&&(q.errored=T),D&&!D.errored&&(D.errored=T))}function f(T,q){let D=this._readableState,U=this._writableState,ae=U||D;return U!=null&&U.destroyed||D!=null&&D.destroyed?(typeof q=="function"&&q(),this):(g(T,U,D),U&&(U.destroyed=!0),D&&(D.destroyed=!0),ae.constructed?b(this,T,q):this.once(h,function(Y){b(this,r(Y,T),q)}),this)}function b(T,q,D){let U=!1;function ae(Y){if(U)return;U=!0;let V=T._readableState,re=T._writableState;g(Y,re,V),re&&(re.closed=!0),V&&(V.closed=!0),typeof D=="function"&&D(Y),Y?t.nextTick(y,T,Y):t.nextTick(w,T)}try{T._destroy(q||null,ae)}catch(Y){ae(Y)}}function y(T,q){m(T,q),w(T)}function w(T){let q=T._readableState,D=T._writableState;D&&(D.closeEmitted=!0),q&&(q.closeEmitted=!0),(D!=null&&D.emitClose||q!=null&&q.emitClose)&&T.emit("close")}function m(T,q){let D=T._readableState,U=T._writableState;U!=null&&U.errorEmitted||D!=null&&D.errorEmitted||(U&&(U.errorEmitted=!0),D&&(D.errorEmitted=!0),T.emit("error",q))}function _(){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||a(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[l]=!0))}e.exports={construct:v,destroyer:j,destroy:f,undestroy:_,errorOrDestroy:x}}),gi=pe((s,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=je(),{EventEmitter:o}=(Tt(),Re(wt));function n(l){o.call(this,l)}r(n.prototype,o.prototype),r(n,o),n.prototype.pipe=function(l,a){let c=this;function u(w){l.writable&&l.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function h(){c.readable&&c.resume&&c.resume()}l.on("drain",h),!l._isStdio&&(!a||a.end!==!1)&&(c.on("end",g),c.on("close",f));let p=!1;function g(){p||(p=!0,l.end())}function f(){p||(p=!0,typeof l.destroy=="function"&&l.destroy())}function b(w){y(),o.listenerCount(this,"error")===0&&this.emit("error",w)}i(c,"error",b),i(l,"error",b);function y(){c.removeListener("data",u),l.removeListener("drain",h),c.removeListener("end",g),c.removeListener("close",f),c.removeListener("error",b),l.removeListener("error",b),c.removeListener("end",y),c.removeListener("close",y),l.removeListener("close",y)}return c.on("end",y),c.on("close",y),l.on("close",y),l.emit("pipe",c),l};function i(l,a,c){if(typeof l.prependListener=="function")return l.prependListener(a,c);!l._events||!l._events[a]?l.on(a,c):t(l._events[a])?l._events[a].unshift(c):l._events[a]=[c,l._events[a]]}e.exports={Stream:n,prependListener:i}}),mr=pe((s,e)=>{le(),ue(),ce();var{SymbolDispose:t}=je(),{AbortError:r,codes:o}=Ve(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:l}=dt(),a=_t(),{ERR_INVALID_ARG_TYPE:c}=o,u,h=(p,g)=>{if(typeof p!="object"||!("aborted"in p))throw new c(g,"AbortSignal",p)};e.exports.addAbortSignal=function(p,g){if(h(p,"signal"),!n(g)&&!i(g))throw new c("stream",["ReadableStream","WritableStream","Stream"],g);return e.exports.addAbortSignalNoValidate(p,g)},e.exports.addAbortSignalNoValidate=function(p,g){if(typeof p!="object"||!("aborted"in p))return g;let f=n(g)?()=>{g.destroy(new r(void 0,{cause:p.reason}))}:()=>{g[l](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||Ye().addAbortListener;let b=u(p,f);a(g,b[t])}return g}}),Hc=pe((s,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:o,Uint8Array:n}=je(),{Buffer:i}=($e(),Re(Fe)),{inspect:l}=Ye();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(a){let c={data:a,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(a){let c={data:a,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let a=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,a}clear(){this.head=this.tail=null,this.length=0}join(a){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=a+c.data;return u}concat(a){if(this.length===0)return i.alloc(0);let c=i.allocUnsafe(a>>>0),u=this.head,h=0;for(;u;)o(c,u.data,h),h+=u.data.length,u=u.next;return c}consume(a,c){let u=this.head.data;if(a<u.length){let h=u.slice(0,a);return this.head.data=u.slice(a),h}return a===u.length?this.shift():c?this._getString(a):this._getBuffer(a)}first(){return this.head.data}*[r](){for(let a=this.head;a;a=a.next)yield a.data}_getString(a){let c="",u=this.head,h=0;do{let p=u.data;if(a>p.length)c+=p,a-=p.length;else{a===p.length?(c+=p,++h,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,a),this.head=u,u.data=t(p,a));break}++h}while((u=u.next)!==null);return this.length-=h,c}_getBuffer(a){let c=i.allocUnsafe(a),u=a,h=this.head,p=0;do{let g=h.data;if(a>g.length)o(c,g,u-a),a-=g.length;else{a===g.length?(o(c,g,u-a),++p,h.next?this.head=h.next:this.head=this.tail=null):(o(c,new n(g.buffer,g.byteOffset,a),u-a),this.head=h,h.data=g.slice(a));break}++p}while((h=h.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](a,c){return l(this,{...c,depth:0,customInspect:!1})}}}),gr=pe((s,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=je(),{validateInteger:o}=er(),{ERR_INVALID_ARG_VALUE:n}=Ve().codes,i=16*1024,l=16;function a(p,g,f){return p.highWaterMark!=null?p.highWaterMark:g?p[f]:null}function c(p){return p?l:i}function u(p,g){o(g,"value",0),p?l=g:i=g}function h(p,g,f,b){let y=a(g,b,f);if(y!=null){if(!r(y)||y<0){let w=b?`options.${f}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(p.objectMode)}e.exports={getHighWaterMark:h,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),Wc=pe((s,e)=>{le(),ue(),ce();var t=($e(),Re(Fe)),r=t.Buffer;function o(i,l){for(var a in i)l[a]=i[a]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(o(t,s),s.Buffer=n);function n(i,l,a){return r(i,l,a)}n.prototype=Object.create(r.prototype),o(r,n),n.from=function(i,l,a){if(typeof i=="number")throw new TypeError("Argument must not be a number");return r(i,l,a)},n.alloc=function(i,l,a){if(typeof i!="number")throw new TypeError("Argument must be a number");var c=r(i);return l!==void 0?typeof a=="string"?c.fill(l,a):c.fill(l):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=Wc().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=g,_=4;break;case"utf8":this.fillLast=c,_=4;break;case"base64":this.text=f,this.end=b,_=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 l(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 a(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=a(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=l(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 g(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 b(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):""}}),fs=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{PromisePrototypeThen:r,SymbolAsyncIterator:o,SymbolIterator:n}=je(),{Buffer:i}=($e(),Re(Fe)),{ERR_INVALID_ARG_TYPE:l,ERR_STREAM_NULL_VALUES:a}=Ve().codes;function c(u,h,p){let g;if(typeof h=="string"||h instanceof i)return new u({objectMode:!0,...p,read(){this.push(h),this.push(null)}});let f;if(h&&h[o])f=!0,g=h[o]();else if(h&&h[n])f=!1,g=h[n]();else throw new l("iterable",["Iterable"],h);let b=new u({objectMode:!0,highWaterMark:1,...p}),y=!1;b._read=function(){y||(y=!0,m())},b._destroy=function(_,x){r(w(_),()=>t.nextTick(x,_),v=>t.nextTick(x,v||_))};async function w(_){let x=_!=null,v=typeof g.throw=="function";if(x&&v){let{value:E,done:S}=await g.throw(_);if(await E,S)return}if(typeof g.return=="function"){let{value:E}=await g.return();await E}}async function m(){for(;;){try{let{value:_,done:x}=f?await g.next():g.next();if(x)b.push(null);else{let v=_&&typeof _.then=="function"?await _:_;if(v===null)throw y=!1,new a;if(b.push(v))continue;y=!1}}catch(_){b.destroy(_)}break}}return b}e.exports=c}),br=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{ArrayPrototypeIndexOf:r,NumberIsInteger:o,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:l,ObjectKeys:a,ObjectSetPrototypeOf:c,Promise:u,SafeSet:h,SymbolAsyncDispose:p,SymbolAsyncIterator:g,Symbol:f}=je();e.exports=se,se.ReadableState=ve;var{EventEmitter:b}=(Tt(),Re(wt)),{Stream:y,prependListener:w}=gi(),{Buffer:m}=($e(),Re(Fe)),{addAbortSignal:_}=mr(),x=_t(),v=Ye().debuglog("stream",C=>{v=C}),E=Hc(),S=Ft(),{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}=Ve(),{validateObject:Y}=er(),V=f("kPaused"),{StringDecoder:re}=zc(),F=fs();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,$=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}}}l(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($),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[b.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 Ce(this,C,L,!1)},se.prototype.unshift=function(C,L){return Ce(this,C,L,!0)};function Ce(C,L,_e,xe){v("readableAddChunk",L);let Se=C._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(C,De);else if(L===null)Se.state&=~we,X(C,Se);else if((Se.state&Q)!==0||L&&L.length>0)if(xe)if((Se.state&te)!==0)M(C,new U);else{if(Se.destroyed||Se.errored)return!1;d(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?d(C,Se,L,!1):z(C,Se)):d(C,Se,L,!1)}else xe||(Se.state&=~we,z(C,Se));return!Se.ended&&(Se.length<Se.highWaterMark||Se.length===0)}function d(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?st(this):he(this),null;if(C=B(C,L),C===0&&L.ended)return L.length===0&&st(this),null;let xe=(L.state&ne)!==0;if(v("need readable",xe),(L.length===0||L.length-C<L.highWaterMark)&&(xe=!0,v("length less than watermark",xe)),L.ended||L.reading||L.destroyed||L.errored||!L.constructed)xe=!1,v("reading, ended or constructing",xe);else if(xe){v("do read"),L.state|=we|N,L.length===0&&(L.state|=ne);try{this._read(L.highWaterMark)}catch(De){M(this,De)}L.state&=~N,L.reading||(C=B(_e,L))}let Se;return C>0?Se=Kt(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&&st(this)),Se!==null&&!L.errorEmitted&&!L.closeEmitted&&(L.dataEmitted=!0,this.emit("data",Se)),Se};function X(C,L){if(v("onEofChunk"),!L.ended){if(L.decoder){let _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,it(C)}function z(C,L){!L.readingMore&&L.constructed&&(L.readingMore=!0,t.nextTick(ie,C,L))}function ie(C,L){for(;!L.reading&&!L.ended&&(L.length<L.highWaterMark||L.flowing&&L.length===0);){let _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?Ke:jt;xe.endEmitted?t.nextTick(Se):_e.once("end",Se),C.on("unpipe",De);function De(lt,yt){v("onunpipe"),lt===_e&&yt&&yt.hasUnpiped===!1&&(yt.hasUnpiped=!0,ar())}function Ke(){v("onend"),C.end()}let et,sr=!1;function ar(){v("cleanup"),C.removeListener("close",at),C.removeListener("finish",Et),et&&C.removeListener("drain",et),C.removeListener("error",Nt),C.removeListener("unpipe",De),_e.removeListener("end",Ke),_e.removeListener("end",jt),_e.removeListener("data",en),sr=!0,et&&xe.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&et()}function lr(){sr||(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()),et||(et=Ee(_e,C),C.on("drain",et))}_e.on("data",en);function en(lt){v("ondata");let yt=C.write(lt);v("dest.write",yt),yt===!1&&lr()}function Nt(lt){if(v("onerror",lt),jt(),C.removeListener("error",Nt),C.listenerCount("error")===0){let yt=C._writableState||C._readableState;yt&&!yt.errorEmitted?M(C,lt):C.emit("error",lt)}}w(C,"error",Nt);function at(){C.removeListener("finish",Et),jt()}C.once("close",at);function Et(){v("onfinish"),C.removeListener("close",at),jt()}C.once("finish",Et);function jt(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?lr():xe.flowing||(v("pipe resume"),_e.resume()),C};function Ee(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 De=0;De<Se.length;De++)Se[De].emit("unpipe",this,{hasUnpiped:!1});return this}let xe=r(L.pipes,C);return xe===-1?this:(L.pipes.splice(xe,1),L.pipes.length===0&&this.pause(),C.emit("unpipe",this,_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(Ie,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(Ae,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(Ae,this),L};function Ae(C){let L=C._readableState;L.readableListening=C.listenerCount("readable")>0,L.resumeScheduled&&L[V]===!1?L.flowing=!0:C.listenerCount("data")>0?C.resume():L.readableListening||(L.flowing=null)}function Ie(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(nt,C,L))}function nt(C,L){v("resume",L.reading),L.reading||C.read(0),L.resumeScheduled=!1,C.emit("resume"),it(C),L.flowing&&!L.reading&&C.read(0)}se.prototype.pause=function(){return v("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(v("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[V]=!0,this};function it(C){let L=C._readableState;for(v("flow",L.flowing);L.flowing&&C.read()!==null;);}se.prototype.wrap=function(C){let L=!1;C.on("data",xe=>{!this.push(xe)&&C.pause&&(L=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",xe=>{M(this,xe)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{L&&C.resume&&(L=!1,C.resume())};let _e=a(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[g]=function(){return ze(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),ze(this,C)};function ze(C,L){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let _e=ot(C,L);return _e.stream=C,_e}async function*ot(C,L){let _e=Z;function xe(Ke){this===C?(_e(),_e=Z):_e=Ke}C.on("readable",xe);let Se,De=x(C,{writable:!1},Ke=>{Se=Ke?P(Se,Ke):null,_e(),_e=Z});try{for(;;){let Ke=C.destroyed?null:C.read();if(Ke!==null)yield Ke;else{if(Se)throw Se;if(Se===null)return;await new u(xe)}}}catch(Ke){throw Se=P(Se,Ke),Se}finally{(Se||L?.destroyOnReturn!==!1)&&(Se===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",xe),De())}}l(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}}}),l(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=Kt;function Kt(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 st(C){let L=C._readableState;v("endReadable",L.endEmitted),L.endEmitted||(L.ended=!0,t.nextTick(Xe,L,C))}function Xe(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(Zr,L);else if(C.autoDestroy){let _e=L._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&L.destroy()}}}function Zr(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,L){return F(se,C,L)};var Gt;function or(){return Gt===void 0&&(Gt={}),Gt}se.fromWeb=function(C,L){return or().newStreamReadableFromReadableStream(C,L)},se.toWeb=function(C,L){return or().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,De){S.destroyer(C,Se),De(Se)}}).wrap(C)}}),bi=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{ArrayPrototypeSlice:r,Error:o,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:l,ObjectSetPrototypeOf:a,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:h}=je();e.exports=Y,Y.WritableState=U;var{EventEmitter:p}=(Tt(),Re(wt)),g=gi().Stream,{Buffer:f}=($e(),Re(Fe)),b=Ft(),{addAbortSignal:y}=mr(),{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}=Ve().codes,{errorOrDestroy:T}=b;a(Y.prototype,g.prototype),a(Y,g);function q(){}var D=u("kOnFinished");function U(R,$,ee){typeof ee!="boolean"&&(ee=$ 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,$),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 $=this instanceof ft();if(!$&&!n(Y,this))return new Y(R);this._writableState=new U(R,this,$),R&&(typeof R.write=="function"&&(this._write=R.write),typeof R.writev=="function"&&(this._writev=R.writev),typeof R.destroy=="function"&&(this._destroy=R.destroy),typeof R.final=="function"&&(this._final=R.final),typeof R.construct=="function"&&(this._construct=R.construct),R.signal&&y(R.signal,this)),g.call(this,R),b.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),W(this,ee)})}i(Y,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,$,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"&&!f.isEncoding(ee))throw new j(ee);typeof de!="function"&&(de=q)}if($===null)throw new O;if(!fe.objectMode)if(typeof $=="string")fe.decodeStrings!==!1&&($=f.from($,ee),ee="buffer");else if($ instanceof f)ee="buffer";else if(g._isUint8Array($))$=g._uint8ArrayToBuffer($),ee="buffer";else throw new _("chunk",["string","Buffer","Uint8Array"],$);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,$,ee,de))}Y.prototype.write=function(R,$,ee){return V(this,R,$,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,$,ee,de,fe){let ye=$.objectMode?1:ee.length;$.length+=ye;let H=$.length<$.highWaterMark;return H||($.needDrain=!0),$.writing||$.corked||$.errored||!$.constructed?($.buffered.push({chunk:ee,encoding:de,callback:fe}),$.allBuffers&&de!=="buffer"&&($.allBuffers=!1),$.allNoop&&fe!==q&&($.allNoop=!1)):($.writelen=ye,$.writecb=fe,$.writing=!0,$.sync=!0,R._write(ee,de,$.onwrite),$.sync=!1),H&&!$.errored&&!$.destroyed}function F(R,$,ee,de,fe,ye,H){$.writelen=de,$.writecb=H,$.writing=!0,$.sync=!0,$.destroyed?$.onwrite(new S("write")):ee?R._writev(fe,$.onwrite):R._write(fe,ye,$.onwrite),$.sync=!1}function Z(R,$,ee,de){--$.pendingcb,de(ee),te($),T(R,ee)}function M(R,$){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,$?($.stack,ee.errored||(ee.errored=$),R._readableState&&!R._readableState.errored&&(R._readableState.errored=$),de?t.nextTick(Z,R,ee,$,fe):Z(R,ee,$,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:$,count:ee,cb:de}){return $.afterWriteTickInfo=null,be(R,$,ee,de)}function be(R,$,ee,de){for(!$.ending&&!R.destroyed&&$.length===0&&$.needDrain&&($.needDrain=!1,R.emit("drain"));ee-- >0;)$.pendingcb--,de();$.destroyed&&te($),W(R,$)}function te(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var $;let{chunk:ye,callback:H}=R.buffered[fe],me=R.objectMode?1:ye.length;R.length-=me,H(($=R.errored)!==null&&$!==void 0?$: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,$){if($.corked||$.bufferProcessing||$.destroyed||!$.constructed)return;let{buffered:ee,bufferedIndex:de,objectMode:fe}=$,ye=ee.length-de;if(!ye)return;let H=de;if($.bufferProcessing=!0,ye>1&&R._writev){$.pendingcb-=ye-1;let me=$.allNoop?q:se=>{for(let Ce=H;Ce<ee.length;++Ce)ee[Ce].callback(se)},ve=$.allNoop&&H===0?ee:r(ee,H);ve.allBuffers=$.allBuffers,F(R,$,!0,$.length,ve,"",me),ae($)}else{do{let{chunk:me,encoding:ve,callback:se}=ee[H];ee[H++]=null;let Ce=fe?1:me.length;F(R,$,!1,Ce,me,ve,se)}while(H<ee.length&&!$.writing);H===ee.length?ae($):H>256?(ee.splice(0,H),$.bufferedIndex=0):$.bufferedIndex=H}$.bufferProcessing=!1}Y.prototype._write=function(R,$,ee){if(this._writev)this._writev([{chunk:R,encoding:$}],ee);else throw new x("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,$,ee){let de=this._writableState;typeof R=="function"?(ee=R,R=null,$=null):typeof $=="function"&&(ee=$,$=null);let fe;if(R!=null){let ye=V(this,R,$);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,$){let ee=!1;function de(fe){if(ee){T(R,fe??v());return}if(ee=!0,$.pendingcb--,fe){let ye=$[D].splice(0);for(let H=0;H<ye.length;H++)ye[H](fe);T(R,fe,$.sync)}else K($)&&($.prefinished=!0,R.emit("prefinish"),$.pendingcb++,t.nextTick(G,R,$))}$.sync=!0,$.pendingcb++;try{R._final(de)}catch(fe){de(fe)}$.sync=!1}function ne(R,$){!$.prefinished&&!$.finalCalled&&(typeof R._final=="function"&&!$.destroyed?($.finalCalled=!0,N(R,$)):($.prefinished=!0,R.emit("prefinish")))}function W(R,$,ee){K($)&&(ne(R,$),$.pendingcb===0&&(ee?($.pendingcb++,t.nextTick((de,fe)=>{K(fe)?G(de,fe):fe.pendingcb--},R,$)):K($)&&($.pendingcb++,G(R,$))))}function G(R,$){$.pendingcb--,$.finished=!0;let ee=$[D].splice(0);for(let de=0;de<ee.length;de++)ee[de]();if(R.emit("finish"),$.autoDestroy){let de=R._readableState;(!de||de.autoDestroy&&(de.endEmitted||de.readable===!1))&&R.destroy()}}l(Y.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(R){this._writableState&&(this._writableState.destroyed=R)}},writable:{__proto__:null,get(){let R=this._writableState;return!!R&&R.writable!==!1&&!R.destroyed&&!R.errored&&!R.ending&&!R.ended},set(R){this._writableState&&(this._writableState.writable=!!R)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let R=this._writableState;return R?!R.destroyed&&!R.ending&&R.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var J=b.destroy;Y.prototype.destroy=function(R,$){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[D].length)&&t.nextTick(te,ee),J.call(this,R,$),this},Y.prototype._undestroy=b.undestroy,Y.prototype._destroy=function(R,$){$(R)},Y.prototype[p.captureRejectionSymbol]=function(R){this.destroy(R)};var ge;function oe(){return ge===void 0&&(ge={}),ge}Y.fromWeb=function(R,$){return oe().newStreamWritableFromWritableStream(R,$)},Y.toWeb=function(R){return oe().newWritableStreamFromStreamWritable(R)}}),Vc=pe((s,e)=>{le(),ue(),ce();var t=Ct(),r=($e(),Re(Fe)),{isReadable:o,isWritable:n,isIterable:i,isNodeStream:l,isReadableNodeStream:a,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:h,isWritableStream:p}=dt(),g=_t(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:b,ERR_INVALID_RETURN_VALUE:y}}=Ve(),{destroyer:w}=Ft(),m=ft(),_=br(),x=bi(),{createDeferredPromise:v}=Ye(),E=fs(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},O=globalThis.AbortController||Xt().AbortController,{FunctionPrototypeCall:P}=je(),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(a(U))return q({readable:U});if(c(U))return q({writable:U});if(l(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:F,destroy:Z}=T(U);if(i(V))return E(j,V,{objectMode:!0,write:re,final:F,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){F(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?a(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 b(ae,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(D){let{promise:U,resolve:ae}=v(),Y=new O,V=Y.signal;return{value:D((async function*(){for(;;){let re=U;U=null;let{chunk:F,done:Z,cb:M}=await re;if(t.nextTick(M),Z)return;if(V.aborted)throw new f(void 0,{cause:V.reason});({promise:U,resolve:ae}=v()),yield F}})(),{signal:V}),write(re,F,Z){let M=ae;ae=null,M({chunk:re,done:!1,cb:Z})},final(re){let F=ae;ae=null,F({done:!0,cb:re})},destroy(re,F){Y.abort(),F(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,F,Z,M,Q;function be(te){let we=M;M=null,we?we(te):te&&Q.destroy(te)}return Q=new j({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(ae!=null&&ae.writableObjectMode),readable:Y,writable:V}),V&&(g(ae,te=>{V=!1,te&&w(U,te),be(te)}),Q._write=function(te,we,K){ae.write(te,we)?K():re=K},Q._final=function(te){ae.end(),F=te},ae.on("drain",function(){if(re){let te=re;re=null,te()}}),ae.on("finish",function(){if(F){let te=F;F=null,te()}})),Y&&(g(U,te=>{Y=!1,te&&w(U,te),be(te)}),U.on("readable",function(){if(Z){let te=Z;Z=null,te()}}),U.on("end",function(){Q.push(null)}),Q._read=function(){for(;;){let te=U.read();if(te===null){Z=Q._read;return}if(!Q.push(te))return}}),Q._destroy=function(te,we){!te&&M!==null&&(te=new f),Z=null,re=null,F=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}=je();e.exports=a;var i=br(),l=bi();n(a.prototype,i.prototype),n(a,i);{let p=o(l.prototype);for(let g=0;g<p.length;g++){let f=p[g];a.prototype[f]||(a.prototype[f]=l.prototype[f])}}function a(p){if(!(this instanceof a))return new a(p);i.call(this,p),l.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(a.prototype,{writable:{__proto__:null,...r(l.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(l.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(l.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(l.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(l.prototype,"writableLength")},writableFinished:{__proto__:null,...r(l.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(l.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(l.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(l.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}a.fromWeb=function(p,g){return u().newStreamDuplexFromReadableWritablePair(p,g)},a.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var h;a.from=function(p){return h||(h=Vc()),h(p,"body")}}),ps=pe((s,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=je();e.exports=a;var{ERR_METHOD_NOT_IMPLEMENTED:o}=Ve().codes,n=ft(),{getHighWaterMark:i}=gr();t(a.prototype,n.prototype),t(a,n);var l=r("kCallback");function a(h){if(!(this instanceof a))return new a(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[l]=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,g)=>{if(p){h?h(p):this.destroy(p);return}g!=null&&this.push(g),this.push(null),h&&h()}):(this.push(null),h&&h())}function u(){this._final!==c&&c.call(this)}a.prototype._final=c,a.prototype._transform=function(h,p,g){throw new o("_transform()")},a.prototype._write=function(h,p,g){let f=this._readableState,b=this._writableState,y=f.length;this._transform(h,p,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),b.ended||y===f.length||f.length<f.highWaterMark?g():this[l]=g})},a.prototype._read=function(){if(this[l]){let h=this[l];this[l]=null,h()}}}),ms=pe((s,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=je();e.exports=o;var r=ps();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,l){l(null,n)}}),yi=pe((s,e)=>{le(),ue(),ce();var t=Ct(),{ArrayIsArray:r,Promise:o,SymbolAsyncIterator:n,SymbolDispose:i}=je(),l=_t(),{once:a}=Ye(),c=Ft(),u=ft(),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:b,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ve(),{validateFunction:m,validateAbortSignal:_}=er(),{isIterable:x,isReadable:v,isReadableNodeStream:E,isNodeStream:S,isTransformStream:I,isWebStream:O,isReadableStream:P,isReadableFinished:j}=dt(),T=globalThis.AbortController||Xt().AbortController,q,D,U;function ae(te,we,K){let N=!1;te.on("close",()=>{N=!0});let ne=l(te,{readable:we,writable:K},W=>{N=!W});return{destroy:W=>{N||(N=!0,c.destroyer(te,W||new b("pipe")))},cleanup:ne}}function Y(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function V(te){if(x(te))return te;if(E(te))return re(te);throw new p("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){D||(D=br()),yield*D.prototype[n].call(te)}async function F(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=l(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,a(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,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,$=[],ee=0;function de(ve){fe(ve,--ee===0)}function fe(ve,se){var Ce;if(ve&&(!oe||oe.code==="ERR_STREAM_PREMATURE_CLOSE")&&(oe=ve),!(!oe&&!se)){for(;$.length;)$.shift()(oe);(Ce=ge)===null||Ce===void 0||Ce[i](),N.abort(),se&&(oe||G.forEach(d=>d()),t.nextTick(we,oe,R))}}let ye;for(let ve=0;ve<te.length;ve++){let se=te[ve],Ce=ve<te.length-1,d=ve>0,k=Ce||K?.end!==!1,A=ve===te.length-1;if(S(se)){let B=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&de(X)};if(k){let{destroy:X,cleanup:he}=ae(se,Ce,d);$.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 g("Iterable, AsyncIterable or Stream","source",ye)}else x(se)||E(se)||I(se)?ye=se:ye=u.from(se);else if(typeof se=="function"){if(I(ye)){var H;ye=V((H=ye)===null||H===void 0?void 0:H.readable)}else ye=V(ye);if(ye=se(ye,{signal:ne}),Ce){if(!x(ye,!0))throw new g("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;q||(q=ms());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++,F(ye,B,de,{end:k});else if(P(ye)||I(ye)){let z=ye.readable||ye;ee++,F(z,B,de,{end:k})}else throw new g("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:he,cleanup:ke}=ae(ye,!1,!0);$.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++,F(B,se,de,{end:k})}else if(x(ye))ee++,F(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 l(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)}),l(we,{readable:!1,writable:!0},K)}e.exports={pipelineImpl:Q,pipeline:M}}),gs=pe((s,e)=>{le(),ue(),ce();var{pipeline:t}=yi(),r=ft(),{destroyer:o}=Ft(),{isNodeStream:n,isReadable:i,isWritable:l,isWebStream:a,isTransformStream:c,isWritableStream:u,isReadableStream:h}=dt(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:f}}=Ve(),b=_t();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])&&!a(y[T]))){if(T<y.length-1&&!(i(y[T])||h(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(l(y[T])||u(y[T])||c(y[T])))throw new g(`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=!!(l(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(a(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;b(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(a(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}}),Kc=pe((s,e)=>{le(),ue(),ce();var t=globalThis.AbortController||Xt().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:i},AbortError:l}=Ve(),{validateAbortSignal:a,validateInteger:c,validateObject:u}=er(),h=je().Symbol("kWeak"),p=je().Symbol("kResistStopPropagation"),{finished:g}=_t(),f=gs(),{addAbortSignalNoValidate:b}=mr(),{isWritable:y,isNodeStream:w}=dt(),{deprecate:m}=Ye(),{ArrayPrototypePush:_,Boolean:x,MathFloor:v,Number:E,NumberIsNaN:S,Promise:I,PromiseReject:O,PromiseResolve:P,PromisePrototypeThen:j,Symbol:T}=je(),q=T("kEmpty"),D=T("kEof");function U(W,G){if(G!=null&&u(G,"options"),G?.signal!=null&&a(G.signal,"options.signal"),w(W)&&!y(W))throw new r("stream",W,"must be writable");let J=f(this,W);return G!=null&&G.signal&&b(G.signal,J),J}function ae(W,G){if(typeof W!="function")throw new o("fn",["Function","AsyncFunction"],W);G!=null&&u(G,"options"),G?.signal!=null&&a(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,$=[],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&&$.length<ge&&(fe(),fe=null)}async function Ce(){try{for await(let d of R){if(ye)return;if(oe.aborted)throw new l;try{if(d=W(d,ee),d===q)continue;d=P(d)}catch(k){d=O(k)}H+=1,j(d,ve,me),$.push(d),de&&(de(),de=null),!ye&&($.length>=ge||H>=J)&&await new I(k=>{fe=k})}$.push(D)}catch(d){let k=O(d);j(k,ve,me),$.push(k)}finally{ye=!0,de&&(de(),de=null)}}Ce();try{for(;;){for(;$.length>0;){let d=await $[0];if(d===D)return;if(oe.aborted)throw new l;d!==q&&(yield d),$.shift(),se()}await new I(d=>{de=d})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function Y(W=void 0){return W!=null&&u(W,"options"),W?.signal!=null&&a(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 l({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 F(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&&a(J.signal,"options.signal");let oe=arguments.length>1;if(J!=null&&(ge=J.signal)!==null&&ge!==void 0&&ge.aborted){let fe=new l(void 0,{cause:J.signal.reason});throw this.once("error",()=>{}),await g(this.destroy(fe)),fe}let R=new t,$=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 l;oe?G=await W(G,fe,{signal:$}):(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&&a(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 l(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&&a(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 l;for await(let oe of this){var ge;if(G!=null&&(ge=G.signal)!==null&&ge!==void 0&&ge.aborted)throw new l;W--<=0&&(yield oe)}}).call(this)}function ne(W,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&a(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 l;for await(let oe of this){var ge;if(G!=null&&(ge=G.signal)!==null&&ge!==void 0&&ge.aborted)throw new l;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:F}}),bs=pe((s,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=je(),{isIterable:o,isNodeStream:n,isWebStream:i}=dt(),{pipelineImpl:l}=yi(),{finished:a}=_t();ys();function c(...u){return new r((h,p)=>{let g,f,b=u[u.length-1];if(b&&typeof b=="object"&&!n(b)&&!o(b)&&!i(b)){let y=t(u);g=y.signal,f=y.end}l(u,(y,w)=>{y?p(y):h(w)},{signal:g,end:f})})}e.exports={finished:a,pipeline:c}}),ys=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Re(Fe)),{ObjectDefineProperty:r,ObjectKeys:o,ReflectApply:n}=je(),{promisify:{custom:i}}=Ye(),{streamReturningOperators:l,promiseReturningOperators:a}=Kc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ve(),u=gs(),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:p}=gr(),{pipeline:g}=yi(),{destroyer:f}=Ft(),b=_t(),y=bs(),w=dt(),m=e.exports=gi().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=br();for(let x of o(l)){let v=function(...S){if(new.target)throw c();return m.Readable.from(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})}for(let x of o(a)){let v=function(...S){if(new.target)throw c();return 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})}m.Writable=bi(),m.Duplex=ft(),m.Transform=ps(),m.PassThrough=ms(),m.pipeline=g;var{addAbortSignal:_}=mr();m.addAbortSignal=_,m.finished=b,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=h,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(g,i,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(b,i,{__proto__:null,enumerable:!0,get(){return y.finished}}),m.Stream=m,m._isUint8Array=function(x){return x instanceof Uint8Array},m._uint8ArrayToBuffer=function(x){return t.from(x.buffer,x.byteOffset,x.byteLength)}}),Ot=pe((s,e)=>{le(),ue(),ce();var t=ys(),r=bs(),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}),Gc=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}}}),Yc=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Re(Fe)),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 l=0;l<this._bufs.length;l++){let a=i+this._bufs[l].length;if(n<a||l===this._bufs.length-1)return[l,n-i];i=a}},o.prototype._reverseOffset=function(n){let i=n[0],l=n[1];for(let a=0;a<i;a++)l+=this._bufs[a].length;return l},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,l,a){if((typeof l!="number"||l<0)&&(l=0),(typeof a!="number"||a>this.length)&&(a=this.length),l>=this.length||a<=0)return n||t.alloc(0);let c=!!n,u=this._offset(l),h=a-l,p=h,g=c&&i||0,f=u[1];if(l===0&&a===this.length){if(!c)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let b=0;b<this._bufs.length;b++)this._bufs[b].copy(n,g),g+=this._bufs[b].length;return n}if(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(h));for(let b=u[0];b<this._bufs.length;b++){let y=this._bufs[b].length-f;if(p>y)this._bufs[b].copy(n,g,f),g+=y;else{this._bufs[b].copy(n,g,f,f+p),g+=y;break}p-=y,f&&(f=0)}return n.length>g?n.slice(0,g):n},o.prototype.shallowSlice=function(n,i){if(n=n||0,i=typeof i!="number"?this.length:i,n<0&&(n+=this.length),i<0&&(i+=this.length),n===i)return this._new();let l=this._offset(n),a=this._offset(i),c=this._bufs.slice(l[0],a[0]+1);return a[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,a[1]),l[1]!==0&&(c[0]=c[0].slice(l[1])),this._new(c)},o.prototype.toString=function(n,i,l){return this.slice(i,l).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,l){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[a,c]=l?[n.length-1,-1]:[0,1];for(let u=a;u>=0&&u<n.length;u+=c)this._attach(n[u],i,l)}else if(this._isBufferList(n)){let[a,c]=l?[n._bufs.length-1,-1]:[0,1];for(let u=a;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],i,l)}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,l){if(l===void 0&&typeof i=="string"&&(l=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,l):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 a=this._offset(i),c=a[0],u=a[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 l=0;l<i.length;l++)if(this.get(n+l)!==i[l])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(l){n[l]===null?o.prototype[l]=function(a,c){return this.slice(a,a+c)[l](0,c)}:o.prototype[l]=function(a=0){return this.slice(a,a+n[l])[l](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}),Jc=pe((s,e)=>{le(),ue(),ce();var t=Ot().Duplex,r=Gc(),o=Yc();function n(i){if(!(this instanceof n))return new n(i);if(typeof i=="function"){this._callback=i;let l=(function(a){this._callback&&(this._callback(a),this._callback=null)}).bind(this);this.on("pipe",function(a){a.on("error",l)}),this.on("unpipe",function(a){a.removeListener("error",l)}),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,l,a){this._appendBuffer(i),typeof a=="function"&&a()},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,l){this._bufs.length=0,this.length=0,l(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}),Qc=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}),vs=pe((s,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=($e(),Re(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 o(n){return[0,1,2].map(i=>[0,1].map(l=>[0,1].map(a=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(l?t.DUP_MASK:0)|i<<t.QOS_SHIFT|a,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"}}),Xc=pe((s,e)=>{le(),ue(),ce();var t=1e3,r=t*60,o=r*60,n=o*24,i=n*7,l=n*365.25;e.exports=function(p,g){g=g||{};var f=typeof p;if(f==="string"&&p.length>0)return a(p);if(f==="number"&&isFinite(p))return g.long?u(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function a(p){if(p=String(p),!(p.length>100)){var g=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(g){var f=parseFloat(g[1]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return f*l;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*o;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 g=Math.abs(p);return g>=n?Math.round(p/n)+"d":g>=o?Math.round(p/o)+"h":g>=r?Math.round(p/r)+"m":g>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var g=Math.abs(p);return g>=n?h(p,g,n,"day"):g>=o?h(p,g,o,"hour"):g>=r?h(p,g,r,"minute"):g>=t?h(p,g,t,"second"):p+" ms"}function h(p,g,f,b){var y=g>=f*1.5;return Math.round(p/f)+" "+b+(y?"s":"")}}),Zc=pe((s,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=h,n.disable=c,n.enable=l,n.enabled=u,n.humanize=Xc(),n.destroy=p,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function o(g){let f=0;for(let b=0;b<g.length;b++)f=(f<<5)-f+g.charCodeAt(b),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=o;function n(g){let f,b=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,(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=g,m.useColors=n.useColors(),m.color=n.selectColor(g),m.extend=i,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(y!==n.namespaces&&(y=n.namespaces,w=n.enabled(g)),w),set:_=>{b=_}}),typeof n.init=="function"&&n.init(m),m}function i(g,f){let b=n(this.namespace+(typeof f>"u"?":":f)+g);return b.log=this.log,b}function l(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let f=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let b of f)b[0]==="-"?n.skips.push(b.slice(1)):n.names.push(b)}function a(g,f){let b=0,y=0,w=-1,m=0;for(;b<g.length;)if(y<f.length&&(f[y]===g[b]||f[y]==="*"))f[y]==="*"?(w=y,m=b,y++):(b++,y++);else if(w!==-1)y=w+1,m++,b=m;else return!1;for(;y<f.length&&f[y]==="*";)y++;return y===f.length}function c(){let g=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),g}function u(g){for(let f of n.skips)if(a(g,f))return!1;for(let f of n.names)if(a(g,f))return!0;return!1}function h(g){return g instanceof Error?g.stack||g.message:g}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 a=!1;return()=>{a||(a=!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 a;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&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;a.splice(1,0,c,"color: inherit");let u=0,h=0;a[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(h=u))}),a.splice(h,0,c)}s.log=console.debug||console.log||(()=>{});function o(a){try{a?s.storage.setItem("debug",a):s.storage.removeItem("debug")}catch{}}function n(){let a;try{a=s.storage.getItem("debug")||s.storage.getItem("DEBUG")}catch{}return!a&&typeof Le<"u"&&"env"in Le&&(a=Le.env.DEBUG),a}function i(){try{return localStorage}catch{}}e.exports=Zc()(s);var{formatters:l}=e.exports;l.j=function(a){try{return JSON.stringify(a)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),eu=pe((s,e)=>{le(),ue(),ce();var t=Jc(),{EventEmitter:r}=(Tt(),Re(wt)),o=Qc(),n=vs(),i=pt()("mqtt-packet:parser"),l=class Lo extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof Lo?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new Lo().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,g={},f=this.packet,b=this._parseString();if(b===null)return this._emitError(new Error("Cannot parse protocolId"));if(b!=="MQTT"&&b!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=b,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"));g.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,g.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,g.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let y=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),w=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(g.will)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),g.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(g.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(g.password){if(h=this._parseBuffer(),h===null)return this._emitError(new Error("Cannot parse password"));f.password=h}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 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,g,f,b,y;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(c.properties=w)}if(c.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<c.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=c.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(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(b=(h>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(h>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,g=h>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,g>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));y={topic:u,qos:p},this.settings.protocolVersion===5?(y.nl=b,y.rap=f,y.rh=g):this.settings.bridgeMode&&(y.rh=0,y.rap=!0,y.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",y),c.subscriptions.push(y)}}}_parseSuback(){i("_parseSuback");let c=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos<this.packet.length;){let u=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!n.MQTT5_SUBACK_CODES[u])return this._emitError(new Error("Invalid suback code"))}else if(u>2&&u!==128)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(u)}}}_parseUnsubscribe(){i("_parseUnsubscribe");let c=this.packet;if(c.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<c.length;){let u=this._parseString();if(u===null)return this._emitError(new Error("Cannot parse topic"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){i("_parseUnsuback");let c=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&c.length!==2)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(c.length<=0)return this._emitError(new Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let u=this._parseProperties();for(Object.getOwnPropertyNames(u).length&&(c.properties=u),c.granted=[];this._pos<this.packet.length;){let 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,g=0,f=!1,b,y=this._pos?this._pos:0;for(;h<u&&y+h<this._list.length;){if(b=this._list.readUInt8(y+h++),g+=p*(b&n.VARBYTEINT_MASK),p*=128,(b&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=h)break}return!f&&h===u&&this._list.length>=h&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=h),f?c?f={bytes:h,value:g}:f=g: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,h={};for(;this._pos<u;){let p=this._parseByte();if(!p)return this._emitError(new Error("Cannot parse property code type")),!1;let g=n.propertiesCodes[p];if(!g)return this._emitError(new Error("Unknown property")),!1;if(g==="userProperties"){h[g]||(h[g]=Object.create(null));let f=this._parseByType(n.propertiesTypes[g]);if(h[g][f.name])if(Array.isArray(h[g][f.name]))h[g][f.name].push(f.value);else{let b=h[g][f.name];h[g][f.name]=[b],h[g][f.name].push(f.value)}else h[g][f.name]=f.value;continue}h[g]?Array.isArray(h[g])?h[g].push(this._parseByType(n.propertiesTypes[g])):(h[g]=[h[g]],h[g].push(this._parseByType(n.propertiesTypes[g]))):h[g]=this._parseByType(n.propertiesTypes[g])}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=l}),tu=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Re(Fe)),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 l(){for(let u=0;u<r;u++)o[u]=i(u)}function a(u){let h=0,p=0,g=t.allocUnsafe(4);do h=u%128|0,u=u/128|0,u>0&&(h=h|128),g.writeUInt8(h,p++);while(u>0&&p<4);return u>0&&(p=0),n?g.subarray(0,p):g.slice(0,p)}function c(u){let h=t.allocUnsafe(4);return h.writeUInt32BE(u,0),h}e.exports={cache:o,generateCache:l,generateNumber:i,genBufVariableByteInt:a,generate4ByteBuffer:c}}),ru=pe((s,e)=>{le(),ue(),ce(),typeof Le>"u"||!Le.version||Le.version.indexOf("v0.")===0||Le.version.indexOf("v1.")===0&&Le.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Le;function t(r,o,n,i){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var l=arguments.length,a,c;switch(l){case 0:case 1:return Le.nextTick(r);case 2:return Le.nextTick(function(){r.call(null,o)});case 3:return Le.nextTick(function(){r.call(null,o,n)});case 4:return Le.nextTick(function(){r.call(null,o,n,i)});default:for(a=new Array(l-1),c=0;c<a.length;)a[c++]=arguments[c];return Le.nextTick(function(){r.apply(null,a)})}}}),ws=pe((s,e)=>{le(),ue(),ce();var t=vs(),{Buffer:r}=($e(),Re(Fe)),o=r.allocUnsafe(0),n=r.from([0]),i=tu(),l=ru().nextTick,a=pt()("mqtt-packet:writeToStream"),c=i.cache,u=i.generateNumber,h=i.generateCache,p=i.genBufVariableByteInt,g=i.generate4ByteBuffer,f=Y,b=!0;function y(K,N,ne){switch(a("generate called"),N.cork&&(N.cork(),l(w,N)),b&&(b=!1,h()),a("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 f===Y},set(K){K?((!c||Object.keys(c).length===0)&&(b=!0),f=Y):(b=!1,f=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,$=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 $=="string"||r.isBuffer($))&&($||J>=4)&&($||oe))ye+=r.byteLength($)+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),F(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])),f(N,R),J===5&&H.write(),F(N,$),ge&&(J===5&&me.write(),U(N,ge.topic),F(N,ge.payload)),ee!=null&&F(N,ee),de!=null&&F(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){a("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,$=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 $!="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),f(N,te(oe)),N.write(oe),J>0&&f(N,$),fe?.write(),a("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,$=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+=$!==0?1:-1),D(N,de),f(N,ge),W===5&&de!==2&&N.write(r.from([$])),fe!==null?fe.write():de===4&&N.write(r.from([0])),!0}function E(K,N,ne){a("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,$=0;if(typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;$+=2;let ee=null;if(W===5){if(ee=Z(N,R),!ee)return!1;$+=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}$+=r.byteLength(ye)+2+1}else return N.destroy(new Error("Invalid subscriptions")),!1;a("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),N.write(t.SUBSCRIBE_HEADER[1][J?1:0][0]),D(N,$),f(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,Ce;U(N,ye),Ce=t.SUBSCRIBE_OPTIONS_QOS[H],W===5&&(Ce|=me?t.SUBSCRIBE_OPTIONS_NL:0,Ce|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Ce|=se?t.SUBSCRIBE_OPTIONS_RH[se]:0),de=N.write(r.from([Ce]))}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 $=null;if(W===5){if($=M(N,oe,ne,R),!$)return!1;R+=$.length}return N.write(t.SUBACK_HEADER),D(N,R),f(N,J),$!==null&&$.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,$=0;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if($+=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;$+=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;$+=ee.length}N.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),D(N,$),f(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,$=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[$][ee][ge][0]),D(N,de),f(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)),a("writeVarByteInt: writing to stream: %o",ne),K.write(ne)}function U(K,N){let ne=r.byteLength(N);return f(K,ne),a("writeString: %s",N),K.write(N,"utf8")}function ae(K,N,ne){U(K,N),U(K,ne)}function Y(K,N){return a("writeNumberCached: number: %d",N),a("writeNumberCached: %o",c[N]),K.write(c[N])}function V(K,N){let ne=u(N);return a("writeNumberGenerated: %o",ne),K.write(ne)}function re(K,N){let ne=g(N);return a("write4ByteNumber: %o",ne),K.write(ne)}function F(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 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,$)=>{let ee=J[$];return Array.isArray(ee)?R+=ee.reduce((de,fe)=>(de+=3+r.byteLength($.toString())+2+r.byteLength(fe.toString()),de),0):R+=3+r.byteLength($.toString())+2+r.byteLength(J[$].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]])),F(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(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}),nu=pe((s,e)=>{le(),ue(),ce();var t=ws(),{EventEmitter:r}=(Tt(),Re(wt)),{Buffer:o}=($e(),Re(Fe));function n(l,a){let c=new i;return t(l,c,a),c.concat()}var i=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(l){return this._array[this._i++]=l,!0}concat(){let l=0,a=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"?a[h]=c[h].length:a[h]=o.byteLength(c[h]),l+=a[h];let p=o.allocUnsafe(l);for(h=0;h<c.length&&c[h]!==void 0;h++)typeof c[h]!="string"?(c[h].copy(p,u),u+=a[h]):(p.write(c[h],u),u+=a[h]);return p}destroy(l){l&&this.emit("error",l)}};e.exports=n}),iu=pe(s=>{le(),ue(),ce(),s.parser=eu().parser,s.generate=nu(),s.writeToStream=ws()}),ou=pe((s,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof pr?pr.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(a(Array.from(h),p))),i.set(Set,(h,p)=>new Set(a(Array.from(h),p))),n.constructorHandlers)for(let h of n.constructorHandlers)i.set(h[0],h[1]);let l=null;return n.proto?u:c;function a(h,p){let g=Object.keys(h),f=new Array(g.length);for(let b=0;b<g.length;b++){let y=g[b],w=h[y];typeof w!="object"||w===null?f[y]=w:w.constructor!==Object&&(l=i.get(w.constructor))?f[y]=l(w,p):ArrayBuffer.isView(w)?f[y]=t(w):f[y]=p(w)}return f}function c(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return a(h,c);if(h.constructor!==Object&&(l=i.get(h.constructor)))return l(h,c);let p={};for(let g in h){if(Object.hasOwnProperty.call(h,g)===!1)continue;let f=h[g];typeof f!="object"||f===null?p[g]=f:f.constructor!==Object&&(l=i.get(f.constructor))?p[g]=l(f,c):ArrayBuffer.isView(f)?p[g]=t(f):p[g]=c(f)}return p}function u(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return a(h,u);if(h.constructor!==Object&&(l=i.get(h.constructor)))return l(h,u);let p={};for(let g in h){let f=h[g];typeof f!="object"||f===null?p[g]=f:f.constructor!==Object&&(l=i.get(f.constructor))?p[g]=l(f,u):ArrayBuffer.isView(f)?p[g]=t(f):p[g]=u(f)}return p}}function o(n){let i=[],l=[],a=new Map;if(a.set(Date,g=>new Date(g)),a.set(Map,(g,f)=>new Map(u(Array.from(g),f))),a.set(Set,(g,f)=>new Set(u(Array.from(g),f))),n.constructorHandlers)for(let g of n.constructorHandlers)a.set(g[0],g[1]);let c=null;return n.proto?p:h;function u(g,f){let b=Object.keys(g),y=new Array(b.length);for(let w=0;w<b.length;w++){let m=b[w],_=g[m];if(typeof _!="object"||_===null)y[m]=_;else if(_.constructor!==Object&&(c=a.get(_.constructor)))y[m]=c(_,f);else if(ArrayBuffer.isView(_))y[m]=t(_);else{let x=i.indexOf(_);x!==-1?y[m]=l[x]:y[m]=f(_)}}return y}function h(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,h);if(g.constructor!==Object&&(c=a.get(g.constructor)))return c(g,h);let f={};i.push(g),l.push(f);for(let b in g){if(Object.hasOwnProperty.call(g,b)===!1)continue;let y=g[b];if(typeof y!="object"||y===null)f[b]=y;else if(y.constructor!==Object&&(c=a.get(y.constructor)))f[b]=c(y,h);else if(ArrayBuffer.isView(y))f[b]=t(y);else{let w=i.indexOf(y);w!==-1?f[b]=l[w]:f[b]=h(y)}}return i.pop(),l.pop(),f}function p(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,p);if(g.constructor!==Object&&(c=a.get(g.constructor)))return c(g,p);let f={};i.push(g),l.push(f);for(let b in g){let y=g[b];if(typeof y!="object"||y===null)f[b]=y;else if(y.constructor!==Object&&(c=a.get(y.constructor)))f[b]=c(y,p);else if(ArrayBuffer.isView(y))f[b]=t(y);else{let w=i.indexOf(y);w!==-1?f[b]=l[w]:f[b]=p(y)}}return i.pop(),l.pop(),f}}}),su=pe((s,e)=>{le(),ue(),ce(),e.exports=ou()()}),_s=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.validateTopic=e,s.validateTopics=t;function e(r){let o=r.split("/");for(let n=0;n<o.length;n++)if(o[n]!=="+"){if(o[n]==="#")return n===o.length-1;if(o[n].indexOf("+")!==-1||o[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let o=0;o<r.length;o++)if(!e(r[o]))return r[o];return null}}),ks=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Ot(),t={objectMode:!0},r={clean:!0},o=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,i){return this._inflights.set(n.messageId,n),i&&i(),this}createStream(){let n=new e.Readable(t),i=[],l=!1,a=0;return this._inflights.forEach((c,u)=>{i.push(c)}),n._read=()=>{!l&&a<i.length?n.push(i[a++]):n.push(null)},n.destroy=c=>{if(!l)return l=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,i){let l=this._inflights.get(n.messageId);return l?(this._inflights.delete(n.messageId),i(null,l)):i&&i(new Error("missing packet")),this}get(n,i){let l=this._inflights.get(n.messageId);return l?i(null,l):i&&i(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};s.default=o}),au=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(),l=o.payload,{qos:a}=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",a),a){case 2:{u.customHandleAcks(i,l,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,l,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,l,o),r.handleMessage(o,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",i,l,o),r.handleMessage(o,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};s.default=t}),lu=pe((s,e)=>{e.exports={version:"5.15.0"}}),$t=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 fc extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,fc.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};s.ErrorWithReasonCode=e;var t=class pc extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,pc.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};s.ErrorWithSubackPacket=t;function r(o,n,i=!1){let l=[n];for(;;){let a=l[0],c=Object.getPrototypeOf(a);if(c?.prototype)l.unshift(c);else break}for(let a of l)for(let c of Object.getOwnPropertyNames(a.prototype))(i||c!=="constructor")&&Object.defineProperty(o.prototype,c,Object.getOwnPropertyDescriptor(a.prototype,c)??Object.create(null))}s.nextTick=typeof Le?.nextTick=="function"?Le.nextTick:o=>{setTimeout(o,0)},s.MQTTJS_VERSION=lu().version}),yr=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=void 0;var e=$t();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,l=null,a=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!a){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,()=>{a(c,o)})):r._removeOutgoingAndStoreMessage(n,a);break}case"pubrec":{l={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,()=>{a(c,o)})):r._sendPacket(l);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 g=r.messageIdToTopic[n];g&&g.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),a(c,o);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),a(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}),cu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=$t(),t=yr(),r=(o,n)=>{let{options:i}=o,l=i.protocolVersion,a=l===5?n.reasonCode:n.returnCode;if(l!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${l}`,a);o.emit("error",c);return}o.handleAuth(n,(c,u)=>{if(c){o.emit("error",c);return}if(a===24)o.reconnecting=!1,o._sendPacket(u);else{let h=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[a]}`,a);o.emit("error",h)}})};s.default=r}),uu=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 Le=="object"&&Le?Le:{},o=(g,f,b,y)=>{typeof r.emitWarning=="function"?r.emitWarning(g,f,b,y):console.error(`[${b}] ${f}: ${g}`)},n=globalThis.AbortController,i=globalThis.AbortSignal;if(typeof n>"u"){i=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(b,y){this._onabort.push(y)}},n=class{constructor(){f()}signal=new i;abort(b){if(!this.signal.aborted){this.signal.reason=b,this.signal.aborted=!0;for(let y of this.signal._onabort)y(b);this.signal.onabort?.(b)}}};let g=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{g&&(g=!1,o("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",f))}}var l=g=>!t.has(g),a=g=>g&&g===Math.floor(g)&&g>0&&isFinite(g),c=g=>a(g)?g<=Math.pow(2,8)?Uint8Array:g<=Math.pow(2,16)?Uint16Array:g<=Math.pow(2,32)?Uint32Array:g<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(g){super(g),this.fill(0)}},h=class cr{heap;length;static#l=!1;static create(f){let b=c(f);if(!b)return[];cr.#l=!0;let y=new cr(f,b);return cr.#l=!1,y}constructor(f,b){if(!cr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new b(f),this.length=0}push(f){this.heap[this.length++]=f}pop(){return this.heap[--this.length]}},p=class mc{#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(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.#d,get head(){return f.#a},get tail(){return f.#o},free:f.#y,isBackgroundFetch:b=>f.#t(b),backgroundFetch:(b,y,w,m)=>f.#L(b,y,w,m),moveToTail:b=>f.#C(b),indexes:b=>f.#k(b),rindexes:b=>f.#x(b),isStale:b=>f.#p(b)}}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(f){let{max:b=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}=f;if(b!==0&&!a(b))throw new TypeError("max option must be a nonnegative integer");let F=b?c(b):Array;if(!F)throw new Error("invalid max value: "+b);if(this.#l=b,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(b).fill(void 0),this.#e=new Array(b).fill(void 0),this.#c=new F(b),this.#d=new F(b),this.#a=0,this.#o=0,this.#y=h.create(b),this.#i=0,this.#b=0,typeof E=="function"&&(this.#m=E),typeof S=="function"?(this.#g=S,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#_=!!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&&!a(this.#h))throw new TypeError("maxSize must be a positive integer if specified");if(!a(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!ae,this.updateAgeOnGet=!!_,this.updateAgeOnHas=!!x,this.ttlResolution=a(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=y||0,this.ttl){if(!a(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";l(Z)&&(t.add(Z),o("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,mc))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#N(){let f=new u(this.#l),b=new u(this.#l);this.#f=f,this.#w=b,this.#j=(m,_,x=e.now())=>{if(b[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=>{b[m]=f[m]!==0?e.now():0},this.#E=(m,_)=>{if(f[_]){let x=f[_],v=b[_];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=b[_];if(!x||!v)return 1/0;let E=(y||w())-v;return x-E},this.#p=m=>{let _=b[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=b=>{this.#b-=f[b],f[b]=0},this.#U=(b,y,w,m)=>{if(this.#t(y))return 0;if(!a(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(y,b),!a(w))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return w},this.#M=(b,y,w)=>{if(f[b]=y,this.#h){let m=this.#h-f[b];for(;this.#b>m;)this.#R(!0)}this.#b+=f[b],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=f=>{};#M=(f,b,y)=>{};#U=(f,b,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 b=this.#o;!(!this.#B(b)||((f||!this.#p(b))&&(yield b),b===this.#a));)b=this.#d[b]}*#x({allowStale:f=this.allowStale}={}){if(this.#i)for(let b=this.#a;!(!this.#B(b)||((f||!this.#p(b))&&(yield b),b===this.#o));)b=this.#c[b]}#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 b=this.#r[f];b!==void 0&&!this.#t(this.#e[f])&&(yield b)}}*rkeys(){for(let f of this.#x()){let b=this.#r[f];b!==void 0&&!this.#t(this.#e[f])&&(yield b)}}*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,b={}){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],b)}}forEach(f,b=this){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(b,m,this.#r[y],this)}}rforEach(f,b=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(b,m,this.#r[y],this)}}purgeStale(){let f=!1;for(let b of this.#x({allowStale:!0}))this.#p(b)&&(this.#S(this.#r[b],"expire"),f=!0);return f}info(f){let b=this.#n.get(f);if(b===void 0)return;let y=this.#e[b],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let _=this.#f[b],x=this.#w[b];if(_&&x){let v=_-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[b]),m}dump(){let f=[];for(let b of this.#k({allowStale:!0})){let y=this.#r[b],w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||y===void 0)continue;let _={value:m};if(this.#f&&this.#w){_.ttl=this.#f[b];let x=e.now()-this.#w[b];_.start=Math.floor(Date.now()-x)}this.#v&&(_.size=this.#v[b]),f.unshift([y,_])}return f}load(f){this.clear();for(let[b,y]of f){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(b,y.value,y)}}set(f,b,y={}){if(b===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,b,y.size||0,x);if(this.maxEntrySize&&S>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(f,"set"),this;let I=this.#i===0?void 0:this.#n.get(f);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]=f,this.#e[I]=b,this.#n.set(f,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(b!==O){if(this.#A&&this.#t(O)){O.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:P}=O;P!==void 0&&!_&&(this.#_&&this.#m?.(P,f,"set"),this.#u&&this.#s?.push([P,f,"set"]))}else _||(this.#_&&this.#m?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]));if(this.#T(I),this.#M(I,S,v),this.#e[I]=b,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 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,b;for(;b=f?.shift();)this.#g?.(...b)}}}#R(f){let b=this.#a,y=this.#r[b],w=this.#e[b];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(b),f&&(this.#r[b]=void 0,this.#e[b]=void 0,this.#y.push(b)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[b],this.#n.delete(y),this.#i--,b}has(f,b={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=b,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,b={}){let{allowStale:y=this.allowStale}=b,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,b,y,w){let m=b===void 0?void 0:this.#e[b];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[b]===P&&(T===void 0?ae.__staleWhileFetching?this.#e[b]=ae.__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),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[b]===P&&(!ae||Y.__staleWhileFetching===void 0?this.#S(f,"fetch"):D||(this.#e[b]=Y.__staleWhileFetching)),U)return y.status&&Y.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},O=(T,q)=>{let D=this.#O?.(f,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 b===void 0?(this.set(f,j,{...v.options,status:void 0}),b=this.#n.get(f)):this.#e[b]=j,j}#t(f){if(!this.#A)return!1;let b=f;return!!b&&b instanceof Promise&&b.hasOwnProperty("__staleWhileFetching")&&b.__abortController instanceof n}async fetch(f,b={}){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}=b;if(!this.#A)return D&&(D.fetch="get"),this.get(f,{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(f);if(Y===void 0){D&&(D.fetch="miss");let V=this.#L(f,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 F=this.#L(f,Y,ae,T),Z=F.__staleWhileFetching!==void 0&&y;return D&&(D.fetch=re?"stale":"refresh",Z&&re&&(D.returnedStale=!0)),Z?F.__staleWhileFetching:F.__returned=F}}async forceFetch(f,b={}){let y=await this.fetch(f,b);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(f,b={}){let y=this.#P;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,..._}=b,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,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:_}=b,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,b){this.#d[b]=f,this.#c[f]=b}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#D(this.#d[f],this.#c[f]),this.#D(this.#o,f),this.#o=f)}delete(f){return this.#S(f,"delete")}#S(f,b){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(b);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,b),this.#u&&this.#s?.push([m,f,b])),this.#n.delete(f),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.#F("delete")}#F(f){for(let b of this.#x({allowStale:!0})){let y=this.#e[b];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let w=this.#r[b];this.#_&&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 b=this.#s,y;for(;y=b?.shift();)this.#g?.(...y)}}};s.LRUCache=p}),mt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.ContainerIterator=s.Container=s.Base=void 0;var e=class{constructor(o=0){this.iteratorType=o}equals(o){return this.o===o.o}};s.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};s.Base=t;var r=class extends t{};s.Container=r}),hu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(o=[]){super(),this.S=[];let n=this;o.forEach(function(i){n.push(i)})}clear(){this.i=0,this.S=[]}push(o){return this.S.push(o),this.i+=1,this.i}pop(){if(this.i!==0)return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}},r=t;s.default=r}),du=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(o=[]){super(),this.j=0,this.q=[];let n=this;o.forEach(function(i){n.push(i)})}clear(){this.q=[],this.i=this.j=0}push(o){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let i=this.i;for(let l=0;l<i;++l)this.q[l]=this.q[this.j+l];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}),fu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(o=[],n=function(l,a){return l>a?-1:l<a?1:0},i=!0){if(super(),this.v=n,Array.isArray(o))this.C=i?[...o]:o;else{this.C=[];let a=this;o.forEach(function(c){a.C.push(c)})}this.i=this.C.length;let l=this.i>>1;for(let a=this.i-1>>1;a>=0;--a)this.k(a,l)}m(o){let n=this.C[o];for(;o>0;){let i=o-1>>1,l=this.C[i];if(this.v(l,n)<=0)break;this.C[o]=l,o=i}this.C[o]=n}k(o,n){let i=this.C[o];for(;o<n;){let l=o<<1|1,a=l+1,c=this.C[l];if(a<this.i&&this.v(c,this.C[a])>0&&(l=a,c=this.C[a]),this.v(c,i)>=0)break;this.C[o]=c,o=l}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}),vi=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Container{},r=t;s.default=r}),gt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),xs=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.RandomIterator=void 0;var e=mt(),t=gt(),r=class extends e.ContainerIterator{constructor(o,n){super(n),this.o=o,this.iteratorType===0?(this.pre=function(){return this.o===0&&(0,t.throwIteratorAccessError)(),this.o-=1,this},this.next=function(){return this.o===this.container.size()&&(0,t.throwIteratorAccessError)(),this.o+=1,this}):(this.pre=function(){return this.o===this.container.size()-1&&(0,t.throwIteratorAccessError)(),this.o+=1,this},this.next=function(){return this.o===-1&&(0,t.throwIteratorAccessError)(),this.o-=1,this})}get pointer(){return this.container.getElementByPos(this.o)}set pointer(o){this.container.setElementByPos(this.o,o)}};s.RandomIterator=r}),pu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=r(vi()),t=xs();function r(l){return l&&l.t?l:{default:l}}var o=class gc extends t.RandomIterator{constructor(a,c,u){super(a,u),this.container=c}copy(){return new gc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(l=[],a=!0){if(super(),Array.isArray(l))this.J=a?[...l]:l,this.i=l.length;else{this.J=[];let c=this;l.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(l){if(l<0||l>this.i-1)throw new RangeError;return this.J[l]}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;return this.J.splice(l,1),this.i-=1,this.i}eraseElementByValue(l){let a=0;for(let c=0;c<this.i;++c)this.J[c]!==l&&(this.J[a++]=this.J[c]);return this.i=this.J.length=a,this.i}eraseElementByIterator(l){let a=l.o;return l=l.next(),this.eraseElementByPos(a),l}pushBack(l){return this.J.push(l),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(l,a){if(l<0||l>this.i-1)throw new RangeError;this.J[l]=a}insert(l,a,c=1){if(l<0||l>this.i)throw new RangeError;return this.J.splice(l,0,...new Array(c).fill(a)),this.i+=c,this.i}find(l){for(let a=0;a<this.i;++a)if(this.J[a]===l)return new o(a,this);return this.end()}reverse(){this.J.reverse()}unique(){let l=1;for(let a=1;a<this.i;++a)this.J[a]!==this.J[a-1]&&(this.J[l++]=this.J[a]);return this.i=this.J.length=l,this.i}sort(l){this.J.sort(l)}forEach(l){for(let a=0;a<this.i;++a)l(this.J[a],a,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},i=n;s.default=i}),mu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(vi()),t=mt(),r=gt();function o(a){return a&&a.t?a:{default:a}}var n=class bc 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 bc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(a=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;a.forEach(function(u){c.pushBack(u)})}V(a){let{L:c,B:u}=a;c.B=u,u.L=c,a===this.p&&(this.p=u),a===this._&&(this._=c),this.i-=1}G(a,c){let u=c.B,h={l:a,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(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return c.l}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return this.V(c),this.i}eraseElementByValue(a){let c=this.p;for(;c!==this.h;)c.l===a&&this.V(c),c=c.B;return this.i}eraseElementByIterator(a){let c=a.o;return c===this.h&&(0,r.throwIteratorAccessError)(),a=a.next(),this.V(c),a}pushBack(a){return this.G(a,this._),this.i}popBack(){if(this.i===0)return;let a=this._.l;return this.V(this._),a}pushFront(a){return this.G(a,this.h),this.i}popFront(){if(this.i===0)return;let a=this.p.l;return this.V(this.p),a}setElementByPos(a,c){if(a<0||a>this.i-1)throw new RangeError;let u=this.p;for(;a--;)u=u.B;u.l=c}insert(a,c,u=1){if(a<0||a>this.i)throw new RangeError;if(u<=0)return this.i;if(a===0)for(;u--;)this.pushFront(c);else if(a===this.i)for(;u--;)this.pushBack(c);else{let h=this.p;for(let g=1;g<a;++g)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(a){let c=this.p;for(;c!==this.h;){if(c.l===a)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let a=this.p,c=this._,u=0;for(;u<<1<this.i;){let h=a.l;a.l=c.l,c.l=h,a=a.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let a=this.p;for(;a!==this.h;){let c=a;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;a.B=c.B,a.B.L=a,a=a.B}return this.i}sort(a){if(this.i<=1)return;let c=[];this.forEach(function(h){c.push(h)}),c.sort(a);let u=this.p;c.forEach(function(h){u.l=h,u=u.B})}merge(a){let c=this;if(this.i===0)a.forEach(function(u){c.pushBack(u)});else{let u=this.p;a.forEach(function(h){for(;u!==c.h&&u.l<=h;)u=u.B;c.G(h,u.L)})}return this.i}forEach(a){let c=this.p,u=0;for(;c!==this.h;)a(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let a=this.p;for(;a!==this.h;)yield a.l,a=a.B}).bind(this)()}},l=i;s.default=l}),gu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=r(vi()),t=xs();function r(l){return l&&l.t?l:{default:l}}var o=class yc extends t.RandomIterator{constructor(a,c,u){super(a,u),this.container=c}copy(){return new yc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(l=[],a=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof l.length=="number")return l.length;if(typeof l.size=="number")return l.size;if(typeof l.size=="function")return l.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=a,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;l.forEach(function(p){h.pushBack(p)})}T(){let l=[],a=Math.max(this.P>>1,1);for(let c=0;c<a;++c)l[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)l[l.length]=this.A[c];for(let c=0;c<this.R;++c)l[l.length]=this.A[c];l[l.length]=[...this.A[this.R]],this.j=a,this.R=l.length-1;for(let c=0;c<a;++c)l[l.length]=new Array(this.F);this.A=l,this.P=l.length}O(l){let a=this.D+l+1,c=a%this.F,u=c-1,h=this.j+(a-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(l){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]=l,this.i}popBack(){if(this.i===0)return;let l=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,l}pushFront(l){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]=l,this.i}popFront(){if(this.i===0)return;let l=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,l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let{curNodeBucketIndex:a,curNodePointerIndex:c}=this.O(l);return this.A[a][c]}setElementByPos(l,a){if(l<0||l>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(l);this.A[c][u]=a}insert(l,a,c=1){if(l<0||l>this.i)throw new RangeError;if(l===0)for(;c--;)this.pushFront(a);else if(l===this.i)for(;c--;)this.pushBack(a);else{let u=[];for(let h=l;h<this.i;++h)u.push(this.getElementByPos(h));this.cut(l-1);for(let h=0;h<c;++h)this.pushBack(a);for(let h=0;h<u.length;++h)this.pushBack(u[h])}return this.i}cut(l){if(l<0)return this.clear(),0;let{curNodeBucketIndex:a,curNodePointerIndex:c}=this.O(l);return this.R=a,this.N=c,this.i=l+1,this.i}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;if(l===0)this.popFront();else if(l===this.i-1)this.popBack();else{let a=[];for(let u=l+1;u<this.i;++u)a.push(this.getElementByPos(u));this.cut(l),this.popBack();let c=this;a.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(l){if(this.i===0)return 0;let a=[];for(let u=0;u<this.i;++u){let h=this.getElementByPos(u);h!==l&&a.push(h)}let c=a.length;for(let u=0;u<c;++u)this.setElementByPos(u,a[u]);return this.cut(c-1)}eraseElementByIterator(l){let a=l.o;return this.eraseElementByPos(a),l=l.next(),l}find(l){for(let a=0;a<this.i;++a)if(this.getElementByPos(a)===l)return new o(a,this);return this.end()}reverse(){let l=0,a=this.i-1;for(;l<a;){let c=this.getElementByPos(l);this.setElementByPos(l,this.getElementByPos(a)),this.setElementByPos(a,c),l+=1,a-=1}}unique(){if(this.i<=1)return this.i;let l=1,a=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==a&&(a=u,this.setElementByPos(l++,u))}for(;this.i>l;)this.popBack();return this.i}sort(l){let a=[];for(let c=0;c<this.i;++c)a.push(this.getElementByPos(c));a.sort(l);for(let c=0;c<this.i;++c)this.setElementByPos(c,a[c])}shrinkToFit(){if(this.i===0)return;let l=[];this.forEach(function(a){l.push(a)}),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 a=0;a<this.P;++a)this.A.push(new Array(this.F));for(let a=0;a<l.length;++a)this.pushBack(l[a])}forEach(l){for(let a=0;a<this.i;++a)l(this.getElementByPos(a),a,this)}[Symbol.iterator](){return(function*(){for(let l=0;l<this.i;++l)yield this.getElementByPos(l)}).bind(this)()}},i=n;s.default=i}),bu=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}),Ss=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=bu(),t=mt(),r=gt(),o=class extends t.Container{constructor(i=function(a,c){return a<c?-1:a>c?1:0},l=!1){super(),this.Y=void 0,this.v=i,l?(this.re=e.TreeNodeEnableIndex,this.M=function(a,c,u){let h=this.ne(a,c,u);if(h){let p=h.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let g=this.he(h);if(g){let{parentNode:f,grandParent:b,curNode:y}=g;f.ie(),b.ie(),y.ie()}}return this.i},this.V=function(a){let c=this.fe(a);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(a,c,u){let h=this.ne(a,c,u);return h&&this.he(h),this.i},this.V=this.fe),this.h=new this.re}X(i,l){let a=this.h;for(;i;){let c=this.v(i.u,l);if(c<0)i=i.W;else if(c>0)a=i,i=i.U;else return i}return a}Z(i,l){let a=this.h;for(;i;)this.v(i.u,l)<=0?i=i.W:(a=i,i=i.U);return a}$(i,l){let a=this.h;for(;i;){let c=this.v(i.u,l);if(c<0)a=i,i=i.W;else if(c>0)i=i.U;else return i}return a}rr(i,l){let a=this.h;for(;i;)this.v(i.u,l)<0?(a=i,i=i.W):i=i.U;return a}ue(i){for(;;){let l=i.tt;if(l===this.h)return;if(i.ee===1){i.ee=0;return}if(i===l.U){let a=l.W;if(a.ee===1)a.ee=0,l.ee=1,l===this.Y?this.Y=l.te():l.te();else if(a.W&&a.W.ee===1){a.ee=l.ee,l.ee=0,a.W.ee=0,l===this.Y?this.Y=l.te():l.te();return}else a.U&&a.U.ee===1?(a.ee=1,a.U.ee=0,a.se()):(a.ee=1,i=l)}else{let a=l.U;if(a.ee===1)a.ee=0,l.ee=1,l===this.Y?this.Y=l.se():l.se();else if(a.U&&a.U.ee===1){a.ee=l.ee,l.ee=0,a.U.ee=0,l===this.Y?this.Y=l.se():l.se();return}else a.W&&a.W.ee===1?(a.ee=1,a.W.ee=0,a.te()):(a.ee=1,i=l)}}}fe(i){if(this.i===1)return this.clear(),this.h;let l=i;for(;l.U||l.W;){if(l.W)for(l=l.W;l.U;)l=l.U;else l=l.U;[i.u,l.u]=[l.u,i.u],[i.l,l.l]=[l.l,i.l],i=l}this.h.U===l?this.h.U=l.tt:this.h.W===l&&(this.h.W=l.tt),this.ue(l);let a=l.tt;return l===a.U?a.U=void 0:a.W=void 0,this.i-=1,this.Y.ee=0,a}oe(i,l){return i===void 0?!1:this.oe(i.U,l)||l(i)?!0:this.oe(i.W,l)}he(i){for(;;){let l=i.tt;if(l.ee===0)return;let a=l.tt;if(l===a.U){let c=a.W;if(c&&c.ee===1){if(c.ee=l.ee=0,a===this.Y)return;a.ee=1,i=a;continue}else if(i===l.W){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,a===this.Y)this.Y=i,this.h.tt=i;else{let u=a.tt;u.U===a?u.U=i:u.W=i}return i.tt=a.tt,l.tt=i,a.tt=i,a.ee=1,{parentNode:l,grandParent:a,curNode:i}}else l.ee=0,a===this.Y?this.Y=a.se():a.se(),a.ee=1}else{let c=a.U;if(c&&c.ee===1){if(c.ee=l.ee=0,a===this.Y)return;a.ee=1,i=a;continue}else if(i===l.U){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,a===this.Y)this.Y=i,this.h.tt=i;else{let u=a.tt;u.U===a?u.U=i:u.W=i}return i.tt=a.tt,l.tt=i,a.tt=i,a.ee=1,{parentNode:l,grandParent:a,curNode:i}}else l.ee=0,a===this.Y?this.Y=a.te():a.te(),a.ee=1}return}}ne(i,l,a){if(this.Y===void 0){this.i+=1,this.Y=new this.re(i,l),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=l;return}else if(h>0)u.U=new this.re(i,l),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,g=this.v(p.u,i);if(g===0){p.l=l;return}else if(g<0)p.W=new this.re(i,l),p.W.tt=p,c=p.W,this.h.W=c;else{if(a!==void 0){let f=a.o;if(f!==this.h){let b=this.v(f.u,i);if(b===0){f.l=l;return}else if(b>0){let y=f.L(),w=this.v(y.u,i);if(w===0){y.l=l;return}else w<0&&(c=new this.re(i,l),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,l),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,l),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=l;return}}}}return this.i+=1,c}I(i,l){for(;i;){let a=this.v(i.u,l);if(a<0)i=i.W;else if(a>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,l){let a=i.o;if(a===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return a.u=l,!0;if(a===this.h.U)return this.v(a.B().u,l)>0?(a.u=l,!0):!1;if(a===this.h.W)return this.v(a.L().u,l)<0?(a.u=l,!0):!1;let c=a.L().u;if(this.v(c,l)>=0)return!1;let u=a.B().u;return this.v(u,l)<=0?!1:(a.u=l,!0)}eraseElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let l=0,a=this;return this.oe(this.Y,function(c){return i===l?(a.V(c),!0):(l+=1,!1)}),this.i}eraseElementByKey(i){if(this.i===0)return!1;let l=this.I(this.Y,i);return l===this.h?!1:(this.V(l),!0)}eraseElementByIterator(i){let l=i.o;l===this.h&&(0,r.throwIteratorAccessError)();let a=l.W===void 0;return i.iteratorType===0?a&&i.next():(!a||l.U===void 0)&&i.next(),this.V(l),i}forEach(i){let l=0;for(let a of this)i(a,l++,this)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let l,a=0;for(let c of this){if(a===i){l=c;break}a+=1}return l}getHeight(){if(this.i===0)return 0;let i=function(l){return l?Math.max(i(l.U),i(l.W))+1:0};return i(this.Y)}},n=o;s.default=n}),Es=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=gt(),r=class extends e.ContainerIterator{constructor(n,i,l){super(l),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 l=0;for(n.U&&(l+=n.U.rt);n!==i;){let a=n.tt;n===a.W&&(l+=1,a.U&&(l+=a.U.rt)),n=a}return l}},o=r;s.default=o}),yu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(Ss()),t=o(Es()),r=gt();function o(a){return a&&a.t?a:{default:a}}var n=class vc 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 vc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(a=[],c,u){super(c,u);let h=this;a.forEach(function(p){h.insert(p)})}*K(a){a!==void 0&&(yield*this.K(a.U),yield a.u,yield*this.K(a.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(a,c){return this.M(a,void 0,c)}find(a){let c=this.I(this.Y,a);return new n(c,this.h,this)}lowerBound(a){let c=this.X(this.Y,a);return new n(c,this.h,this)}upperBound(a){let c=this.Z(this.Y,a);return new n(c,this.h,this)}reverseLowerBound(a){let c=this.$(this.Y,a);return new n(c,this.h,this)}reverseUpperBound(a){let c=this.rr(this.Y,a);return new n(c,this.h,this)}union(a){let c=this;return a.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},l=i;s.default=l}),vu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(Ss()),t=o(Es()),r=gt();function o(a){return a&&a.t?a:{default:a}}var n=class wc 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 wc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(a=[],c,u){super(c,u);let h=this;a.forEach(function(p){h.setElement(p[0],p[1])})}*K(a){a!==void 0&&(yield*this.K(a.U),yield[a.u,a.l],yield*this.K(a.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 a=this.h.U;return[a.u,a.l]}back(){if(this.i===0)return;let a=this.h.W;return[a.u,a.l]}lowerBound(a){let c=this.X(this.Y,a);return new n(c,this.h,this)}upperBound(a){let c=this.Z(this.Y,a);return new n(c,this.h,this)}reverseLowerBound(a){let c=this.$(this.Y,a);return new n(c,this.h,this)}reverseUpperBound(a){let c=this.rr(this.Y,a);return new n(c,this.h,this)}setElement(a,c,u){return this.M(a,c,u)}find(a){let c=this.I(this.Y,a);return new n(c,this.h,this)}getElementByKey(a){return this.I(this.Y,a).l}union(a){let c=this;return a.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},l=i;s.default=l}),As=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"}}),Is=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.HashContainerIterator=s.HashContainer=void 0;var e=mt(),t=o(As()),r=gt();function o(l){return l&&l.t?l:{default:l}}var n=class extends e.ContainerIterator{constructor(l,a,c){super(c),this.o=l,this.h=a,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(l){let{L:a,B:c}=l;a.B=c,c.L=a,l===this.p&&(this.p=c),l===this._&&(this._=a),this.i-=1}M(l,a,c){c===void 0&&(c=(0,t.default)(l));let u;if(c){let h=l[this.HASH_TAG];if(h!==void 0)return this.H[h].l=a,this.i;Object.defineProperty(l,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:l,l:a,L:this._,B:this.h},this.H.push(u)}else{let h=this.g[l];if(h)return h.l=a,this.i;u={u:l,l:a,L:this._,B:this.h},this.g[l]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(l,a){if(a===void 0&&(a=(0,t.default)(l)),a){let c=l[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[l]||this.h}clear(){let l=this.HASH_TAG;this.H.forEach(function(a){delete a.u[l]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(l,a){let c;if(a===void 0&&(a=(0,t.default)(l)),a){let u=l[this.HASH_TAG];if(u===void 0)return!1;delete l[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[l],c===void 0)return!1;delete this.g[l]}return this.V(c),!0}eraseElementByIterator(l){let a=l.o;return a===this.h&&(0,r.throwIteratorAccessError)(),this.V(a),l.next()}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let a=this.p;for(;l--;)a=a.B;return this.V(a),this.i}};s.HashContainer=i}),wu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=Is(),t=gt(),r=class _c extends e.HashContainerIterator{constructor(l,a,c,u){super(l,a,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new _c(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.HashContainer{constructor(i=[]){super();let l=this;i.forEach(function(a){l.insert(a)})}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,l){return this.M(i,void 0,l)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let l=this.p;for(;i--;)l=l.B;return l.u}find(i,l){let a=this.I(i,l);return new r(a,this.h,this)}forEach(i){let l=0,a=this.p;for(;a!==this.h;)i(a.u,l++,this),a=a.B}[Symbol.iterator](){return(function*(){let i=this.p;for(;i!==this.h;)yield i.u,i=i.B}).bind(this)()}},n=o;s.default=n}),_u=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=Is(),t=o(As()),r=gt();function o(a){return a&&a.t?a:{default:a}}var n=class kc 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 kc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(a=[]){super();let c=this;a.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(a,c,u){return this.M(a,c,u)}getElementByKey(a,c){if(c===void 0&&(c=(0,t.default)(a)),c){let h=a[this.HASH_TAG];return h!==void 0?this.H[h].l:void 0}let u=this.g[a];return u?u.l:void 0}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return[c.u,c.l]}find(a,c){let u=this.I(a,c);return new n(u,this.h,this)}forEach(a){let c=0,u=this.p;for(;u!==this.h;)a([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let a=this.p;for(;a!==this.h;)yield[a.u,a.l],a=a.B}).bind(this)()}},l=i;s.default=l}),ku=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 a.default}}),Object.defineProperty(s,"OrderedSet",{enumerable:!0,get:function(){return l.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(hu()),t=h(du()),r=h(fu()),o=h(pu()),n=h(mu()),i=h(gu()),l=h(yu()),a=h(vu()),c=h(wu()),u=h(_u());function h(p){return p&&p.t?p:{default:p}}}),xu=pe((s,e)=>{le(),ue(),ce();var t=ku().OrderedSet,r=pt()("number-allocator:trace"),o=pt()("number-allocator:error");function n(l,a){this.low=l,this.high=a}n.prototype.equals=function(l){return this.low===l.low&&this.high===l.high},n.prototype.compare=function(l){return this.low<l.low&&this.high<l.low?-1:l.low<this.low&&l.high<this.low?1:0};function i(l,a){if(!(this instanceof i))return new i(l,a);this.min=l,this.max=a,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 l=this.ss.begin(),a=l.pointer.low,c=l.pointer.high,u=a;return u+1<=c?this.ss.updateKeyByIterator(l,new n(a+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},i.prototype.use=function(l){let a=new n(l,l),c=this.ss.lowerBound(a);if(!c.equals(this.ss.end())){let u=c.pointer.low,h=c.pointer.high;return c.pointer.equals(a)?(this.ss.eraseElementByIterator(c),r("use():"+l),!0):u>l?!1:u===l?(this.ss.updateKeyByIterator(c,new n(u+1,h)),r("use():"+l),!0):h===l?(this.ss.updateKeyByIterator(c,new n(u,h-1)),r("use():"+l),!0):(this.ss.updateKeyByIterator(c,new n(l+1,h)),this.ss.insert(new n(u,l-1)),r("use():"+l),!0)}return r("use():failed"),!1},i.prototype.free=function(l){if(l<this.min||l>this.max){o("free():"+l+" is out of range");return}let a=new n(l,l),c=this.ss.upperBound(a);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(a);return}c.pre();let u=c.pointer.high;c.pointer.high+1===l?this.ss.updateKeyByIterator(c,new n(u,l)):this.ss.insert(a)}else if(c.equals(this.ss.begin()))if(l+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(l,u))}else this.ss.insert(a);else{let u=c.pointer.low,h=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===l?l+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,h))):this.ss.updateKeyByIterator(c,new n(p,l)):l+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(l,h))):this.ss.insert(a)}r("free():"+l)},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 l of this.ss)console.log(l)},e.exports=i}),Ts=pe((s,e)=>{le(),ue(),ce();var t=xu();e.exports.NumberAllocator=t}),Su=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=uu(),t=Ts(),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}),Eu=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=yr(),r=e(Su()),o=$t(),n=(i,l)=>{i.log("_handleConnack");let{options:a}=i,c=a.protocolVersion===5?l.reasonCode:l.returnCode;if(clearTimeout(i.connackTimer),delete i.topicAliasSend,l.properties){if(l.properties.topicAliasMaximum){if(l.properties.topicAliasMaximum>65535){i.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}l.properties.topicAliasMaximum>0&&(i.topicAliasSend=new r.default(l.properties.topicAliasMaximum))}l.properties.serverKeepAlive&&a.keepalive&&(a.keepalive=l.properties.serverKeepAlive),l.properties.maximumPacketSize&&(a.properties||(a.properties={}),a.properties.maximumPacketSize=l.properties.maximumPacketSize)}if(c===0)i.reconnecting=!1,i._onConnect(l);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}),Au=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,l={cmd:"pubcomp",messageId:i};t.incomingStore.get(r,(a,c)=>{a?t._sendPacket(l,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(l,n)}))})};s.default=e}),Iu=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(au()),r=e(cu()),o=e(Eu()),n=e(yr()),i=e(Au()),l=(a,c,u)=>{let{options:h}=a;if(h.protocolVersion===5&&h.properties&&h.properties.maximumPacketSize&&h.properties.maximumPacketSize<c.length)return a.emit("error",new Error(`exceeding packets size ${c.cmd}`)),a.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),a;switch(a.log("_handlePacket :: emitting packetreceive"),a.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(a,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":a.reschedulePing(),(0,n.default)(a,c),u();break;case"pubrel":a.reschedulePing(),(0,i.default)(a,c,u);break;case"connack":(0,o.default)(a,c),u();break;case"auth":a.reschedulePing(),(0,r.default)(a,c),u();break;case"pingresp":a.log("_handlePacket :: received pingresp"),a.reschedulePing(!0),u();break;case"disconnect":a.emit("disconnect",c),u();break;default:a.log("_handlePacket :: unknown command"),u();break}};s.default=l}),Cs=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}),Tu=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}),Cu=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((Tt(),Re(wt))),r=$t(),o=class{};s.TypedEventEmitter=o,(0,r.applyMixin)(o,t.default)}),vr=pe((s,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o){return typeof o}:function(o){return o&&typeof Symbol=="function"&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ou=pe((s,e)=>{le(),ue(),ce();var t=vr().default;function r(o,n){if(t(o)!="object"||!o)return o;var i=o[Symbol.toPrimitive];if(i!==void 0){var l=i.call(o,n||"default");if(t(l)!="object")return l;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}),Pu=pe((s,e)=>{le(),ue(),ce();var t=vr().default,r=Ou();function o(n){var i=r(n,"string");return t(i)=="symbol"?i:i+""}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Mu=pe((s,e)=>{le(),ue(),ce();var t=Pu();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}),Ru=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}),Lu=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,l,a,c,u=[],h=!0,p=!1;try{if(a=(n=n.call(r)).next,o===0){if(Object(n)!==n)return;h=!1}else for(;!(h=(i=a.call(n)).done)&&(u.push(i.value),u.length!==o);h=!0);}catch(g){p=!0,l=g}finally{try{if(!h&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw l}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Nu=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}),ju=pe((s,e)=>{le(),ue(),ce();var t=Nu();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}),Uu=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}),Bu=pe((s,e)=>{le(),ue(),ce();var t=Ru(),r=Lu(),o=ju(),n=Uu();function i(l,a){return t(l)||r(l,a)||o(l,a)||n()}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),Os=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(s,function(t){var r=function(g){return function(f){var b=g(f);return f.add(b),b}},o=function(g){return function(f,b){return g.set(f,b),b}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,l=i*2,a=function(g,f){return function(b){var y=f.get(b),w=y===void 0?b.size:y<l?y+1:0;if(!b.has(w))return g(b,w);if(b.size<i){for(;b.has(w);)w=Math.floor(Math.random()*l);return g(b,w)}if(b.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;b.has(w);)w=Math.floor(Math.random()*n);return g(b,w)}},c=new WeakMap,u=o(c),h=a(u,c),p=r(h);t.addUniqueNumber=p,t.generateUniqueNumber=h})}),Du=pe((s,e)=>{le(),ue(),ce();function t(o,n,i,l,a,c,u){try{var h=o[c](u),p=h.value}catch(g){return void i(g)}h.done?n(p):Promise.resolve(p).then(l,a)}function r(o){return function(){var n=this,i=arguments;return new Promise(function(l,a){var c=o.apply(n,i);function u(p){t(c,l,a,u,h,"next",p)}function h(p){t(c,l,a,u,h,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ps=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}),Ms=pe((s,e)=>{le(),ue(),ce();function t(r,o,n,i){var l=Object.defineProperty;try{l({},"",{})}catch{l=0}e.exports=t=function(a,c,u,h){function p(g,f){t(a,g,function(b){return this._invoke(g,f,b)})}c?l?l(a,c,{value:u,enumerable:!h,configurable:!h,writable:!h}):a[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}),Rs=pe((s,e)=>{le(),ue(),ce();var t=Ms();function r(){var o,n,i=typeof Symbol=="function"?Symbol:{},l=i.iterator||"@@iterator",a=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&&!F&&n<D.length;n++){var F,Z=D[n],M=ae.p,Q=Z[2];V>3?(F=Q===re)&&(T=Z[(j=Z[4])?5:(j=3,3)],Z[4]=Z[5]=o):Z[0]<=M&&((F=V<2&&M<Z[1])?(j=0,ae.v=re,ae.n=Z[1]):M<Q&&(F=V<3||Z[0]>re||re>Q)&&(Z[4]=V,Z[5]=re,ae.n=Q,j=0))}if(F||V>1)return u;throw U=!0,re}return function(V,re,F){if(q>1)throw TypeError("Generator is already running");for(U&&re===1&&Y(re,F),j=re,T=F;(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 g(){}n=Object.getPrototypeOf;var f=[][l]?n(n([][l]())):(t(n={},l,function(){return this}),n),b=g.prototype=h.prototype=Object.create(f);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,a,"GeneratorFunction")),w.prototype=Object.create(b),w}return p.prototype=g,t(b,"constructor",g),t(g,"constructor",p),p.displayName="GeneratorFunction",t(g,a,"GeneratorFunction"),t(b),t(b,a,"Generator"),t(b,l,function(){return this}),t(b,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ls=pe((s,e)=>{le(),ue(),ce();var t=Ps(),r=Ms();function o(n,i){function l(c,u,h,p){try{var g=n[c](u),f=g.value;return f instanceof t?i.resolve(f.v).then(function(b){l("next",b,h,p)},function(b){l("throw",b,h,p)}):i.resolve(f).then(function(b){g.value=b,h(g)},function(b){return l("throw",b,h,p)})}catch(b){p(b)}}var a;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(g,f){l(c,h,g,f)})}return a=a?a.then(p,p):p()},!0)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Ns=pe((s,e)=>{le(),ue(),ce();var t=Rs(),r=Ls();function o(n,i,l,a,c){return new r(t().w(n,i,l,a),c||Promise)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Fu=pe((s,e)=>{le(),ue(),ce();var t=Ns();function r(o,n,i,l,a){var c=t(o,n,i,l,a);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}),$u=pe((s,e)=>{le(),ue(),ce();function t(r){var o=Object(r),n=[];for(var i in o)n.unshift(i);return function l(){for(;n.length;)if((i=n.pop())in o)return l.value=i,l.done=!1,l;return l.done=!0,l}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),qu=pe((s,e)=>{le(),ue(),ce();var t=vr().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}),Hu=pe((s,e)=>{le(),ue(),ce();var t=Ps(),r=Rs(),o=Fu(),n=Ns(),i=Ls(),l=$u(),a=qu();function c(){var u=r(),h=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(h):h.__proto__).constructor;function g(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 b(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,a(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(b(y),w,m,_&&_.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:i,async:function(y,w,m,_,x){return(g(w)?n:o)(b(y),w,m,_,x)},keys:l,values:a}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),Wu=pe((s,e)=>{le(),ue(),ce();var t=Hu()();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,Mu(),Bu(),Os(),Du(),Wu()):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,l){var a=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(l.mark(function v(){var E,S,I,O;return l.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(l.mark(function E(S){var I;return l.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 g(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?g(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):g(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var b=new WeakMap,y=function(m){if(b.has(m))return b.get(m);var _=new Map;return b.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))}}),a(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=f(f({},I),{},r({},T,q({call:E,notify:S})))}return f({},I)}};t.createBroker=w})}),Vu=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,vr(),zu(),Os()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimersBroker={},t._typeof,t.brokerFactory,t.fastUniqueNumbers))})(s,function(t,r,o,n){var i=new Map([[0,null]]),l=new Map([[0,null]]),a=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(l.get(p))==="symbol"&&(l.set(p,null),h("clear",{timerId:p,timerType:"timeout"}).then(function(){l.delete(p)}))}},setInterval:function(u){var h=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,b=new Array(f>2?f-2:0),y=2;y<f;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(i);i.set(m,w);var _=function(){return h("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=i.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===w&&(p.apply(void 0,b),i.get(m)===w&&_())})};return _(),m}},setTimeout:function(u){var h=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,b=new Array(f>2?f-2:0),y=2;y<f;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(l);return l.set(m,w),h("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var _=l.get(m);if(_===void 0)throw new Error("The timer is in an undefined state.");_===w&&(l.delete(m),p.apply(void 0,b))}),m}}}),c=function(u){var h=new Worker(u);return a(h)};t.load=c,t.wrap=a})}),Ku=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,Vu()):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 g=null;return function(){if(g!==null)return g;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),b=URL.createObjectURL(f);return g=h(b),setTimeout(function(){return URL.revokeObjectURL(b)}),g}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,i=o(r.load,n),l=function(h){return i().clearInterval(h)},a=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=l,t.clearTimeout=a,t.setInterval=c,t.setTimeout=u})}),wr=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&&Le?.versions?!Object.prototype.hasOwnProperty.call(Le.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}),Gu=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(c,u,h,p){p===void 0&&(p=h);var g=Object.getOwnPropertyDescriptor(u,h);(!g||("get"in g?!u.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return u[h]}}),Object.defineProperty(c,p,g)}: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 g in h)Object.prototype.hasOwnProperty.call(h,g)&&(p[p.length]=g);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var h={};if(u!=null)for(var p=c(u),g=0;g<p.length;g++)p[g]!=="default"&&e(h,u,p[g]);return t(h,u),h}})();Object.defineProperty(s,"__esModule",{value:!0});var o=Ku(),n=r(wr()),i={set:o.setInterval,clear:o.clearInterval},l={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},a=c=>{switch(c){case"native":return l;case"worker":return i;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?i:l}};s.default=a}),js=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(Gu()),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}),wi=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(iu()),i=Ot(),l=o(su()),a=o(pt()),c=r(_s()),u=o(ks()),h=o(Iu()),p=o(Cs()),g=o(Tu()),f=$t(),b=Cu(),y=o(js()),w=r(wr()),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 No extends b.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 I in _)typeof this.options[I]>"u"?this.options[I]=_[I]:this.options[I]=S[I];this.log=this.options.log||(0,a.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",No.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:No.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 g.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,f.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,F)=>{if(F=F||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<F.qos||P){let Z={topic:re,qos:F.qos};O===5&&(Z.nl=F.nl,Z.rap=F.rap,Z.rh=F.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,F)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:F};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 f.ErrorWithSubackPacket(te.message,we)):Q(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),M},V=()=>{let re=this.options.subscribeBatchSize??U.length,F=[];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;F.push(Y(M,Q))}return Promise.all(F).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,f.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,l.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,l.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}),Yu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Ts(),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 Ju(){if(_i)return _r;_i=!0;let s=2147483647,e=36,t=1,r=26,o=38,n=700,i=72,l=128,a="-",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"},g=e-t,f=Math.floor,b=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?f(P/n):P>>1,P+=f(P/j);P>g*r>>1;q+=e)P=f(P/g);return f(q+(g+1)*P/(P+o))},I=function(P){let j=[],T=P.length,q=0,D=l,U=i,ae=P.lastIndexOf(a);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 F=1,Z=e;;Z+=e){Y>=T&&y("invalid-input");let M=v(P.charCodeAt(Y++));M>=e&&y("invalid-input"),M>f((s-q)/F)&&y("overflow"),q+=M*F;let Q=Z<=U?t:Z>=U+r?r:Z-U;if(M<Q)break;let be=e-Q;F>f(s/be)&&y("overflow"),F*=be}let re=j.length+1;U=S(q-V,re,V==0),f(q/re)>s-D&&y("overflow"),D+=f(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=l,D=0,U=i;for(let V of P)V<128&&j.push(b(V));let ae=j.length,Y=ae;for(ae&&j.push(a);Y<T;){let V=s;for(let F of P)F>=q&&F<V&&(V=F);let re=Y+1;V-q>f((s-D)/re)&&y("overflow"),D+=(V-q)*re,q=V;for(let F of P)if(F<q&&++D>s&&y("overflow"),F===q){let Z=D;for(let M=e;;M+=e){let Q=M<=U?t:M>=U+r?r:M-U;if(Z<Q)break;let be=Z-Q,te=e-Q;j.push(b(E(Q+be%te,0))),Z=f(be/te)}j.push(b(E(Z,0))),U=S(D,re,Y===ae),D=0,++Y}++D,++q}return j.join("")};return _r={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})}},_r}var _r,_i,kt,Qu=Ge(()=>{le(),ue(),ce(),_r={},_i=!1,kt=Ju(),kt.decode,kt.encode,kt.toASCII,kt.toUnicode,kt.ucs2,kt.version});function Xu(){return Ei||(Ei=!0,Si=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}),Si}function Zu(){return Ii||(Ii=!0,Ai=Error),Ai}function eh(){return Ci||(Ci=!0,Ti=EvalError),Ti}function th(){return Pi||(Pi=!0,Oi=RangeError),Oi}function rh(){return Ri||(Ri=!0,Mi=ReferenceError),Mi}function Us(){return Ni||(Ni=!0,Li=SyntaxError),Li}function tr(){return Ui||(Ui=!0,ji=TypeError),ji}function nh(){return Di||(Di=!0,Bi=URIError),Bi}function ih(){if(Fi)return kr;Fi=!0;var s=typeof Symbol<"u"&&Symbol,e=Xu();return kr=function(){return typeof s!="function"||typeof Symbol!="function"||typeof s("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},kr}function oh(){if($i)return xr;$i=!0;var s={__proto__:null,foo:{}},e=Object;return xr=function(){return{__proto__:s}.foo===s.foo&&!(s instanceof e)},xr}function sh(){if(qi)return Sr;qi=!0;var s="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",o=function(l,a){for(var c=[],u=0;u<l.length;u+=1)c[u]=l[u];for(var h=0;h<a.length;h+=1)c[h+l.length]=a[h];return c},n=function(l,a){for(var c=[],u=a,h=0;u<l.length;u+=1,h+=1)c[h]=l[u];return c},i=function(l,a){for(var c="",u=0;u<l.length;u+=1)c+=l[u],u+1<l.length&&(c+=a);return c};return Sr=function(l){var a=this;if(typeof a!="function"||e.apply(a)!==r)throw new TypeError(s+a);for(var c=n(arguments,1),u,h=function(){if(this instanceof u){var y=a.apply(this,o(c,arguments));return Object(y)===y?y:this}return a.apply(l,o(c,arguments))},p=t(0,a.length-c.length),g=[],f=0;f<p;f++)g[f]="$"+f;if(u=Function("binder","return function ("+i(g,",")+"){ return binder.apply(this,arguments); }")(h),a.prototype){var b=function(){};b.prototype=a.prototype,u.prototype=new b,b.prototype=null}return u},Sr}function ki(){if(Hi)return Er;Hi=!0;var s=sh();return Er=Function.prototype.bind||s,Er}function ah(){if(Wi)return Ar;Wi=!0;var s=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=ki();return Ar=t.call(s,e),Ar}function qt(){if(zi)return Ir;zi=!0;var s,e=Zu(),t=eh(),r=th(),o=rh(),n=Us(),i=tr(),l=nh(),a=Function,c=function(Y){try{return a('"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,g=ih()(),f=oh()(),b=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),y={},w=typeof Uint8Array>"u"||!b?s:b(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?s:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?s:ArrayBuffer,"%ArrayIteratorPrototype%":g&&b?b([][Symbol.iterator]()):s,"%AsyncFromSyncIteratorPrototype%":s,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":typeof Atomics>"u"?s:Atomics,"%BigInt%":typeof BigInt>"u"?s:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?s:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?s:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?s:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?s:Float32Array,"%Float64Array%":typeof Float64Array>"u"?s:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?s:FinalizationRegistry,"%Function%":a,"%GeneratorFunction%":y,"%Int8Array%":typeof Int8Array>"u"?s:Int8Array,"%Int16Array%":typeof Int16Array>"u"?s:Int16Array,"%Int32Array%":typeof Int32Array>"u"?s:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&b?b(b([][Symbol.iterator]())):s,"%JSON%":typeof JSON=="object"?JSON:s,"%Map%":typeof Map>"u"?s:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!b?s:b(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?s:Promise,"%Proxy%":typeof Proxy>"u"?s:Proxy,"%RangeError%":r,"%ReferenceError%":o,"%Reflect%":typeof Reflect>"u"?s:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?s:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!b?s:b(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?s:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&b?b(""[Symbol.iterator]()):s,"%Symbol%":g?Symbol:s,"%SyntaxError%":n,"%ThrowTypeError%":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%":l,"%WeakMap%":typeof WeakMap>"u"?s:WeakMap,"%WeakRef%":typeof WeakRef>"u"?s:WeakRef,"%WeakSet%":typeof WeakSet>"u"?s:WeakSet};if(b)try{null.error}catch(Y){var _=b(b(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 F=Y("%AsyncGeneratorFunction%");F&&(re=F.prototype)}else if(V==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&b&&(re=b(Z.prototype))}return m[V]=re,re},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},E=ki(),S=ah(),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 F=[];return P(Y,q,function(Z,M,Q,be){F[F.length]=Q?P(be,D,"$1"):M||Z}),F},ae=function(Y,V){var re=Y,F;if(S(v,re)&&(F=v[re],re="%"+F[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:F,name:re,value:Z}}throw new n("intrinsic "+Y+" does not exist!")};return Ir=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),F=re.length>0?re[0]:"",Z=ae("%"+F+"%",V),M=Z.name,Q=Z.value,be=!1,te=Z.alias;te&&(F=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),F+="."+N,M="%"+F+"%",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},Ir}function xi(){if(Vi)return Tr;Vi=!0;var s=qt(),e=s("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Tr=e,Tr}function Bs(){if(Ki)return Cr;Ki=!0;var s=qt(),e=s("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Cr=e,Cr}function lh(){if(Gi)return Or;Gi=!0;var s=xi(),e=Us(),t=tr(),r=Bs();return Or=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 l=arguments.length>3?arguments[3]:null,a=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:l===null&&h?h.enumerable:!l,value:i,writable:a===null&&h?h.writable:!a});else if(u||!l&&!a&&!c)o[n]=i;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Or}function ch(){if(Yi)return Pr;Yi=!0;var s=xi(),e=function(){return!!s};return e.hasArrayLengthDefineBug=function(){if(!s)return null;try{return s([],"length",{value:1}).length!==1}catch{return!0}},Pr=e,Pr}function uh(){if(Ji)return Mr;Ji=!0;var s=qt(),e=lh(),t=ch()(),r=Bs(),o=tr(),n=s("%Math.floor%");return Mr=function(i,l){if(typeof i!="function")throw new o("`fn` is not a function");if(typeof l!="number"||l<0||l>4294967295||n(l)!==l)throw new o("`length` must be a positive 32-bit integer");var a=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||!a)&&(t?e(i,"length",l,!0,!0):e(i,"length",l)),i},Mr}function hh(){if(Qi)return Ht;Qi=!0;var s=ki(),e=qt(),t=uh(),r=tr(),o=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||s.call(n,o),l=xi(),a=e("%Math.max%");Ht=function(u){if(typeof u!="function")throw new r("a function is required");var h=i(s,n,arguments);return t(h,1+a(0,u.length-(arguments.length-1)),!0)};var c=function(){return i(s,o,arguments)};return l?l(Ht,"apply",{value:c}):Ht.apply=c,Ht}function dh(){if(Xi)return Rr;Xi=!0;var s=qt(),e=hh(),t=e(s("String.prototype.indexOf"));return Rr=function(r,o){var n=s(r,!!o);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Rr}var Si,Ei,Ai,Ii,Ti,Ci,Oi,Pi,Mi,Ri,Li,Ni,ji,Ui,Bi,Di,kr,Fi,xr,$i,Sr,qi,Er,Hi,Ar,Wi,Ir,zi,Tr,Vi,Cr,Ki,Or,Gi,Pr,Yi,Mr,Ji,Ht,Qi,Rr,Xi,fh=Ge(()=>{le(),ue(),ce(),Si={},Ei=!1,Ai={},Ii=!1,Ti={},Ci=!1,Oi={},Pi=!1,Mi={},Ri=!1,Li={},Ni=!1,ji={},Ui=!1,Bi={},Di=!1,kr={},Fi=!1,xr={},$i=!1,Sr={},qi=!1,Er={},Hi=!1,Ar={},Wi=!1,Ir={},zi=!1,Tr={},Vi=!1,Cr={},Ki=!1,Or={},Gi=!1,Pr={},Yi=!1,Mr={},Ji=!1,Ht={},Qi=!1,Rr={},Xi=!1});function Zi(s){throw new Error("Node.js process "+s+" is not supported by JSPM core outside of Node.js")}function ph(){!Pt||!Mt||(Pt=!1,Mt.length?rt=Mt.concat(rt):rr=-1,rt.length&&Ds())}function Ds(){if(!Pt){var s=setTimeout(ph,0);Pt=!0;for(var e=rt.length;e;){for(Mt=rt,rt=[];++rr<e;)Mt&&Mt[rr].run();rr=-1,e=rt.length}Mt=null,Pt=!1,clearTimeout(s)}}function mh(s){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];rt.push(new Fs(s,e)),rt.length===1&&!Pt&&setTimeout(Ds,0)}function Fs(s,e){this.fun=s,this.array=e}function He(){}function gh(s){Zi("_linkedBinding")}function bh(s){Zi("dlopen")}function yh(){return[]}function vh(){return[]}function wh(s,e){if(!s)throw new Error(e||"assertion error")}function _h(){return!1}function kh(){return bt.now()/1e3}function eo(s){var e=Math.floor((Date.now()-bt.now())*.001),t=bt.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return s&&(r=r-s[0],o=o-s[1],o<0&&(r--,o+=Nr)),[r,o]}function xt(){return ro}function xh(s){return[]}var rt,Pt,Mt,rr,$s,qs,Hs,Ws,zs,Vs,Ks,Gs,Ys,Js,Qs,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,Lr,la,ca,ua,ha,da,fa,pa,ma,ga,ba,ya,va,wa,_a,ka,xa,Sa,Ea,Aa,Ia,Ta,Ca,Oa,Pa,Ma,bt,to,Nr,Ra,La,Na,ja,Ua,Ba,Da,Fa,$a,qa,Ha,ro,Wa=Ge(()=>{le(),ue(),ce(),rt=[],Pt=!1,rr=-1,Fs.prototype.run=function(){this.fun.apply(null,this.array)},$s="browser",qs="x64",Hs="browser",Ws={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},zs=["/usr/bin/node"],Vs=[],Ks="v16.8.0",Gs={},Ys=function(s,e){console.warn((e?e+": ":"")+s)},Js=function(s){Zi("binding")},Qs=function(s){return 0},Xs=function(){return"/"},Zs=function(s){},ea={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},ta=He,ra=[],na={},ia=!1,oa={},sa=He,aa=He,Lr=function(){return{}},la=Lr,ca=Lr,ua=He,ha=He,da=He,fa={},pa={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},ma=He,ga=He,ba=He,ya=He,va=He,wa=He,_a=He,ka=void 0,xa=void 0,Sa=void 0,Ea=He,Aa=2,Ia=1,Ta="/bin/usr/node",Ca=9229,Oa="node",Pa=[],Ma=He,bt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},bt.now===void 0&&(to=Date.now(),bt.timing&&bt.timing.navigationStart&&(to=bt.timing.navigationStart),bt.now=()=>Date.now()-to),Nr=1e9,eo.bigint=function(s){var e=eo(s);return typeof BigInt>"u"?e[0]*Nr+e[1]:BigInt(e[0]*Nr)+BigInt(e[1])},Ra=10,La={},Na=0,ja=xt,Ua=xt,Ba=xt,Da=xt,Fa=xt,$a=He,qa=xt,Ha=xt,ro={version:Ks,versions:Gs,arch:qs,platform:Hs,release:ea,_rawDebug:ta,moduleLoadList:ra,binding:Js,_linkedBinding:gh,_events:La,_eventsCount:Na,_maxListeners:Ra,on:xt,addListener:ja,once:Ua,off:Ba,removeListener:Da,removeAllListeners:Fa,emit:$a,prependListener:qa,prependOnceListener:Ha,listeners:xh,domain:na,_exiting:ia,config:oa,dlopen:bh,uptime:kh,_getActiveRequests:yh,_getActiveHandles:vh,reallyExit:sa,_kill:aa,cpuUsage:Lr,resourceUsage:la,memoryUsage:ca,kill:ua,exit:ha,openStdin:da,allowedNodeEnvironmentFlags:fa,assert:wh,features:pa,_fatalExceptions:ma,setUncaughtExceptionCaptureCallback:ga,hasUncaughtExceptionCaptureCallback:_h,emitWarning:Ys,nextTick:mh,_tickCallback:ba,_debugProcess:ya,_debugEnd:va,_startProfilerIdleNotifier:wa,_stopProfilerIdleNotifier:_a,stdout:ka,stdin:Sa,stderr:xa,abort:Ea,umask:Qs,chdir:Zs,cwd:Xs,env:Ws,title:$s,argv:zs,execArgv:Vs,pid:Aa,ppid:Ia,execPath:Ta,debugPort:Ca,hrtime:eo,argv0:Oa,_preload_modules:Pa,setSourceMapsEnabled:Ma}});function Sh(){if(no)return jr;no=!0;var s=ro;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 l="",a=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(l.length<2||a!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var g=l.lastIndexOf("/");if(g!==l.length-1){g===-1?(l="",a=0):(l=l.slice(0,g),a=l.length-1-l.lastIndexOf("/")),c=p,u=0;continue}}else if(l.length===2||l.length===1){l="",a=0,c=p,u=0;continue}}i&&(l.length>0?l+="/..":l="..",a=2)}else l.length>0?l+="/"+n.slice(c+1,p):l=n.slice(c+1,p),a=p-c-1;c=p,u=0}else h===46&&u!==-1?++u:u=-1}return l}function r(n,i){var l=i.dir||i.root,a=i.base||(i.name||"")+(i.ext||"");return l?l===i.root?l+a:l+n+a:a}var o={resolve:function(){for(var n="",i=!1,l,a=arguments.length-1;a>=-1&&!i;a--){var c;a>=0?c=arguments[a]:(l===void 0&&(l=s.cwd()),c=l),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,l=n.charCodeAt(n.length-1)===47;return n=t(n,!i),n.length===0&&!i&&(n="."),n.length>0&&l&&(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 l=arguments[i];e(l),l.length>0&&(n===void 0?n=l:n+="/"+l)}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 l=1;l<n.length&&n.charCodeAt(l)===47;++l);for(var a=n.length,c=a-l,u=1;u<i.length&&i.charCodeAt(u)===47;++u);for(var h=i.length,p=h-u,g=c<p?c:p,f=-1,b=0;b<=g;++b){if(b===g){if(p>g){if(i.charCodeAt(u+b)===47)return i.slice(u+b+1);if(b===0)return i.slice(u+b)}else c>g&&(n.charCodeAt(l+b)===47?f=b:b===0&&(f=0));break}var y=n.charCodeAt(l+b),w=i.charCodeAt(u+b);if(y!==w)break;y===47&&(f=b)}var m="";for(b=l+f+1;b<=a;++b)(b===a||n.charCodeAt(b)===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),l=i===47,a=-1,c=!0,u=n.length-1;u>=1;--u)if(i=n.charCodeAt(u),i===47){if(!c){a=u;break}}else c=!1;return a===-1?l?"/":".":l&&a===1?"//":n.slice(0,a)},basename:function(n,i){if(i!==void 0&&typeof i!="string")throw new TypeError('"ext" argument must be a string');e(n);var l=0,a=-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 g=n.charCodeAt(u);if(g===47){if(!c){l=u+1;break}}else p===-1&&(c=!1,p=u+1),h>=0&&(g===i.charCodeAt(h)?--h===-1&&(a=u):(h=-1,a=p))}return l===a?a=p:a===-1&&(a=n.length),n.slice(l,a)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){l=u+1;break}}else a===-1&&(c=!1,a=u+1);return a===-1?"":n.slice(l,a)}},extname:function(n){e(n);for(var i=-1,l=0,a=-1,c=!0,u=0,h=n.length-1;h>=0;--h){var p=n.charCodeAt(h);if(p===47){if(!c){l=h+1;break}continue}a===-1&&(c=!1,a=h+1),p===46?i===-1?i=h:u!==1&&(u=1):i!==-1&&(u=-1)}return i===-1||a===-1||u===0||u===1&&i===a-1&&i===l+1?"":n.slice(i,a)},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 l=n.charCodeAt(0),a=l===47,c;a?(i.root="/",c=1):c=0;for(var u=-1,h=0,p=-1,g=!0,f=n.length-1,b=0;f>=c;--f){if(l=n.charCodeAt(f),l===47){if(!g){h=f+1;break}continue}p===-1&&(g=!1,p=f+1),l===46?u===-1?u=f:b!==1&&(b=1):u!==-1&&(b=-1)}return u===-1||p===-1||b===0||b===1&&u===p-1&&u===h+1?p!==-1&&(h===0&&a?i.base=i.name=n.slice(1,p):i.base=i.name=n.slice(h,p)):(h===0&&a?(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):a&&(i.dir="/"),i},sep:"/",delimiter:":",win32:null,posix:null};return o.posix=o,jr=o,jr}var jr,no,io,Eh=Ge(()=>{le(),ue(),ce(),Wa(),jr={},no=!1,io=Sh()}),za={};Ut(za,{URL:()=>rl,Url:()=>Qa,default:()=>We,fileURLToPath:()=>Ka,format:()=>Xa,parse:()=>tl,pathToFileURL:()=>Ga,resolve:()=>Za,resolveObject:()=>el});function Ah(){if(so)return Ur;so=!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,l=o&&Set.prototype.forEach,a=typeof WeakMap=="function"&&WeakMap.prototype,c=a?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,h=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,g=p?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,b=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 Ee=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof z=="number"){var Ae=z<0?-P(-z):P(z);if(Ae!==z){var Ie=String(Ae),Pe=m.call(ie,Ie.length+1);return _.call(Ie,Ee,"$&_")+"."+_.call(_.call(Pe,/([0-9]{3})/g,"$&_"),/_$/,"")}}return _.call(ie,Ee,"$&_")}var re=Ya,F=re.custom,Z=G(F)?F:null;Ur=function z(ie,Ee,Ae,Ie){var Pe=Ee||{};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 nt=oe(Pe,"customInspect")?Pe.customInspect:!0;if(typeof nt!="boolean"&&nt!=="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 it=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 ze=String(ie);return it?V(ie,ze):ze}if(typeof ie=="bigint"){var ot=String(ie)+"n";return it?V(ie,ot):ot}var Kt=typeof Pe.depth>"u"?5:Pe.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=Kt&&Kt>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var st=X(Pe,Ae);if(typeof Ie>"u")Ie=[];else if(ee(Ie,ie)>=0)return"[Circular]";function Xe(at,Et,jt){if(Et&&(Ie=O.call(Ie),Ie.push(Et)),jt){var lt={depth:Pe.depth};return oe(Pe,"quoteStyle")&&(lt.quoteStyle=Pe.quoteStyle),z(at,lt,Ae+1,Ie)}return z(at,Pe,Ae+1,Ie)}if(typeof ie=="function"&&!we(ie)){var Zr=$(ie),Gt=ke(ie,Xe);return"[Function"+(Zr?": "+Zr:" (anonymous)")+"]"+(Gt.length>0?" { "+I.call(Gt,", ")+" }":"")}if(G(ie)){var or=D?_.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):q.call(ie);return typeof ie=="object"&&!D?d(or):or}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,Xe);return st&&!B(xe)?"["+he(xe,st)+"]":"[ "+I.call(xe,", ")+" ]"}if(K(ie)){var Se=ke(ie,Xe);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(S.call("[cause]: "+Xe(ie.cause),Se),", ")+" }":Se.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Se,", ")+" }"}if(typeof ie=="object"&&nt){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Kt-Ae});if(nt!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(de(ie)){var De=[];return r&&r.call(ie,function(at,Et){De.push(Xe(Et,ie,!0)+" => "+Xe(at,ie))}),A("Map",t.call(ie),De,st)}if(H(ie)){var Ke=[];return l&&l.call(ie,function(at){Ke.push(Xe(at,ie))}),A("Set",i.call(ie),Ke,st)}if(fe(ie))return k("WeakMap");if(me(ie))return k("WeakSet");if(ye(ie))return k("WeakRef");if(ne(ie))return d(Xe(Number(ie)));if(J(ie))return d(Xe(j.call(ie)));if(W(ie))return d(f.call(ie));if(N(ie))return d(Xe(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Br<"u"&&ie===Br)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var et=ke(ie,Xe),sr=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,ar=ie instanceof Object?"":"null prototype",lr=!sr&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):ar?"Object":"",en=sr||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Nt=en+(lr||ar?"["+I.call(S.call([],lr||[],ar||[]),": ")+"] ":"");return et.length===0?Nt+"{}":st?Nt+"{"+he(et,st)+"}":Nt+"{ "+I.call(et,", ")+" }"}return String(ie)};function M(z,ie,Ee){var Ae=(Ee.quoteStyle||ie)==="double"?'"':"'";return Ae+z+Ae}function Q(z){return _.call(String(z),/"/g,"&quot;")}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||Br)};function oe(z,ie){return ge.call(z,ie)}function R(z){return b.call(z)}function $(z){if(z.name)return z.name;var ie=w.call(y.call(z),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(z,ie){if(z.indexOf)return z.indexOf(ie);for(var Ee=0,Ae=z.length;Ee<Ae;Ee++)if(z[Ee]===ie)return Ee;return-1}function 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(!g||!z||typeof z!="object")return!1;try{return g.call(z),!0}catch{}return!1}function H(z){if(!i||!z||typeof z!="object")return!1;try{i.call(z);try{t.call(z)}catch{return!0}return z instanceof Set}catch{}return!1}function me(z){if(!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 Ee=z.length-ie.maxStringLength,Ae="... "+Ee+" more character"+(Ee>1?"s":"");return se(m.call(z,0,ie.maxStringLength),ie)+Ae}var Ie=_.call(_.call(z,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Ce);return M(Ie,"single",ie)}function Ce(z){var ie=z.charCodeAt(0),Ee={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ee?"\\"+Ee:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function d(z){return"Object("+z+")"}function k(z){return z+" { ? }"}function A(z,ie,Ee,Ae){var Ie=Ae?he(Ee,Ae):I.call(Ee,", ");return z+" ("+ie+") {"+Ie+"}"}function B(z){for(var ie=0;ie<z.length;ie++)if(ee(z[ie],`
4
+ `)>=0)return!1;return!0}function X(z,ie){var Ee;if(z.indent===" ")Ee=" ";else if(typeof z.indent=="number"&&z.indent>0)Ee=I.call(Array(z.indent+1)," ");else return null;return{base:Ee,prev:I.call(Array(ie+1),Ee)}}function he(z,ie){if(z.length===0)return"";var Ee=`
5
5
  `+ie.prev+ie.base;return Ee+I.call(z,","+Ee)+`
6
- `+ie.prev}function ke(z,ie){var Ee=ye(z),Ae=[];if(Ee){Ae.length=z.length;for(var Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],z):""}var Pe=typeof T=="function"?T(z):[],nt;if(D){nt={};for(var it=0;it<Pe.length;it++)nt["$"+Pe[it]]=Pe[it]}for(var ze in z)oe(z,ze)&&(Ee&&String(Number(ze))===ze&&ze<z.length||D&&nt["$"+ze]instanceof Symbol||(E.call(/[^\w$]/,ze)?Ae.push(ie(ze,z)+": "+ie(z[ze],z)):Ae.push(ze+": "+ie(z[ze],z))));if(typeof T=="function")for(var ot=0;ot<Pe.length;ot++)ae.call(z,Pe[ot])&&Ae.push("["+ie(Pe[ot])+"]: "+ie(z[Pe[ot]],z));return Ae}return Ur}function Td(){if(so)return Dr;so=!0;var s=qt(),e=fd(),t=Id(),r=tr(),i=s("%WeakMap%",!0),n=s("%Map%",!0),o=e("WeakMap.prototype.get",!0),l=e("WeakMap.prototype.set",!0),a=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(b,w){for(var m=b,_;(_=m.next)!==null;m=_)if(_.key===w)return m.next=_.next,_.next=b.next,b.next=_,_},g=function(b,w){var m=p(b,w);return m&&m.value},f=function(b,w,m){var _=p(b,w);_?_.value=m:b.next={key:w,next:b.next,value:m}},y=function(b,w){return!!p(b,w)};return Dr=function(){var b,w,m,_={assert:function(x){if(!_.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(i&&x&&(typeof x=="object"||typeof x=="function")){if(b)return o(b,x)}else if(n){if(w)return c(w,x)}else if(m)return g(m,x)},has:function(x){if(i&&x&&(typeof x=="object"||typeof x=="function")){if(b)return a(b,x)}else if(n){if(w)return d(w,x)}else if(m)return y(m,x);return!1},set:function(x,v){i&&x&&(typeof x=="object"||typeof x=="function")?(b||(b=new i),l(b,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),f(m,x,v))}};return _},Dr}function io(){if(ao)return Fr;ao=!0;var s=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Fr={default:t.RFC3986,formatters:{RFC1738:function(r){return s.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Fr}function za(){if(lo)return $r;lo=!0;var s=io(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var b=[],w=0;w<256;++w)b.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return b})(),i=function(b){for(;b.length>1;){var w=b.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(b,w){for(var m=w&&w.plainObjects?Object.create(null):{},_=0;_<b.length;++_)typeof b[_]<"u"&&(m[_]=b[_]);return m},o=function b(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]=b(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]=b(v[E],S,_):v[E]=S,v},x)},l=function(b,w){return Object.keys(w).reduce(function(m,_){return m[_]=w[_],m},b)},a=function(b,w,m){var _=b.replace(/\+/g," ");if(m==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},c=1024,u=function(b,w,m,_,x){if(b.length===0)return b;var v=b;if(typeof b=="symbol"?v=Symbol.prototype.toString.call(b):typeof b!="string"&&(v=String(b)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var E="",S=0;S<v.length;S+=c){for(var I=v.length>=c?v.slice(S,S+c):v,P=[],O=0;O<I.length;++O){var j=I.charCodeAt(O);if(j===45||j===46||j===95||j===126||j>=48&&j<=57||j>=65&&j<=90||j>=97&&j<=122||x===s.RFC1738&&(j===40||j===41)){P[P.length]=I.charAt(O);continue}if(j<128){P[P.length]=r[j];continue}if(j<2048){P[P.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){P[P.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}O+=1,j=65536+((j&1023)<<10|I.charCodeAt(O)&1023),P[P.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}E+=P.join("")}return E},d=function(b){for(var w=[{obj:{o:b},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],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(w.push({obj:v,prop:I}),m.push(P))}return i(w),b},p=function(b){return Object.prototype.toString.call(b)==="[object RegExp]"},g=function(b){return!b||typeof b!="object"?!1:!!(b.constructor&&b.constructor.isBuffer&&b.constructor.isBuffer(b))},f=function(b,w){return[].concat(b,w)},y=function(b,w){if(t(b)){for(var m=[],_=0;_<b.length;_+=1)m.push(w(b[_]));return m}return w(b)};return $r={arrayToObject:n,assign:l,combine:f,compact:d,decode:a,encode:u,isBuffer:g,isRegExp:p,maybeMap:y,merge:o},$r}function Cd(){if(co)return qr;co=!0;var s=Td(),e=za(),t=io(),r=Object.prototype.hasOwnProperty,i={brackets:function(y){return y+"[]"},comma:"comma",indices:function(y,b){return y+"["+b+"]"},repeat:function(y){return y}},n=Array.isArray,o=Array.prototype.push,l=function(y,b){o.apply(y,n(b)?b:[b])},a=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(y){return a.call(y)},skipNulls:!1,strictNullHandling:!1},d=function(y){return typeof y=="string"||typeof y=="number"||typeof y=="boolean"||typeof y=="symbol"||typeof y=="bigint"},p={},g=function y(b,w,m,_,x,v,E,S,I,P,O,j,T,q,D,U,ae,Y){for(var V=b,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var M=re.get(b);if(F+=1,typeof M<"u"){if(M===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=0)}if(typeof P=="function"?V=P(w,V):V instanceof Date?V=T(V):m==="comma"&&n(V)&&(V=e.maybeMap(V,function(R){return R instanceof Date?T(R):R})),V===null){if(v)return I&&!U?I(w,u.encoder,ae,"key",q):w;V=""}if(d(V)||e.isBuffer(V)){if(I){var Q=U?w:I(w,u.encoder,ae,"key",q);return[D(Q)+"="+D(I(V,u.encoder,ae,"value",q))]}return[D(w)+"="+D(String(V))]}var ye=[];if(typeof V>"u")return ye;var te;if(m==="comma"&&n(V))U&&I&&(V=e.maybeMap(V,I)),te=[{value:V.length>0?V.join(",")||null:void 0}];else if(n(P))te=P;else{var we=Object.keys(V);te=O?we.sort(O):we}var G=S?w.replace(/\./g,"%2E"):w,N=_&&n(V)&&V.length===1?G+"[]":G;if(x&&n(V)&&V.length===0)return N+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],K=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&K===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(b,F);var oe=s();oe.set(p,Y),l(ye,y(K,ge,m,_,x,v,E,S,m==="comma"&&U&&n(V)?null:I,P,O,j,T,q,D,U,ae,oe))}}return ye},f=function(y){if(!y)return u;if(typeof y.allowEmptyArrays<"u"&&typeof y.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof y.encodeDotInKeys<"u"&&typeof y.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(y.encoder!==null&&typeof y.encoder<"u"&&typeof y.encoder!="function")throw new TypeError("Encoder has to be a function.");var b=y.charset||u.charset;if(typeof y.charset<"u"&&y.charset!=="utf-8"&&y.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 y.format<"u"){if(!r.call(t.formatters,y.format))throw new TypeError("Unknown format option provided.");w=y.format}var m=t.formatters[w],_=u.filter;(typeof y.filter=="function"||n(y.filter))&&(_=y.filter);var x;if(y.arrayFormat in i?x=y.arrayFormat:"indices"in y?x=y.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in y&&typeof y.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof y.allowDots>"u"?y.encodeDotInKeys===!0?!0:u.allowDots:!!y.allowDots;return{addQueryPrefix:typeof y.addQueryPrefix=="boolean"?y.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof y.allowEmptyArrays=="boolean"?!!y.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:b,charsetSentinel:typeof y.charsetSentinel=="boolean"?y.charsetSentinel:u.charsetSentinel,commaRoundTrip:y.commaRoundTrip,delimiter:typeof y.delimiter>"u"?u.delimiter:y.delimiter,encode:typeof y.encode=="boolean"?y.encode:u.encode,encodeDotInKeys:typeof y.encodeDotInKeys=="boolean"?y.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof y.encoder=="function"?y.encoder:u.encoder,encodeValuesOnly:typeof y.encodeValuesOnly=="boolean"?y.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:w,formatter:m,serializeDate:typeof y.serializeDate=="function"?y.serializeDate:u.serializeDate,skipNulls:typeof y.skipNulls=="boolean"?y.skipNulls:u.skipNulls,sort:typeof y.sort=="function"?y.sort:null,strictNullHandling:typeof y.strictNullHandling=="boolean"?y.strictNullHandling:u.strictNullHandling}};return qr=function(y,b){var w=y,m=f(b),_,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=i[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;_||(_=Object.keys(w)),m.sort&&_.sort(m.sort);for(var I=s(),P=0;P<_.length;++P){var O=_[P];m.skipNulls&&w[O]===null||l(v,g(w[O],O,E,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var j=v.join(m.delimiter),T=m.addQueryPrefix===!0?"?":"";return m.charsetSentinel&&(m.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),j.length>0?T+j:""},qr}function Pd(){if(uo)return Hr;uo=!0;var s=za(),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},i=function(p){return p.replace(/&#(\d+);/g,function(g,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,g){return p&&typeof p=="string"&&g.comma&&p.indexOf(",")>-1?p.split(","):p},o="utf8=%26%2310003%3B",l="utf8=%E2%9C%93",a=function(p,g){var f={__proto__:null},y=g.ignoreQueryPrefix?p.replace(/^\?/,""):p;y=y.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var b=g.parameterLimit===1/0?void 0:g.parameterLimit,w=y.split(g.delimiter,b),m=-1,_,x=g.charset;if(g.charsetSentinel)for(_=0;_<w.length;++_)w[_].indexOf("utf8=")===0&&(w[_]===l?x="utf-8":w[_]===o&&(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,P;S===-1?(I=g.decoder(v,r.decoder,x,"key"),P=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,S),r.decoder,x,"key"),P=s.maybeMap(n(v.slice(S+1),g),function(j){return g.decoder(j,r.decoder,x,"value")})),P&&g.interpretNumericEntities&&x==="iso-8859-1"&&(P=i(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var O=e.call(f,I);O&&g.duplicates==="combine"?f[I]=s.combine(f[I],P):(!O||g.duplicates==="last")&&(f[I]=P)}return f},c=function(p,g,f,y){for(var b=y?g:n(g,f),w=p.length-1;w>=0;--w){var m,_=p[w];if(_==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(b===""||f.strictNullHandling&&b===null)?[]:[].concat(b);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:b}:!isNaN(E)&&_!==v&&String(E)===v&&E>=0&&f.parseArrays&&E<=f.arrayLimit?(m=[],m[E]=b):v!=="__proto__"&&(m[v]=b)}b=m}return b},u=function(p,g,f,y){if(p){var b=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,_=f.depth>0&&w.exec(b),x=_?b.slice(0,_.index):b,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(b))!==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("["+b.slice(_.index)+"]")}return c(v,g,f,y)}},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 g=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 y=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:y,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:g,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: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 Hr=function(p,g){var f=d(g);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var y=typeof p=="string"?a(p,f):p,b=f.plainObjects?Object.create(null):{},w=Object.keys(y),m=0;m<w.length;++m){var _=w[m],x=u(_,y[_],f,typeof p=="string");b=s.merge(b,x,f)}return f.allowSparse===!0?b:s.compact(b)},Hr}function Od(){if(ho)return Wr;ho=!0;var s=Cd(),e=Pd(),t=io();return Wr={formats:t,parse:e,stringify:s},Wr}function Md(){if(fo)return St;fo=!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]*$/,i=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
7
- `," "],o=["{","}","|","\\","^","`"].concat(n),l=["'"].concat(o),a=["%","/","?",";","#"].concat(l),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=Od();function w(v,E,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,E,S),I}e.prototype.parse=function(v,E,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),P=I!==-1&&I<v.indexOf("#")?"?":"#",O=v.split(P),j=/\\/g;O[0]=O[0].replace(j,"/"),v=O.join(P);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var q=i.exec(T);if(q)return this.path=T,this.href=T,this.pathname=q[1],q[2]?(this.search=q[2],E?this.query=b.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var U=D.toLowerCase();this.protocol=U,T=T.substr(D.length)}if(S||D||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(D&&f[D])&&(T=T.substr(2),this.slashes=!0)}if(!f[D]&&(ae||D&&!y[D])){for(var Y=-1,V=0;V<c.length;V++){var re=T.indexOf(c[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var F,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(F=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(F)),Y=-1;for(var V=0;V<a.length;V++){var re=T.indexOf(a[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var Q=this.hostname.split(/\./),V=0,ye=Q.length;V<ye;V++){var te=Q[V];if(te&&!te.match(d)){for(var we="",G=0,N=te.length;G<N;G++)te.charCodeAt(G)>127?we+="x":we+=te[G];if(!we.match(d)){var ne=Q.slice(0,V),W=Q.slice(V+1),K=te.match(p);K&&(ne.push(K[1]),W.unshift(K[2])),W.length&&(T="/"+W.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=s.toASCII(this.hostname));var J=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+J,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!g[U])for(var V=0,ye=l.length;V<ye;V++){var oe=l[V];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var $=T.indexOf("#");$!==-1&&(this.hash=T.substr($),T=T.slice(0,$));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),E&&(this.query=b.parse(this.query)),T=T.slice(0,ee)):E&&(this.search="",this.query={}),T&&(this.pathname=T),y[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var J=this.pathname||"",he=this.search||"";this.path=J+he}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=w(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var E=this.protocol||"",S=this.pathname||"",I=this.hash||"",P=!1,O="";this.host?P=v+this.host:this.hostname&&(P=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(P+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(O=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var j=this.search||O&&"?"+O||"";return E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||y[E])&&P!==!1?(P="//"+(P||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):P||(P=""),I&&I.charAt(0)!=="#"&&(I="#"+I),j&&j.charAt(0)!=="?"&&(j="?"+j),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),j=j.replace("#","%23"),E+P+S+j+I};function _(v,E){return w(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function x(v,E){return v?w(v,!1,!0).resolveObject(E):E}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var E=new e;E.parse(v,!1,!0),v=E}for(var S=new e,I=Object.keys(this),P=0;P<I.length;P++){var O=I[P];S[O]=this[O]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var j=Object.keys(v),T=0;T<j.length;T++){var q=j[T];q!=="protocol"&&(S[q]=v[q])}return y[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(!y[v.protocol]){for(var D=Object.keys(v),U=0;U<D.length;U++){var ae=D[U];S[ae]=v[ae]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!f[v.protocol]){for(var ye=(v.pathname||"").split("/");ye.length&&!(v.host=ye.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),ye[0]!==""&&ye.unshift(""),ye.length<2&&ye.unshift(""),S.pathname=ye.join("/")}else S.pathname=v.pathname;if(S.search=v.search,S.query=v.query,S.host=v.host||"",S.auth=v.auth,S.hostname=v.hostname||v.host,S.port=v.port,S.pathname||S.search){var Y=S.pathname||"",V=S.search||"";S.path=Y+V}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||re||S.host&&v.pathname,M=Z,Q=S.pathname&&S.pathname.split("/")||[],ye=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!y[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&&(ye[0]===""?ye[0]=v.host:ye.unshift(v.host)),v.host=null),Z=Z&&(ye[0]===""||Q[0]==="")),F)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=ye;else if(ye.length)Q||(Q=[]),Q.pop(),Q=Q.concat(ye),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 G=Q.slice(-1)[0],N=(S.host||v.host||Q.length>1)&&(G==="."||G==="..")||G==="",ne=0,W=Q.length;W>=0;W--)G=Q[W],G==="."?Q.splice(W,1):G===".."?(Q.splice(W,1),ne++):ne&&(Q.splice(W,1),ne--);if(!Z&&!M)for(;ne--;ne)Q.unshift("..");Z&&Q[0]!==""&&(!Q[0]||Q[0].charAt(0)!=="/")&&Q.unshift(""),N&&Q.join("/").substr(-1)!=="/"&&Q.push("");var K=Q[0]===""||Q[0]&&Q[0].charAt(0)==="/";if(te){S.hostname=K?"":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&&!K&&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 Va(s){if(typeof s=="string")s=new URL(s);else if(!(s instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(s.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return zr?Rd(s):Ld(s)}function Rd(s){let e=s.hostname,t=s.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let i=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&i===102||t[r+1]==="5"&&i===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(sl,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,i=t[2];if(r<il||r>ol||i!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Ld(s){if(s.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=s.pathname;for(let t=0;t<e.length;t++)if(e[t]==="%"){let r=e.codePointAt(t+2)||32;if(e[t+1]==="2"&&r===102)throw new Deno.errors.InvalidData("must not include encoded / characters")}return decodeURIComponent(e)}function Ga(s){let e=no.resolve(s),t=s.charCodeAt(s.length-1);(t===nl||zr&&t===rl)&&e[e.length-1]!==no.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(al,"%25")),!zr&&e.includes("\\")&&(e=e.replace(ll,"%5C")),e.includes(`
8
- `)&&(e=e.replace(cl,"%0A")),e.includes("\r")&&(e=e.replace(ul,"%0D")),e.includes(" ")&&(e=e.replace(dl,"%09")),r.pathname=e,r}var Ka,Ur,oo,Br,Dr,so,Fr,ao,$r,lo,qr,co,Hr,uo,Wr,ho,St,fo,We,Ya,Ja,Qa,Xa,Za,el,tl,rl,nl,il,ol,zr,sl,al,ll,cl,ul,dl,Nd=Ke(()=>{le(),ue(),ce(),Xu(),pd(),Ad(),Ha(),Ka=Object.freeze(Object.create(null)),Ur={},oo=!1,Br=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Dr={},so=!1,Fr={},ao=!1,$r={},lo=!1,qr={},co=!1,Hr={},uo=!1,Wr={},ho=!1,St={},fo=!1,We=Md(),We.parse,We.resolve,We.resolveObject,We.format,We.Url,Ya=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,We.URL=typeof URL<"u"?URL:null,We.pathToFileURL=Ga,We.fileURLToPath=Va,Ja=We.Url,Qa=We.format,Xa=We.resolve,Za=We.resolveObject,el=We.parse,tl=We.URL,rl=92,nl=47,il=97,ol=122,zr=Ya==="win32",sl=/\//g,al=/%/g,ll=/\\/g,cl=/\n/g,ul=/\r/g,dl=/\t/g}),jd=pe((s,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),po=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=Pt(),t=($e(),Re(Fe));function r(n,o){let l=new Array(n.length);for(let a=0;a<n.length;a++)typeof n[a].chunk=="string"?l[a]=t.Buffer.from(n[a].chunk,"utf8"):l[a]=n[a].chunk;this._write(t.Buffer.concat(l),"binary",o)}var i=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,o,l){super({objectMode:!0}),this.proxy=o,this.socket=l,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",a=>{!this.destroyed&&this.readable&&this.push(a)})}_read(n){this.proxy.read(n)}_write(n,o,l){this.isSocketOpen?this.writeToProxy(n,o,l):this.writeQueue.push({chunk:n,encoding:o,cb:l})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,o){this.writeQueue=[],this.proxy.destroy(),o(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,o,l){this.proxy.write(n,o)===!1?this.proxy.once("drain",l):l()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:o,cb:l}=this.writeQueue.shift();this.writeToProxy(n,o,l)}}};s.BufferedDuplex=i}),Vr=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=($e(),Re(Fe)),r=e(jd()),i=e(pt()),n=Pt(),o=e(wr()),l=po(),a=(0,i.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={}),!o.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 g(w,m,_){a("createWebSocket"),a(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";a(`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 y=(w,m)=>{a("streamBuilder");let _=d(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=g(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=y;var b=(w,m)=>{a("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=f(w,m),I=O(m,U,ae);m.objectMode||(I._writev=l.writev.bind(I)),I.on("close",()=>{S.close()});let P=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=I,_.socket=S):(_=new l.BufferedDuplex(m,I,S),P?S.addEventListener("open",j):S.onopen=j),P?(S.addEventListener("close",T),S.addEventListener("error",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function O(Y,V,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function j(){a("WebSocket onOpen"),_ instanceof l.BufferedDuplex&&_.socketReady()}function T(Y){a("WebSocket onClose",Y),_.end(),_.destroy()}function q(Y){a("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(F){return re(F)}re()}function ae(Y){S.close(),Y()}return _};s.browserStreamBuilder=b}),mo={};Ut(mo,{Server:()=>Ne,Socket:()=>Ne,Stream:()=>Ne,_createServerHandle:()=>Ne,_normalizeArgs:()=>Ne,_setSimultaneousAccepts:()=>Ne,connect:()=>Ne,createConnection:()=>Ne,createServer:()=>Ne,default:()=>hl,isIP:()=>Ne,isIPv4:()=>Ne,isIPv6:()=>Ne});function Ne(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var hl,fl=Ke(()=>{le(),ue(),ce(),hl={_createServerHandle:Ne,_normalizeArgs:Ne,_setSimultaneousAccepts:Ne,connect:Ne,createConnection:Ne,createServer:Ne,isIP:Ne,isIPv4:Ne,isIPv6:Ne,Server:Ne,Socket:Ne,Stream:Ne}}),pl=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),ml=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((fl(),Re(mo))),r=e(pt()),i=e(pl()),n=(0,r.default)("mqttjs:tcp"),o=(l,a)=>{if(a.port=a.port||1883,a.hostname=a.hostname||a.host||"localhost",a.socksProxy)return(0,i.default)(a.hostname,a.port,a.socksProxy,{timeout:a.socksTimeout});let{port:c,path:u}=a,d=a.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};s.default=o}),gl={};Ut(gl,{default:()=>yl});var yl,Ud=Ke(()=>{le(),ue(),ce(),yl={}}),bl=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(s,"__esModule",{value:!0});var t=(Ud(),Re(gl)),r=e((fl(),Re(mo))),i=e(pt()),n=e(pl()),o=(0,i.default)("mqttjs:tls");function l(c){let{host:u,port:d,socksProxy:p,...g}=c;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:f})}return(0,t.connect)(c)}var a=(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,o("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=l(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",p),d};s.default=a}),vl=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Re(Fe)),t=Pt(),r=po(),i,n,o;function l(){let p=new t.Transform;return p._write=(g,f,y)=>{i.send({data:g.buffer,success(){y()},fail(b){y(new Error(b))}})},p._flush=g=>{i.close({success(){g()}})},p}function a(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,g){let f=p.protocol==="wxs"?"wss":"ws",y=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(y=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(y=p.transformWsUrl(y,p,g)),y}function u(){i.onOpen(()=>{o.socketReady()}),i.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),i.onClose(()=>{o.emit("close"),o.end(),o.destroy()}),i.onError(p=>{let g=new Error(p.errMsg);o.destroy(g)})}var d=(p,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let f=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";a(g);let y=c(g,p);i=wx.connectSocket({url:y,protocols:[f]}),n=l(),o=new r.BufferedDuplex(g,n,i),o._destroy=(w,m)=>{i.close({success(){m&&m(w)}})};let b=o.destroy;return o.destroy=(w,m)=>(o.destroy=b,setTimeout(()=>{i.close({fail(){o._destroy(w,m)}})},0),o),u(),o};s.default=d}),wl=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Re(Fe)),t=Pt(),r=po(),i,n,o,l=!1;function a(){let g=new t.Transform;return g._write=(f,y,b)=>{i.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},g._flush=f=>{i.closeSocket({success(){f()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,f){let y=g.protocol==="alis"?"wss":"ws",b=`${y}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(b=`${y}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(b=g.transformWsUrl(b,g,f)),b}function d(){l||(l=!0,i.onSocketOpen(()=>{o.socketReady()}),i.onSocketMessage(g=>{if(typeof g.data=="string"){let f=e.Buffer.from(g.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(g.data)}}),i.onSocketClose(()=>{o.end(),o.destroy()}),i.onSocketError(g=>{o.destroy(g)}))}var p=(g,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let y=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let b=u(f,g);return i=f.my,i.connectSocket({url:b,protocols:y}),n=a(),o=new r.BufferedDuplex(f,n,i),d(),o};s.default=p}),Bd=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(s,"__esModule",{value:!0}),s.connectAsync=u;var t=e(pt()),r=e((Nd(),Re(Wa))),i=e(vi()),n=e(wr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var o=(0,t.default)("mqttjs"),l=null;function a(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,g,f]=p;d.username=g,d.password=f}else d.username=d.auth}function c(d,p){if(o("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let y=r.default.parse(d,!0),b={};if(y.port!=null&&(b.port=Number(y.port)),b.host=y.hostname,b.query=y.query,b.auth=y.auth,b.protocol=y.protocol,b.path=y.path,p={...b,...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,a(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 Le<"u"&&(p.socksProxy=Le.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(l||(l={},!n.default&&!p.forceNativeWebSocket?(l.ws=Vr().streamBuilder,l.wss=Vr().streamBuilder,l.mqtt=ml().default,l.tcp=ml().default,l.ssl=bl().default,l.tls=l.ssl,l.mqtts=bl().default):(l.ws=Vr().browserStreamBuilder,l.wss=Vr().browserStreamBuilder,l.wx=vl().default,l.wxs=vl().default,l.ali=wl().default,l.alis=wl().default)),!l[p.protocol]){let y=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,w)=>y&&w%2===0?!1:typeof l[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(y){return p.servers&&((!y._reconnectCount||y._reconnectCount===p.servers.length)&&(y._reconnectCount=0),p.host=p.servers[y._reconnectCount].host,p.port=p.servers[y._reconnectCount].port,p.protocol=p.servers[y._reconnectCount].protocol?p.servers[y._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,y._reconnectCount++),o("calling streambuilder for",p.protocol),l[p.protocol](y,p)}let f=new i.default(g,p);return f.on("error",()=>{}),f}function u(d,p,g=!0){return new Promise((f,y)=>{let b=c(d,p),w={connect:_=>{m(),f(b)},end:()=>{m(),f(b)},error:_=>{m(),b.end(),y(_)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{b.off(_,w[_])})}Object.keys(w).forEach(_=>{b.on(_,w[_])})})}s.default=c}),_l=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(g,f,y,b){b===void 0&&(b=y);var w=Object.getOwnPropertyDescriptor(f,y);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[y]}}),Object.defineProperty(g,b,w)}:function(g,f,y,b){b===void 0&&(b=y),g[b]=f[y]}),t=s&&s.__setModuleDefault||(Object.create?function(g,f){Object.defineProperty(g,"default",{enumerable:!0,value:f})}:function(g,f){g.default=f}),r=s&&s.__importStar||(function(){var g=function(f){return g=Object.getOwnPropertyNames||function(y){var b=[];for(var w in y)Object.prototype.hasOwnProperty.call(y,w)&&(b[b.length]=w);return b},g(f)};return function(f){if(f&&f.__esModule)return f;var y={};if(f!=null)for(var b=g(f),w=0;w<b.length;w++)b[w]!=="default"&&e(y,f,b[w]);return t(y,f),y}})(),i=s&&s.__exportStar||function(g,f){for(var y in g)y!=="default"&&!Object.prototype.hasOwnProperty.call(f,y)&&e(f,g,y)},n=s&&s.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=s.KeepaliveManager=s.UniqueMessageIdProvider=s.DefaultMessageIdProvider=s.Store=s.MqttClient=s.connectAsync=s.connect=s.Client=void 0;var o=n(vi());s.MqttClient=o.default;var l=n(Ts());s.DefaultMessageIdProvider=l.default;var a=n(Ju());s.UniqueMessageIdProvider=a.default;var c=n(_s());s.Store=c.default;var u=r(Bd());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Ns());s.KeepaliveManager=d.default,s.Client=o.default,i(vi(),s),i($t(),s),i(ws(),s);var p=br();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Dd=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(o,l,a,c){c===void 0&&(c=a);var u=Object.getOwnPropertyDescriptor(l,a);(!u||("get"in u?!l.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return l[a]}}),Object.defineProperty(o,c,u)}:function(o,l,a,c){c===void 0&&(c=a),o[c]=l[a]}),t=s&&s.__setModuleDefault||(Object.create?function(o,l){Object.defineProperty(o,"default",{enumerable:!0,value:l})}:function(o,l){o.default=l}),r=s&&s.__importStar||(function(){var o=function(l){return o=Object.getOwnPropertyNames||function(a){var c=[];for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(c[c.length]=u);return c},o(l)};return function(l){if(l&&l.__esModule)return l;var a={};if(l!=null)for(var c=o(l),u=0;u<c.length;u++)c[u]!=="default"&&e(a,l,c[u]);return t(a,l),a}})(),i=s&&s.__exportStar||function(o,l){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(l,a)&&e(l,o,a)};Object.defineProperty(s,"__esModule",{value:!0});var n=r(_l());s.default=n,i(_l(),s)});const Fd=Dd();const $d={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},qd=300,Hd={templateId:"7",type:"link",isDeepLink:!0},Wd={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class kl{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={...$d,...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,i={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&&(i.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,o)=>{let l=!1;const a=d=>{l||(l=!0,clearTimeout(u),d())},c=(d,p)=>{l||(this.debugLog("CONNECT_FAIL",{reason:d,message:p?.message}),a(()=>o(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Fd.connect(this.config.mqttEndpoint,i),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),l||a(()=>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),!l){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),l||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",{}),l||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[i,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[i]=`${n.slice(0,200)}…(${n.length})`:r[i]=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 i=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,i)}publishFileMessage(e,t){if(!this.client)return;const r={...Hd,...this.config.fileTemplate??{},...zd(t)},i={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??{}},o=this.buildOutgoingEnvelope(e,{text:JSON.stringify(i),type:"html",attributes:n,metadata:i.metadata});this.publishEnvelope(e,o)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=qd){if(!this.client)return;const i=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(i,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 i=[...this.subscribedTopics];this.subscribedTopics.clear(),i.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 i=null;try{i=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!i)return;this.debugLog("RECV",{topic:e,sender:i.sender,type:i.type,contentType:i.metadata?.contentType,templateId:i.metadata?.templateId,messageId:i.message_id,text:typeof i.text=="string"?i.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof i.status=="number"?i.status:Number(i.status??0),p={conversationId:c,messageId:u,status:d,raw:i};this.statusUpdateHandlers.forEach(g=>g(p)),this.messageHandlers.forEach(g=>g(i,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const o=e.match(this.inboundRegex),l=o?.groups?.conversationId,a={topic:e,conversationId:l,messageId:typeof i.message_id=="string"?i.message_id:void 0,kind:o?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(i,a))}buildOutgoingEnvelope(e,t){const r={...Wd,...this.config.messageDefaults??{}},i=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),o={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:i,senderFullname:i,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:o}}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,(i,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(i,n)=>{const o={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const l=o[n];return l?l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function zd(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function xl(s,e){return(s.sender??"").toString()===e}function Sl(s,e){const t=(s.sender??"").toString(),r=e.systemSenders??["metadata","system"],i=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(i)?"assistant":r.includes(t)?"system":"agent":"system"}function go(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 i=JSON.parse(s.text);typeof i.message=="string"&&(e.innerMessage=i.message);const n=i.metadata;n&&typeof n=="object"&&(typeof n.contentType=="string"&&(e.contentType=n.contentType),typeof n.templateId=="string"&&(e.templateId=n.templateId),n.payload!==void 0&&(e.payload=n.payload))}catch{}const r=s.attributes;if(r&&typeof r=="object"){const i=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&i&&typeof i.contentType=="string"&&(e.contentType=i.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&i&&typeof i.templateId=="string"&&(e.templateId=i.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&i&&i.payload!==void 0&&(e.payload=i.payload),e.payload===void 0&&i&&i.template!==void 0&&(e.payload=i.template)}return e}function El(s){const e=go(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 i=r[0],n=i.action,o=n&&typeof n.url=="string"?n.url:void 0,l=typeof i.description=="string"?i.description:void 0,a=s.attributes,c=a&&typeof a.cloudFileId=="string"?a.cloudFileId:void 0;return!o&&!l?null:{fileName:l,fileUrl:o,cloudFileId:c,templateId:e.templateId}}function Al(s,e,t){const r=Sl(s,t),i=go(s),n=El(s);let o="";i.innerMessage?o=i.innerMessage:typeof s.text=="string"&&(s.text.trim().startsWith("{")?i.contentType!=="300"&&(o=s.text):o=s.text);const l=typeof s.message_id=="string"?s.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,a=typeof s.timestamp=="number"?new Date(s.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof s.status=="number"?Vd(s.status):"delivered",d={id:l,externalId:l,conversationId:e,role:c,content:o,createdAt:a,status:u,metadata:{sender:s.sender,sender_fullname:s.sender_fullname??s.senderFullname,app_id:s.app_id,attributes:s.attributes}};return i.contentType&&(d.template={contentType:i.contentType,templateId:i.templateId,payload:i.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:i}}function Vd(s){return s<0?"error":s>=250?"read":s>=150?"delivered":"sent"}class Il extends ur{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 Do(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Fo,this.conversationManager=new zo(e.conversationId),this.usesAikaara()&&(this.connection=new Bo(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 kl({...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 i=r?"connected":"disconnected";this.emit("connection:state",i),this.config.onConnectionStateChange?.(i)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,i)=>this.handleTiledeskMessage(r,i))),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),i=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;i&&(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(a){return this.config.onError?.(a instanceof Error?a:new Error(String(a))),"unknown"}if(!r.length)return"empty";const i=r.map(a=>Al(a,e,{userId:t})).sort((a,c)=>new Date(a.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=i.map(a=>a.message),o=this.messageStore.messages,l=[...n,...o.filter(a=>!n.some(c=>c.externalId&&c.externalId===a.externalId))];this.messageStore.setMessages(l);for(const{message:a,template:c}of i){if(this.config.onMessage)try{this.config.onMessage(a)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:a.id,conversationId:e,role:a.role==="tool"?"system":a.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 i=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",i),this.config.onMessage?.(i);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 i=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:i.fileName,fileUrl:i.url,cloudFileId:i.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 i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(i,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 i=t.conversationId??r;if(!i)return;const n=this.config.tiledeskIdentity?.userId??"",{message:o,template:l}=Al(e,i,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&o.role==="assistant")return;if(xl(e,n)){const u=this.messageStore.reconcileOptimistic(o);if(u){this.emit("message:updated",u);return}}const{message:a,deduped:c}=this.messageStore.upsertRemoteMessage(o);if(c)this.emit("message:updated",a);else{this.emit("message:received",a),this.config.onMessage?.(a);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:a.role,hasAttachments:Array.isArray(a.attachments)&&a.attachments.length>0,templateId:a.template?.templateId,messageId:a.id,conversationId:a.conversationId}}))}catch{}}if(l.contentType){const u={messageId:a.id,conversationId:i,role:o.role==="tool"?"system":o.role,contentType:l.contentType,templateId:l.templateId,payload:l.payload,innerMessage:l.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||"",i=e.content||"";i?this.messageStore.updateStreaming(i):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,i=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),i&&(this.emit("stream:end",{messageId:i.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",i),this.config.onMessage?.(i));break}case"message_queued":{const r=this.messageStore.messages.findLast(i=>i.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class Gd extends ur{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const Tl={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 Kd(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function Yd(s,e,t){const r=Kd(s.name||"");if(r&&e&&e[r])return e[r];const i=s.type;return i&&i.trim().length>0?i:r&&Tl[r]?Tl[r]:t}function yo(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Jd(s,e){const t=e.split(".");let r=s;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return"";return typeof r=="string"?r:""}function Cl(s){const e=s.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const i=t.name||`upload-${Date.now()}`,n=Yd(t,s.contentTypeMap,s.contentTypeFallback??"application/octet-stream"),o={fileName:i,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},l=s.authHeader?await s.authHeader():void 0,a={accept:"application/json",...s.extraHeaders??{},...l?{authorization:l}:{}};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=yo(c,o),d=await fetch(u,{method:s.signMethod??"GET",headers:a});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const p=await d.json().catch(()=>({})),g=Jd(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const f=s.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,s.s3HostRewrite):g,y=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!y.ok){const w=await y.text().catch(()=>"");throw new Error(`S3 PUT failed: ${y.status} ${w.slice(0,200)}`)}if(s.registerEndpoint){const w=JSON.parse(yo(JSON.stringify(s.registerBody??{}),o)),m=await fetch(s.registerEndpoint,{method:"POST",headers:{...a,"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?yo(s.viewerTemplate,o):g.split("?")[0],fileName:i,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function bo(s){return{async upload(e,t){const r=new FormData,i=s.fieldName??"file";r.append(i,e,e.name);const n=typeof s.extraFields=="function"?s.extraFields(t):s.extraFields;if(n)for(const[p,g]of Object.entries(n))r.append(p,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const o=typeof s.headers=="function"?await s.headers():s.headers??{},l=await fetch(s.endpoint,{method:s.method??"POST",body:r,headers:o,credentials:s.credentials});if(!l.ok)throw new Error(`Upload failed: ${l.status} ${l.statusText}`);const a=await l.json().catch(()=>({}));if(s.parseResponse)return s.parseResponse(a,t);const c=a,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const Qd="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Pl(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??Qd;return{async fetchMessages(i,n){const o=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(i)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),l=o.startsWith("http")?o:`${e}${o.startsWith("/")?o:`/${o}`}`,a={accept:"application/json","content-type":"application/json",...s.extraHeaders??{}};if(s.getToken){const p=await s.getToken();p&&(a.authorization=p)}const c=await fetch(l,{method:"GET",headers:a}),u=await c.json().catch(()=>null);if(s.parseResponse&&u)return s.parseResponse(u);const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const Xd="^[A-Z]{5}[0-9]{4}[A-Z]$",Zd="^[A-Z]{4}[0-9]{5}[A-Z]$",eh="^[A-Z]{4}0[A-Z0-9]{6}$",Ol="^[0-9]{6}$",th=[{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)",required:!0,pattern:Zd,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"basicSalary",type:"number",label:"Basic Salary",currency:"₹",required:!0,min:0},{id:"hraReceived",type:"number",label:"HRA Received",currency:"₹",min:0},{id:"leaveTravelAllowance",type:"number",label:"Leave Travel Allowance",currency:"₹",min:0},{id:"anyOtherAllowance",type:"number",label:"Other Allowances",currency:"₹",min:0},{id:"leaveEncashment",type:"number",label:"Leave Encashment",currency:"₹",min:0},{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted by Employer",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"businessGroup",type:"group",title:"Business Details",fields:[{id:"businessName",type:"text",label:"Business / Profession Name"},{id:"businessNatureOfWork",type:"text",label:"Nature of Work"},{id:"grossReceipts",type:"number",label:"Gross Receipts / Turnover",currency:"₹",min:0},{id:"netProfit",type:"number",label:"Net Profit",currency:"₹"}]}],submitLabel:"Save"},{id:"capital-gains",title:"Capital Gains",icon:"📈",fields:[{id:"equityGains",type:"group",title:"Equity & Mutual Funds",fields:[{id:"shortTermEquityGain",type:"number",label:"Short-Term Capital Gain",currency:"₹"},{id:"longTermEquityGain",type:"number",label:"Long-Term Capital Gain",currency:"₹"}]},{id:"propertyGains",type:"group",title:"Land & Building",fields:[{id:"landBuildingTermType",type:"radio",label:"Holding Period",options:[{value:"short",label:"Short-Term"},{value:"long",label:"Long-Term"}]},{id:"landBuildingPurchaseValue",type:"number",label:"Purchase Value",currency:"₹"},{id:"landBuildingSellValue",type:"number",label:"Sale Value",currency:"₹"}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureIncomeGt5Lakh",type:"yes-no",label:"Is agricultural income above ₹5,00,000?"}],submitLabel:"Save"},{id:"exempt-income",title:"Other Exempt Income",icon:"🧾",fields:[{id:"exemptIncome",type:"number",label:"Total Exempt Income",currency:"₹",min:0},{id:"exemptIncomeNature",type:"text",label:"Nature of Exempt Income",placeholder:"e.g. PPF interest, gratuity"}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"typeOfHouseProperty",type:"radio",label:"Property Type",required:!0,options:[{value:"SOP",label:"Self-Occupied"},{value:"LOP",label:"Let-Out"}]},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",hint:"Interest deduction capped at ₹2,00,000",fields:[{id:"loanTakenFrom",type:"text",label:"Loan Taken From",required:!0},{id:"lenderName",type:"text",label:"Lender Name",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account Number",required:!0},{id:"sanctionDate",type:"date",label:"Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Home Loan Interest",currency:"₹",min:0,max:2e5},{id:"homeLoanPrinciple",type:"number",label:"Home Loan Principal",currency:"₹",min:0}]},{id:"addressDetails",type:"group",title:"Property Address",fields:[{id:"housePropertyAddress",type:"text",label:"Address"},{id:"housePropertyPincode",type:"text",label:"Pincode",maxLength:6,pattern:Ol}]},{id:"rentalDetails",type:"group",title:"Rental Income Details",showWhen:{field:"typeOfHouseProperty",equals:"LOP"},fields:[{id:"rentalIncome",type:"number",label:"Annual Rental Income",currency:"₹",required:!0,min:0},{id:"nameOfTenant",type:"text",label:"Tenant Name",required:!0},{id:"propertyTax",type:"number",label:"Municipal / Property Tax Paid",currency:"₹",min:0}]},{id:"hasCoOwnedProperty",type:"yes-no",label:"Is this property co-owned?"},{id:"coOwnerGroup",type:"group",title:"Co-Owner Details",showWhen:{field:"hasCoOwnedProperty",equals:!0},fields:[{id:"coOwnerName",type:"text",label:"Co-Owner Name",required:!0},{id:"coOwnerPan",type:"text",label:"Co-Owner PAN",required:!0,pattern:Xd,maxLength:10},{id:"coOwnerShare",type:"text",label:"Co-Owner Share (%)",placeholder:"e.g. 50",maxLength:5}]}],submitLabel:"Save"},{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:"80C Investment Amount",currency:"₹",min:0,max:15e4}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Premium for Self / Spouse / Children",currency:"₹",min:0,max:25e3},{id:"us80dForParentsAmount",type:"number",label:"Premium for Parents",currency:"₹",min:0,max:5e4},{id:"hasParentOverSixty",type:"yes-no",label:"Are your parents senior citizens (60+)?"},{id:"preventiveHealthCheckUp",type:"number",label:"Preventive Health Check-up",currency:"₹",min:0},{id:"medicalExpenditure",type:"number",label:"Medical Expenditure (senior citizen)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"tax-paid-tds",title:"Tax Paid / TDS",icon:"🧮",fields:[{id:"tdsGroup",type:"group",title:"Tax Deducted at Source",fields:[{id:"tdsOnSalary",type:"number",label:"TDS on Salary",currency:"₹",min:0},{id:"tdsOtherThanSalary",type:"number",label:"TDS (other than salary)",currency:"₹",min:0}]},{id:"advanceTaxGroup",type:"group",title:"Advance / Self-Assessment Tax",fields:[{id:"selfAssessmentOrAdvanceTax",type:"number",label:"Advance / Self-Assessment Tax Paid",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:eh,maxLength:11}]},{id:"immovableGroup",type:"group",title:"Immovable Assets",hint:"Required if total income exceeds ₹50,00,000",fields:[{id:"immovableAssetDescription",type:"text",label:"Description"},{id:"immovableAssetFlatNo",type:"text",label:"Flat / House No."},{id:"immovableAssetArea",type:"text",label:"Area / Locality"},{id:"immovableAssetPincode",type:"text",label:"Pincode",maxLength:6,pattern:Ol},{id:"immovableAssetCost",type:"number",label:"Cost of Asset",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"have-a-question",title:"I only have a question",icon:"❓",fields:[{id:"question",type:"textarea",label:"What would you like to ask?",placeholder:"Type your question for the TaxBuddy expert…",required:!0,rows:5,maxLength:1e3}],submitLabel:"Send Question"}];function rh(s,e){const t=s||{},r={userId:vo(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Oe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Oe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Oe(t.us80dForParentsAmount),r.hasParentOverSixty=wo(t.hasParentOverSixty),r.preventiveHealthCheckUp=Oe(t.preventiveHealthCheckUp),r.medicalExpenditure=Oe(t.medicalExpenditure),r.savingBankInterest=Oe(t.savingBankInterest),r.fdInterest=Oe(t.fdInterest),r.dividend=Oe(t.dividend),r.anyOtherIncome=Oe(t.anyOtherIncome),r.cryptoSellValue=Oe(t.cryptoSellPrice),r.cryptoPurchaseAmount=Oe(t.cryptoPurchasePrice),r.vdaPurchaseCost=Oe(t.cryptoPurchasePrice),r.businessName=Me(t.businessName),r.businessAnnualTurnOver=Oe(t.grossReceipts),r.businessNetProfit=Oe(t.netProfit),r.agricultureDetails={income:Oe(t.agricultureIncome)},r.exemptIncomeAmount=Oe(t.exemptIncome),r.exemptIncomeNature=Me(t.exemptIncomeNature),Oe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Me(t.exemptIncomeNature)??"Exempt income",value:String(Oe(t.exemptIncome))}]),r.bankAccountNumber=Me(t.bankAccountNumber),r.bankIfscCode=Me(t.bankIfscCode),(Me(t.bankAccountNumber)||Me(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Me(t.bankAccountNumber),bankIfscCode:Me(t.bankIfscCode)}]);const i={description:Me(t.immovableAssetDescription),flatNo:Me(t.immovableAssetFlatNo),area:Me(t.immovableAssetArea),pinCode:Me(t.immovableAssetPincode),amount:Oe(t.immovableAssetCost)};Object.values(i).some(l=>l!==void 0)&&(r.immovableAsset=[i]);const n=_o(t.hpDetails,nh);n.length&&(r.hpDetails=n);const o=_o(t.salaryDetails,ih);if(o.length){r.salaryIncome=o;const l=_o(t.salaryDetails,c=>({grossSalary:Oe(c.grossSalary),employerName:Me(c.employerName)}));l.length&&(r.salary=l);const a=Ml(t.salaryDetails)[0]??{};r.hraAmount=Oe(a.hraReceived),r.leaveTravelAllowanceAmount=Oe(a.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Oe(a.leaveEncashment),r.anyOtherAllowanceAmount=Oe(a.anyOtherAllowance),r.salaryIncomeFlag=!0}return Gr(r)}function nh(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Me(s.loanTakenFrom),bankOrInstituteName:Me(s.lenderName),loanAccountNo:Me(s.loanAccountNumber),loanSanctionDate:ah(s.sanctionDate),totalLoanAmount:Oe(s.totalLoanAmount),interest:Oe(s.homeLoanInterest)},t=Object.entries(e).some(([r,i])=>r!=="loanType"&&i!==void 0);return{typeOfHouseProperty:Me(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:wo(s.hasRentalIncome),homeLoanInterest:Oe(s.homeLoanInterest),homeLoanPrinciple:Oe(s.homeLoanPrinciple),housePropertyAddress:Me(s.housePropertyAddress),housePropertyPincode:Me(s.housePropertyPincode),rentalIncome:Oe(s.rentalIncome),nameOfTenant:Me(s.nameOfTenant),propertyTax:Oe(s.propertyTax),hasCoOwnedProperty:wo(s.hasCoOwnedProperty),coOwnerName:Me(s.coOwnerName),coOwnerPan:Me(s.coOwnerPan),coOwnerShare:Me(s.coOwnerShare),loanDetails:t?[e]:void 0}}function ih(s){return{grossSalaryIncome:Oe(s.grossSalary),salary:Oe(s.basicSalary),employer:{employerName:Me(s.employerName),employerTan:Me(s.employerTan)},allowance:{hraAmount:Oe(s.hraReceived),leaveTravelAllowanceAmount:Oe(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Oe(s.leaveEncashment),anyOtherAllowanceAmount:Oe(s.anyOtherAllowance)}}}function oh(s,e){const t=[];for(const r of s){const i=Me(r.employerName),n=Me(r.employerTan),o=Oe(r.grossSalary),l=Oe(r.basicSalary),a=Oe(r.totalTdsDeposited);i===void 0&&n===void 0&&o===void 0&&l===void 0&&a===void 0||t.push({grossSalary:o??0,basicSalary:l??0,employerName:i??"",tanNumber:n??"",tdsDeducted:a??0})}return t.length?{userId:vo(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function sh(s,e){const t=Me(s.aadhaarNumber),r=Me(s.bankAccountNumber),i=Me(s.bankIfscCode);return t===void 0&&r===void 0&&i===void 0?null:{userId:vo(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:i}]}}function vo(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Oe(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Me(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function wo(s){return s===!0||s===!1?s:void 0}function ah(s){const e=Me(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Ml(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function _o(s,e){return Ml(s).map(t=>Gr(e(t))).filter(t=>t!==void 0)}function Gr(s){if(Array.isArray(s)){const e=s.map(Gr).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 i=Gr(r);i!==void 0&&(e[t]=i)}return Object.keys(e).length?e:void 0}return s}function lh(s){const e=s&&typeof s=="object"?s:{},t={},r=Je(e.employers),i=Je(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(a=>{const c=ko(a.salary),u=ko(a.perquisites),d=ko(a.profitsInLieuOfSalaryType),p=c+u+d,g=uh(a.allowance);return{employerName:Ue(a.employerName),employerTan:Ue(a.employerTAN),basicSalary:c||void 0,grossSalary:p||void 0,hraReceived:g.hra,leaveTravelAllowance:g.lta,leaveEncashment:g.leaveEncashment,anyOtherAllowance:g.other,totalTdsDeposited:ch(a,i,r)??Be(a.totalTdsDeposited)}}));const n=Je(e.houseProperties);n.length&&(t.hpDetails=n.map(a=>{const c=Je(a.loanDetails),u=c.length?c[0]:void 0,d=Be(a.grossAnnualRentReceived),p=c.length?c.reduce((w,m)=>w+(Be(m.interest)??0),0):void 0,g=Je(a.tenant),f=Je(a.coOwners),y=g[0],b=f[0];return{typeOfHouseProperty:Ue(a.propertyType),loanTakenFrom:Ue(u?.loanTakenFrom),lenderName:Ue(u?.bankOrInstituteName),loanAccountNumber:Ue(u?.loanAccountNo),sanctionDate:Ue(u?.loanSanctionDate),totalLoanAmount:Be(u?.totalLoanAmount),outstandingAmount:Be(u?.loanOutstandingAmount),homeLoanInterest:p,homeLoanPrinciple:void 0,housePropertyAddress:Ue(a.address),housePropertyPincode:Ue(a.pinCode),rentalIncome:d,nameOfTenant:Ue(y?.name),propertyTax:Be(a.propertyTax),hasCoOwnedProperty:f.length>0,coOwnerName:Ue(b?.name),coOwnerPan:Ue(b?.panNumber),coOwnerShare:Be(b?.share)?.toString()}})),t.us80cAmount=Kr(Je(e.deductionUS80CDetails).map(a=>Be(a.amount))),t.us80dForSelfAndFamilyAmount=Kr(Je(e.deductionUS80DDetails).map(a=>Be(a.healthInsuranceAmount))),t.anyOtherIncome=Kr(Je(e.incomes).filter(a=>Ue(a.incomeType)!=="SALARY"&&Ue(a.incomeType)!=="BUSINESS").map(a=>Be(a.amount))),t.dividend=Kr(Je(e.dividendIncomes).map(a=>Be(a.income)));const o=e.business;o&&(t.businessName=Ue(o.businessName),t.grossReceipts=Be(o.grossReceipts),t.netProfit=Be(o.netProfit)),t.agricultureIncome=Be(e.agriculturalDetails?.income),t.aadhaarNumber=Ue(e.aadharNumber);const l=Je(e.bankDetails)[0];return l&&(t.bankAccountNumber=Ue(l.accountNumber),t.bankIfscCode=Ue(l.ifsCode)),Rl(t)}function ko(s){return Je(s).reduce((e,t)=>e+(Be(t.taxableAmount)??0),0)}function ch(s,e,t){if(!e.length)return;const r=Ue(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ue(n.deductorTAN)?.trim().toUpperCase()===r)return Be(n.totalTdsDeposited)}const i=Ue(s.employerName)?.trim().toLowerCase();if(i){for(const n of e)if(Ue(n.deductorName)?.trim().toLowerCase()===i)return Be(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Be(e[0].totalTdsDeposited)}function uh(s){const e=Je(s);if(!e.length)return{};let t,r,i,n;for(const o of e){const l=Be(o.exemptAmount)??Be(o.allowanceAmount);switch(Ue(o.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=l;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=l;break;case"LEAVE_ENCASHMENT":i=l;break;default:n=(n??0)+(Be(o.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:i,other:n}}function Kr(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function Je(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Be(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Ue(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function Rl(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(Array.isArray(r)?e[t]=r.map(i=>i&&typeof i=="object"?Rl(i):i):e[t]=r);return e}function xo(){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=mh(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 i=gh(e.slug),n=typeof i?.tenantJwt=="string"?i.tenantJwt:"",o=e.getChatJwt,l=async()=>n||await o(),a=(i&&i.userId!=null&&i.userId!==""?String(i.userId):bh(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",a??"(none)"),{baseUrl:r,getToken:l,headers:yh(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||vh(),isRevised:"N",userId:a,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function dh(s){const e=await s.getToken(),t=s.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${s.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...s.headers}});if(!r.ok){const i=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${i.slice(0,200)}`)}return lh(So(await r.json().catch(()=>({}))))}async function hh(s,e){const t=await s.getToken(),r=s.userId,i=rh(e,{userId:r,assessmentYear:s.assessmentYear,isRevised:s.isRevised}),n=s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...s.headers};s.txbdyApiKey&&(o["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(i).join(", "));const l=await fetch(n,{method:"PUT",headers:o,body:JSON.stringify(i)});if(!l.ok){const a=await l.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${l.status} ${a.slice(0,200)}`)}return So(await l.json().catch(()=>({})))}async function fh(s,e){return Ll(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function ph(s,e){return Ll(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Ll(s,e,t){const i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await s.getToken()}`,...s.headers};s.txbdyApiKey&&(i["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:i,body:JSON.stringify(t)});if(!n.ok){const o=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${o.slice(0,200)}`)}return So(await n.json().catch(()=>({})))}function mh(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 gh(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 yh(s){const e={};if(!s)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,i]of Object.entries(s))!t.test(r)&&typeof i=="string"&&(e[r]=i);return e}function bh(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function So(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function vh(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class wh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Il(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??{},i=t.attributes?.action??{},n={...t.attributes,action:{...r,...i}};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(),i=r(e);return t.some(n=>typeof n=="string"&&r(n)===i)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:th,data:{}});const t=xo();if(!(!t||!t.baseUrl))try{const r=await dh(t);e.setData(r)}catch(r){console.warn("[smart-edit] fetch failed",r),this.errorBanner.show("Could not load your ITR details — starting from a blank form.",4e3)}}ensureSmartEditModal(){if(this.smartEditModal)return this.smartEditModal;const e=document.createElement("aikaara-smart-edit-modal");return document.body.appendChild(e),e.addEventListener("smart-edit-submit",(t=>{const r=t.detail;this.handleSectionSubmit(r.sectionId,r.record)})),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSectionSubmit(e,t){const r=xo();if(!r)return;const i={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],o=oh(n,i);o&&await fh(r,o)}else if(e==="bank-details"){const n=sh(t,i);n&&await ph(r,n)}}catch(n){console.warn("[smart-edit] section save failed",e,n),this.errorBanner.show("Failed to save. Please try again.",4e3)}}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=xo();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await hh(t,e)}catch(r){console.warn("[smart-edit] save failed",r),this.errorBanner.show("Failed to save your ITR details. Please try again.",4e3)}}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class Nl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||Oc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||jo,position:this.getAttribute("position")||this._config.position||Pc,width:Number(this.getAttribute("width"))||this._config.width||Ac,height:Number(this.getAttribute("height"))||this._config.height||Ic,fontFamily:this._config.fontFamily||Cc,borderRadius:this._config.borderRadius??Tc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Uo,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,chatActions:this._config.chatActions,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Mc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,i){if(typeof document>"u")return;const n=document.documentElement,o=(l,a)=>{a!==void 0&&a!==""&&n.style.setProperty(`--aikaara-${l}`,a)};o("primary",e?.primary??t),o("primary-hover",e?.primaryHover),o("primary-contrast",e?.primaryContrast),o("surface",e?.surface),o("surface-muted",e?.surfaceMuted),o("border",e?.border),o("text",e?.text),o("text-muted",e?.textMuted),o("font",e?.font??i),o("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),o("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),o("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),o("user-bubble-bg",e?.userBubbleBg),o("user-bubble-text",e?.userBubbleText),o("bot-bubble-bg",e?.botBubbleBg),o("bot-bubble-text",e?.botBubbleText),o("modal-width",e?.modalWidth),o("modal-height",e?.modalHeight),o("modal-max-width",e?.modalMaxWidth),o("modal-max-height",e?.modalMaxHeight),o("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=i=>typeof i=="number"?`${i}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(([,i])=>i!==void 0&&i!=="").map(([i,n])=>`--aikaara-${i}: ${n};`).join(`
6
+ `+ie.prev}function ke(z,ie){var Ee=be(z),Ae=[];if(Ee){Ae.length=z.length;for(var Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],z):""}var Pe=typeof T=="function"?T(z):[],nt;if(D){nt={};for(var it=0;it<Pe.length;it++)nt["$"+Pe[it]]=Pe[it]}for(var ze in z)oe(z,ze)&&(Ee&&String(Number(ze))===ze&&ze<z.length||D&&nt["$"+ze]instanceof Symbol||(E.call(/[^\w$]/,ze)?Ae.push(ie(ze,z)+": "+ie(z[ze],z)):Ae.push(ze+": "+ie(z[ze],z))));if(typeof T=="function")for(var ot=0;ot<Pe.length;ot++)ae.call(z,Pe[ot])&&Ae.push("["+ie(Pe[ot])+"]: "+ie(z[Pe[ot]],z));return Ae}return Ur}function Ih(){if(ao)return Dr;ao=!0;var s=qt(),e=dh(),t=Ah(),r=tr(),o=s("%WeakMap%",!0),n=s("%Map%",!0),i=e("WeakMap.prototype.get",!0),l=e("WeakMap.prototype.set",!0),a=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=_,_},g=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}},b=function(y,w){return!!p(y,w)};return Dr=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 g(m,x)},has:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return a(y,x)}else if(n){if(w)return h(w,x)}else if(m)return b(m,x);return!1},set:function(x,v){o&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new o),l(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),f(m,x,v))}};return _},Dr}function oo(){if(lo)return Fr;lo=!0;var s=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Fr={default:t.RFC3986,formatters:{RFC1738:function(r){return s.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Fr}function Va(){if(co)return $r;co=!0;var s=oo(),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)},l=function(y,w){return Object.keys(w).reduce(function(m,_){return m[_]=w[_],m},y)},a=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]"},g=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)},b=function(y,w){if(t(y)){for(var m=[],_=0;_<y.length;_+=1)m.push(w(y[_]));return m}return w(y)};return $r={arrayToObject:n,assign:l,combine:f,compact:h,decode:a,encode:u,isBuffer:g,isRegExp:p,maybeMap:b,merge:i},$r}function Th(){if(uo)return qr;uo=!0;var s=Ih(),e=Va(),t=oo(),r=Object.prototype.hasOwnProperty,o={brackets:function(b){return b+"[]"},comma:"comma",indices:function(b,y){return b+"["+y+"]"},repeat:function(b){return b}},n=Array.isArray,i=Array.prototype.push,l=function(b,y){i.apply(b,n(y)?y:[y])},a=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(b){return a.call(b)},skipNulls:!1,strictNullHandling:!1},h=function(b){return typeof b=="string"||typeof b=="number"||typeof b=="boolean"||typeof b=="symbol"||typeof b=="bigint"},p={},g=function b(y,w,m,_,x,v,E,S,I,O,P,j,T,q,D,U,ae,Y){for(var V=y,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var M=re.get(y);if(F+=1,typeof M<"u"){if(M===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=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,F);var oe=s();oe.set(p,Y),l(be,b(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},f=function(b){if(!b)return u;if(typeof b.allowEmptyArrays<"u"&&typeof b.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof b.encodeDotInKeys<"u"&&typeof b.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(b.encoder!==null&&typeof b.encoder<"u"&&typeof b.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=b.charset||u.charset;if(typeof b.charset<"u"&&b.charset!=="utf-8"&&b.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof b.format<"u"){if(!r.call(t.formatters,b.format))throw new TypeError("Unknown format option provided.");w=b.format}var m=t.formatters[w],_=u.filter;(typeof b.filter=="function"||n(b.filter))&&(_=b.filter);var x;if(b.arrayFormat in o?x=b.arrayFormat:"indices"in b?x=b.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in b&&typeof b.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof b.allowDots>"u"?b.encodeDotInKeys===!0?!0:u.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:u.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?u.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:u.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:u.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:w,formatter:m,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:u.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:u.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:u.strictNullHandling}};return qr=function(b,y){var w=b,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=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||l(v,g(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:""},qr}function Ch(){if(ho)return Hr;ho=!0;var s=Va(),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(g,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,g){return p&&typeof p=="string"&&g.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",l="utf8=%E2%9C%93",a=function(p,g){var f={__proto__:null},b=g.ignoreQueryPrefix?p.replace(/^\?/,""):p;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=g.parameterLimit===1/0?void 0:g.parameterLimit,w=b.split(g.delimiter,y),m=-1,_,x=g.charset;if(g.charsetSentinel)for(_=0;_<w.length;++_)w[_].indexOf("utf8=")===0&&(w[_]===l?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=g.decoder(v,r.decoder,x,"key"),O=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,S),r.decoder,x,"key"),O=s.maybeMap(n(v.slice(S+1),g),function(j){return g.decoder(j,r.decoder,x,"value")})),O&&g.interpretNumericEntities&&x==="iso-8859-1"&&(O=o(O)),v.indexOf("[]=")>-1&&(O=t(O)?[O]:O);var P=e.call(f,I);P&&g.duplicates==="combine"?f[I]=s.combine(f[I],O):(!P||g.duplicates==="last")&&(f[I]=O)}return f},c=function(p,g,f,b){for(var y=b?g:n(g,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,g,f,b){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,g,f,b)}},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 g=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 b=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:b,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:g,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: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 Hr=function(p,g){var f=h(g);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var b=typeof p=="string"?a(p,f):p,y=f.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var _=w[m],x=u(_,b[_],f,typeof p=="string");y=s.merge(y,x,f)}return f.allowSparse===!0?y:s.compact(y)},Hr}function Oh(){if(fo)return Wr;fo=!0;var s=Th(),e=Ch(),t=oo();return Wr={formats:t,parse:e,stringify:s},Wr}function Ph(){if(po)return St;po=!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),l=["'"].concat(i),a=["%","/","?",";","#"].concat(l),c=["/","?","#"],u=255,h=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},b={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=Oh();function w(v,E,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,E,S),I}e.prototype.parse=function(v,E,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),O=I!==-1&&I<v.indexOf("#")?"?":"#",P=v.split(O),j=/\\/g;P[0]=P[0].replace(j,"/"),v=P.join(O);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var q=o.exec(T);if(q)return this.path=T,this.href=T,this.pathname=q[1],q[2]?(this.search=q[2],E?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var U=D.toLowerCase();this.protocol=U,T=T.substr(D.length)}if(S||D||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(D&&f[D])&&(T=T.substr(2),this.slashes=!0)}if(!f[D]&&(ae||D&&!b[D])){for(var Y=-1,V=0;V<c.length;V++){var re=T.indexOf(c[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var F,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(F=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(F)),Y=-1;for(var V=0;V<a.length;V++){var re=T.indexOf(a[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var Q=this.hostname.split(/\./),V=0,be=Q.length;V<be;V++){var te=Q[V];if(te&&!te.match(h)){for(var we="",K=0,N=te.length;K<N;K++)te.charCodeAt(K)>127?we+="x":we+=te[K];if(!we.match(h)){var ne=Q.slice(0,V),W=Q.slice(V+1),G=te.match(p);G&&(ne.push(G[1]),W.unshift(G[2])),W.length&&(T="/"+W.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=s.toASCII(this.hostname));var J=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+J,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!g[U])for(var V=0,be=l.length;V<be;V++){var oe=l[V];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var $=T.indexOf("#");$!==-1&&(this.hash=T.substr($),T=T.slice(0,$));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),E&&(this.query=y.parse(this.query)),T=T.slice(0,ee)):E&&(this.search="",this.query={}),T&&(this.pathname=T),b[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var J=this.pathname||"",de=this.search||"";this.path=J+de}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=w(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var E=this.protocol||"",S=this.pathname||"",I=this.hash||"",O=!1,P="";this.host?O=v+this.host:this.hostname&&(O=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(O+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(P=y.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var j=this.search||P&&"?"+P||"";return E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||b[E])&&O!==!1?(O="//"+(O||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):O||(O=""),I&&I.charAt(0)!=="#"&&(I="#"+I),j&&j.charAt(0)!=="?"&&(j="?"+j),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),j=j.replace("#","%23"),E+O+S+j+I};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,I=Object.keys(this),O=0;O<I.length;O++){var P=I[O];S[P]=this[P]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var j=Object.keys(v),T=0;T<j.length;T++){var q=j[T];q!=="protocol"&&(S[q]=v[q])}return b[S.protocol]&&S.hostname&&!S.pathname&&(S.pathname="/",S.path=S.pathname),S.href=S.format(),S}if(v.protocol&&v.protocol!==S.protocol){if(!b[v.protocol]){for(var D=Object.keys(v),U=0;U<D.length;U++){var ae=D[U];S[ae]=v[ae]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!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||"",V=S.search||"";S.path=Y+V}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||re||S.host&&v.pathname,M=Z,Q=S.pathname&&S.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!b[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(Q[0]===""?Q[0]=S.host:Q.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||Q[0]==="")),F)S.host=v.host||v.host===""?v.host:S.host,S.hostname=v.hostname||v.hostname===""?v.hostname:S.hostname,S.search=v.search,S.query=v.query,Q=be;else if(be.length)Q||(Q=[]),Q.pop(),Q=Q.concat(be),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=Q.shift(),S.hostname=S.host;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return S.search=v.search,S.query=v.query,(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S}if(!Q.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var K=Q.slice(-1)[0],N=(S.host||v.host||Q.length>1)&&(K==="."||K==="..")||K==="",ne=0,W=Q.length;W>=0;W--)K=Q[W],K==="."?Q.splice(W,1):K===".."?(Q.splice(W,1),ne++):ne&&(Q.splice(W,1),ne--);if(!Z&&!M)for(;ne--;ne)Q.unshift("..");Z&&Q[0]!==""&&(!Q[0]||Q[0].charAt(0)!=="/")&&Q.unshift(""),N&&Q.join("/").substr(-1)!=="/"&&Q.push("");var G=Q[0]===""||Q[0]&&Q[0].charAt(0)==="/";if(te){S.hostname=G?"":Q.length?Q.shift():"",S.host=S.hostname;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return Z=Z||S.host&&Q.length,Z&&!G&&Q.unshift(""),Q.length>0?S.pathname=Q.join("/"):(S.pathname=null,S.path=null),(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=v.auth||S.auth,S.slashes=S.slashes||v.slashes,S.href=S.format(),S},e.prototype.parseHost=function(){var v=this.host,E=r.exec(v);E&&(E=E[0],E!==":"&&(this.port=E.substr(1)),v=v.substr(0,v.length-E.length)),v&&(this.hostname=v)},St.parse=w,St.resolve=_,St.resolveObject=x,St.format=m,St.Url=e,St}function Ka(s){if(typeof s=="string")s=new URL(s);else if(!(s instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(s.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return zr?Mh(s):Rh(s)}function Mh(s){let e=s.hostname,t=s.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let o=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&o===102||t[r+1]==="5"&&o===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(al,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,o=t[2];if(r<ol||r>sl||o!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Rh(s){if(s.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=s.pathname;for(let t=0;t<e.length;t++)if(e[t]==="%"){let r=e.codePointAt(t+2)||32;if(e[t+1]==="2"&&r===102)throw new Deno.errors.InvalidData("must not include encoded / characters")}return decodeURIComponent(e)}function Ga(s){let e=io.resolve(s),t=s.charCodeAt(s.length-1);(t===il||zr&&t===nl)&&e[e.length-1]!==io.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(ll,"%25")),!zr&&e.includes("\\")&&(e=e.replace(cl,"%5C")),e.includes(`
8
+ `)&&(e=e.replace(ul,"%0A")),e.includes("\r")&&(e=e.replace(hl,"%0D")),e.includes(" ")&&(e=e.replace(dl,"%09")),r.pathname=e,r}var Ya,Ur,so,Br,Dr,ao,Fr,lo,$r,co,qr,uo,Hr,ho,Wr,fo,St,po,We,Ja,Qa,Xa,Za,el,tl,rl,nl,il,ol,sl,zr,al,ll,cl,ul,hl,dl,Lh=Ge(()=>{le(),ue(),ce(),Qu(),fh(),Eh(),Wa(),Ya=Object.freeze(Object.create(null)),Ur={},so=!1,Br=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Dr={},ao=!1,Fr={},lo=!1,$r={},co=!1,qr={},uo=!1,Hr={},ho=!1,Wr={},fo=!1,St={},po=!1,We=Ph(),We.parse,We.resolve,We.resolveObject,We.format,We.Url,Ja=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,We.URL=typeof URL<"u"?URL:null,We.pathToFileURL=Ga,We.fileURLToPath=Ka,Qa=We.Url,Xa=We.format,Za=We.resolve,el=We.resolveObject,tl=We.parse,rl=We.URL,nl=92,il=47,ol=97,sl=122,zr=Ja==="win32",al=/\//g,ll=/%/g,cl=/\\/g,ul=/\n/g,hl=/\r/g,dl=/\t/g}),Nh=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")}}),mo=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=Ot(),t=($e(),Re(Fe));function r(n,i){let l=new Array(n.length);for(let a=0;a<n.length;a++)typeof n[a].chunk=="string"?l[a]=t.Buffer.from(n[a].chunk,"utf8"):l[a]=n[a].chunk;this._write(t.Buffer.concat(l),"binary",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,l){super({objectMode:!0}),this.proxy=i,this.socket=l,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",a=>{!this.destroyed&&this.readable&&this.push(a)})}_read(n){this.proxy.read(n)}_write(n,i,l){this.isSocketOpen?this.writeToProxy(n,i,l):this.writeQueue.push({chunk:n,encoding:i,cb:l})}_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,l){this.proxy.write(n,i)===!1?this.proxy.once("drain",l):l()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:l}=this.writeQueue.shift();this.writeToProxy(n,i,l)}}};s.BufferedDuplex=o}),Vr=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=($e(),Re(Fe)),r=e(Nh()),o=e(pt()),n=Ot(),i=e(wr()),l=mo(),a=(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 g(w,m,_){a("createWebSocket"),a(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";a(`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 b=(w,m)=>{a("streamBuilder");let _=h(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=g(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=b;var y=(w,m)=>{a("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=f(w,m),I=P(m,U,ae);m.objectMode||(I._writev=l.writev.bind(I)),I.on("close",()=>{S.close()});let O=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=I,_.socket=S):(_=new l.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 F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function j(){a("WebSocket onOpen"),_ instanceof l.BufferedDuplex&&_.socketReady()}function T(Y){a("WebSocket onClose",Y),_.end(),_.destroy()}function q(Y){a("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(F){return re(F)}re()}function ae(Y){S.close(),Y()}return _};s.browserStreamBuilder=y}),go={};Ut(go,{Server:()=>Ne,Socket:()=>Ne,Stream:()=>Ne,_createServerHandle:()=>Ne,_normalizeArgs:()=>Ne,_setSimultaneousAccepts:()=>Ne,connect:()=>Ne,createConnection:()=>Ne,createServer:()=>Ne,default:()=>fl,isIP:()=>Ne,isIPv4:()=>Ne,isIPv6:()=>Ne});function Ne(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var fl,pl=Ge(()=>{le(),ue(),ce(),fl={_createServerHandle:Ne,_normalizeArgs:Ne,_setSimultaneousAccepts:Ne,connect:Ne,createConnection:Ne,createServer:Ne,isIP:Ne,isIPv4:Ne,isIPv6:Ne,Server:Ne,Socket:Ne,Stream:Ne}}),ml=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),gl=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((pl(),Re(go))),r=e(pt()),o=e(ml()),n=(0,r.default)("mqttjs:tcp"),i=(l,a)=>{if(a.port=a.port||1883,a.hostname=a.hostname||a.host||"localhost",a.socksProxy)return(0,o.default)(a.hostname,a.port,a.socksProxy,{timeout:a.socksTimeout});let{port:c,path:u}=a,h=a.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};s.default=i}),bl={};Ut(bl,{default:()=>yl});var yl,jh=Ge(()=>{le(),ue(),ce(),yl={}}),vl=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=(jh(),Re(bl)),r=e((pl(),Re(go))),o=e(pt()),n=e(ml()),i=(0,o.default)("mqttjs:tls");function l(c){let{host:u,port:h,socksProxy:p,...g}=c;if(p!==void 0){let f=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:f})}return(0,t.connect)(c)}var a=(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=l(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(g){u.rejectUnauthorized&&c.emit("error",g),h.end()}return h.on("error",p),h};s.default=a}),wl=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Re(Fe)),t=Ot(),r=mo(),o,n,i;function l(){let p=new t.Transform;return p._write=(g,f,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},p._flush=g=>{o.close({success(){g()}})},p}function a(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,g){let f=p.protocol==="wxs"?"wss":"ws",b=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(b=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(b=p.transformWsUrl(b,p,g)),b}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(p=>{let g=new Error(p.errMsg);i.destroy(g)})}var h=(p,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let f=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";a(g);let b=c(g,p);o=wx.connectSocket({url:b,protocols:[f]}),n=l(),i=new r.BufferedDuplex(g,n,o),i._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=i.destroy;return i.destroy=(w,m)=>(i.destroy=y,setTimeout(()=>{o.close({fail(){i._destroy(w,m)}})},0),i),u(),i};s.default=h}),_l=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Re(Fe)),t=Ot(),r=mo(),o,n,i,l=!1;function a(){let g=new t.Transform;return g._write=(f,b,y)=>{o.sendSocketMessage({data:f.buffer,success(){y()},fail(){y(new Error)}})},g._flush=f=>{o.closeSocket({success(){f()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,f){let b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,f)),y}function h(){l||(l=!0,o.onSocketOpen(()=>{i.socketReady()}),o.onSocketMessage(g=>{if(typeof g.data=="string"){let f=e.Buffer.from(g.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(g.data)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(g=>{i.destroy(g)}))}var p=(g,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let b=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let y=u(f,g);return o=f.my,o.connectSocket({url:y,protocols:b}),n=a(),i=new r.BufferedDuplex(f,n,o),h(),i};s.default=p}),Uh=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((Lh(),Re(za))),o=e(wi()),n=e(wr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),l=null;function a(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,g,f]=p;h.username=g,h.password=f}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 b=r.default.parse(h,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,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,a(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 Le<"u"&&(p.socksProxy=Le.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(l||(l={},!n.default&&!p.forceNativeWebSocket?(l.ws=Vr().streamBuilder,l.wss=Vr().streamBuilder,l.mqtt=gl().default,l.tcp=gl().default,l.ssl=vl().default,l.tls=l.ssl,l.mqtts=vl().default):(l.ws=Vr().browserStreamBuilder,l.wss=Vr().browserStreamBuilder,l.wx=wl().default,l.wxs=wl().default,l.ali=_l().default,l.alis=_l().default)),!l[p.protocol]){let b=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof l[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(b){return p.servers&&((!b._reconnectCount||b._reconnectCount===p.servers.length)&&(b._reconnectCount=0),p.host=p.servers[b._reconnectCount].host,p.port=p.servers[b._reconnectCount].port,p.protocol=p.servers[b._reconnectCount].protocol?p.servers[b._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,b._reconnectCount++),i("calling streambuilder for",p.protocol),l[p.protocol](b,p)}let f=new o.default(g,p);return f.on("error",()=>{}),f}function u(h,p,g=!0){return new Promise((f,b)=>{let y=c(h,p),w={connect:_=>{m(),f(y)},end:()=>{m(),f(y)},error:_=>{m(),y.end(),b(_)}};g===!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}),kl=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(g,f,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(f,b);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[b]}}),Object.defineProperty(g,y,w)}:function(g,f,b,y){y===void 0&&(y=b),g[y]=f[b]}),t=s&&s.__setModuleDefault||(Object.create?function(g,f){Object.defineProperty(g,"default",{enumerable:!0,value:f})}:function(g,f){g.default=f}),r=s&&s.__importStar||(function(){var g=function(f){return g=Object.getOwnPropertyNames||function(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(f)};return function(f){if(f&&f.__esModule)return f;var b={};if(f!=null)for(var y=g(f),w=0;w<y.length;w++)y[w]!=="default"&&e(b,f,y[w]);return t(b,f),b}})(),o=s&&s.__exportStar||function(g,f){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(f,b)&&e(f,g,b)},n=s&&s.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=s.KeepaliveManager=s.UniqueMessageIdProvider=s.DefaultMessageIdProvider=s.Store=s.MqttClient=s.connectAsync=s.connect=s.Client=void 0;var i=n(wi());s.MqttClient=i.default;var l=n(Cs());s.DefaultMessageIdProvider=l.default;var a=n(Yu());s.UniqueMessageIdProvider=a.default;var c=n(ks());s.Store=c.default;var u=r(Uh());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(js());s.KeepaliveManager=h.default,s.Client=i.default,o(wi(),s),o($t(),s),o(_s(),s);var p=yr();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Bh=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(i,l,a,c){c===void 0&&(c=a);var u=Object.getOwnPropertyDescriptor(l,a);(!u||("get"in u?!l.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return l[a]}}),Object.defineProperty(i,c,u)}:function(i,l,a,c){c===void 0&&(c=a),i[c]=l[a]}),t=s&&s.__setModuleDefault||(Object.create?function(i,l){Object.defineProperty(i,"default",{enumerable:!0,value:l})}:function(i,l){i.default=l}),r=s&&s.__importStar||(function(){var i=function(l){return i=Object.getOwnPropertyNames||function(a){var c=[];for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(c[c.length]=u);return c},i(l)};return function(l){if(l&&l.__esModule)return l;var a={};if(l!=null)for(var c=i(l),u=0;u<c.length;u++)c[u]!=="default"&&e(a,l,c[u]);return t(a,l),a}})(),o=s&&s.__exportStar||function(i,l){for(var a in i)a!=="default"&&!Object.prototype.hasOwnProperty.call(l,a)&&e(l,i,a)};Object.defineProperty(s,"__esModule",{value:!0});var n=r(kl());s.default=n,o(kl(),s)});const Dh=Bh();const Fh={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}/#"},$h=300,qh={templateId:"7",type:"link",isDeepLink:!0},Hh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class xl{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={...Fh,...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 l=!1;const a=h=>{l||(l=!0,clearTimeout(u),h())},c=(h,p)=>{l||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),a(()=>i(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Dh.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),l||a(()=>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),!l){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),l||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",{}),l||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={...qh,...this.config.fileTemplate??{},...Wh(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=$h){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(g=>g(p)),this.messageHandlers.forEach(g=>g(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),l=i?.groups?.conversationId,a={topic:e,conversationId:l,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,a))}buildOutgoingEnvelope(e,t){const r={...Hh,...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 l=i[n];return l?l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Wh(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function Sl(s,e){return(s.sender??"").toString()===e}function El(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 bo(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 Al(s){const e=bo(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,l=typeof o.description=="string"?o.description:void 0,a=s.attributes,c=a&&typeof a.cloudFileId=="string"?a.cloudFileId:void 0;return!i&&!l?null:{fileName:l,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function Il(s,e,t){const r=El(s,t),o=bo(s),n=Al(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 l=typeof s.message_id=="string"?s.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,a=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:l,externalId:l,conversationId:e,role:c,content:i,createdAt:a,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 Tl extends ur{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new Fo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new $o,this.conversationManager=new Vo(e.conversationId),this.usesAikaara()&&(this.connection=new Do(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 xl({...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(a){return this.config.onError?.(a instanceof Error?a:new Error(String(a))),"unknown"}if(!r.length)return"empty";const o=r.map(a=>Il(a,e,{userId:t})).sort((a,c)=>new Date(a.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(a=>a.message),i=this.messageStore.messages,l=[...n,...i.filter(a=>!n.some(c=>c.externalId&&c.externalId===a.externalId))];this.messageStore.setMessages(l);for(const{message:a,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(a)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:a.id,conversationId:e,role:a.role==="tool"?"system":a.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:l}=Il(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(Sl(e,n)){const u=this.messageStore.reconcileOptimistic(i);if(u){this.emit("message:updated",u);return}}const{message:a,deduped:c}=this.messageStore.upsertRemoteMessage(i);if(c)this.emit("message:updated",a);else{this.emit("message:received",a),this.config.onMessage?.(a);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:a.role,hasAttachments:Array.isArray(a.attachments)&&a.attachments.length>0,templateId:a.template?.templateId,messageId:a.id,conversationId:a.conversationId}}))}catch{}}if(l.contentType){const u={messageId:a.id,conversationId:o,role:i.role==="tool"?"system":i.role,contentType:l.contentType,templateId:l.templateId,payload:l.payload,innerMessage:l.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class Vh extends ur{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const Cl={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 Kh(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function Gh(s,e,t){const r=Kh(s.name||"");if(r&&e&&e[r])return e[r];const o=s.type;return o&&o.trim().length>0?o:r&&Cl[r]?Cl[r]:t}function yo(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Yh(s,e){const t=e.split(".");let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function Ol(s){const e=s.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Gh(t,s.contentTypeMap,s.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},l=s.authHeader?await s.authHeader():void 0,a={accept:"application/json",...s.extraHeaders??{},...l?{authorization:l}:{}};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=yo(c,i),h=await fetch(u,{method:s.signMethod??"GET",headers:a});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),g=Yh(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const f=s.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,s.s3HostRewrite):g,b=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(s.registerEndpoint){const w=JSON.parse(yo(JSON.stringify(s.registerBody??{}),i)),m=await fetch(s.registerEndpoint,{method:"POST",headers:{...a,"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?yo(s.viewerTemplate,i):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function vo(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,g]of Object.entries(n))r.append(p,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof s.headers=="function"?await s.headers():s.headers??{},l=await fetch(s.endpoint,{method:s.method??"POST",body:r,headers:i,credentials:s.credentials});if(!l.ok)throw new Error(`Upload failed: ${l.status} ${l.statusText}`);const a=await l.json().catch(()=>({}));if(s.parseResponse)return s.parseResponse(a,t);const c=a,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 Jh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Pl(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??Jh;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)),l=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,a={accept:"application/json","content-type":"application/json",...s.extraHeaders??{}};if(s.getToken){const p=await s.getToken();p&&(a.authorization=p)}const c=await fetch(l,{method:"GET",headers:a}),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 Qh=[{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)",required:!0,pattern:"^[A-Z]{4}[0-9]{5}[A-Z]$",maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"basicSalary",type:"number",label:"Basic Salary",currency:"₹",required:!0,min:0},{id:"hraReceived",type:"number",label:"HRA Received",currency:"₹",min:0},{id:"leaveTravelAllowance",type:"number",label:"Leave Travel Allowance",currency:"₹",min:0},{id:"anyOtherAllowance",type:"number",label:"Other Allowances",currency:"₹",min:0},{id:"leaveEncashment",type:"number",label:"Leave Encashment",currency:"₹",min:0},{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted by Employer",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"businessGroup",type:"group",title:"Business Details",fields:[{id:"businessName",type:"text",label:"Business / Profession Name"},{id:"businessNatureOfWork",type:"text",label:"Nature of Work"},{id:"grossReceipts",type:"number",label:"Gross Receipts / Turnover",currency:"₹",min:0},{id:"netProfit",type:"number",label:"Net Profit",currency:"₹"}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:"^[A-Z]{4}0[A-Z0-9]{6}$",maxLength:11}]},{id:"immovableGroup",type:"group",title:"Immovable Assets",hint:"Required if total income exceeds ₹50,00,000",fields:[{id:"immovableAssetDescription",type:"text",label:"Description"},{id:"immovableAssetFlatNo",type:"text",label:"Flat / House No."},{id:"immovableAssetArea",type:"text",label:"Area / Locality"},{id:"immovableAssetPincode",type:"text",label:"Pincode",maxLength:6,pattern:"^[0-9]{6}$"},{id:"immovableAssetCost",type:"number",label:"Cost of Asset",currency:"₹",min:0}]}],submitLabel:"Save"}];function Xh(s,e){const t=s||{},r={userId:Kr(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Te(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Te(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Te(t.us80dForParentsAmount),r.hasParentOverSixty=wo(t.hasParentOverSixty),r.preventiveHealthCheckUp=Te(t.preventiveHealthCheckUp),r.medicalExpenditure=Te(t.medicalExpenditure),r.savingBankInterest=Te(t.savingBankInterest),r.fdInterest=Te(t.fdInterest),r.dividend=Te(t.dividend),r.anyOtherIncome=Te(t.anyOtherIncome),r.cryptoSellValue=Te(t.cryptoSellPrice),r.cryptoPurchaseAmount=Te(t.cryptoPurchasePrice),r.vdaPurchaseCost=Te(t.cryptoPurchasePrice),r.businessName=Me(t.businessName),r.businessAnnualTurnOver=Te(t.grossReceipts),r.businessNetProfit=Te(t.netProfit),r.agricultureDetails={income:Te(t.agricultureIncome)},r.exemptIncomeAmount=Te(t.exemptIncome),r.exemptIncomeNature=Me(t.exemptIncomeNature),Te(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Me(t.exemptIncomeNature)??"Exempt income",value:String(Te(t.exemptIncome))}]),r.bankAccountNumber=Me(t.bankAccountNumber),r.bankIfscCode=Me(t.bankIfscCode),(Me(t.bankAccountNumber)||Me(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Me(t.bankAccountNumber),bankIfscCode:Me(t.bankIfscCode)}]);const o={description:Me(t.immovableAssetDescription),flatNo:Me(t.immovableAssetFlatNo),area:Me(t.immovableAssetArea),pinCode:Me(t.immovableAssetPincode),amount:Te(t.immovableAssetCost)};Object.values(o).some(l=>l!==void 0)&&(r.immovableAsset=[o]);const n=_o(t.hpDetails,Zh);n.length&&(r.hpDetails=n);const i=_o(t.salaryDetails,ed);if(i.length){r.salaryIncome=i;const l=_o(t.salaryDetails,c=>({grossSalary:Te(c.grossSalary),employerName:Me(c.employerName)}));l.length&&(r.salary=l);const a=Ml(t.salaryDetails)[0]??{};r.hraAmount=Te(a.hraReceived),r.leaveTravelAllowanceAmount=Te(a.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Te(a.leaveEncashment),r.anyOtherAllowanceAmount=Te(a.anyOtherAllowance),r.salaryIncomeFlag=!0}return Gr(r)}function Zh(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Me(s.loanTakenFrom),bankOrInstituteName:Me(s.lenderName),loanAccountNo:Me(s.loanAccountNumber),loanSanctionDate:id(s.sanctionDate),totalLoanAmount:Te(s.totalLoanAmount),interest:Te(s.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Me(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:wo(s.hasRentalIncome),homeLoanInterest:Te(s.homeLoanInterest),homeLoanPrinciple:Te(s.homeLoanPrinciple),housePropertyAddress:Me(s.housePropertyAddress),housePropertyPincode:Me(s.housePropertyPincode),rentalIncome:Te(s.rentalIncome),nameOfTenant:Me(s.nameOfTenant),propertyTax:Te(s.propertyTax),hasCoOwnedProperty:wo(s.hasCoOwnedProperty),coOwnerName:Me(s.coOwnerName),coOwnerPan:Me(s.coOwnerPan),coOwnerShare:Me(s.coOwnerShare),loanDetails:t?[e]:void 0}}function ed(s){return{grossSalaryIncome:Te(s.grossSalary),salary:Te(s.basicSalary),employer:{employerName:Me(s.employerName),employerTan:Me(s.employerTan)},allowance:{hraAmount:Te(s.hraReceived),leaveTravelAllowanceAmount:Te(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Te(s.leaveEncashment),anyOtherAllowanceAmount:Te(s.anyOtherAllowance)}}}function td(s,e){const t=[];for(const r of s){const o=Me(r.employerName),n=Me(r.employerTan),i=Te(r.grossSalary),l=Te(r.basicSalary),a=Te(r.totalTdsDeposited);o===void 0&&n===void 0&&i===void 0&&l===void 0&&a===void 0||t.push({grossSalary:i??0,basicSalary:l??0,employerName:o??"",tanNumber:n??"",tdsDeducted:a??0})}return t.length?{userId:Kr(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function rd(s,e){const t=Me(s.aadhaarNumber),r=Me(s.bankAccountNumber),o=Me(s.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:Kr(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function nd(s,e){return{userId:Kr(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Te(s.savingBankInterest)??0,fdInterest:Te(s.fdInterest)??0,dividend:Te(s.dividend)??0,anyOtherIncome:Te(s.anyOtherIncome)??0}}function Kr(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Te(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Me(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function wo(s){return s===!0||s===!1?s:void 0}function id(s){const e=Me(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Ml(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function _o(s,e){return Ml(s).map(t=>Gr(e(t))).filter(t=>t!==void 0)}function Gr(s){if(Array.isArray(s)){const e=s.map(Gr).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=Gr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return s}function od(s){const e=s&&typeof s=="object"?s:{},t={},r=Je(e.employers),o=Je(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(a=>{const c=ko(a.salary),u=ko(a.perquisites),h=ko(a.profitsInLieuOfSalaryType),p=c+u+h,g=ad(a.allowance);return{employerName:Ue(a.employerName),employerTan:Ue(a.employerTAN),basicSalary:c||void 0,grossSalary:p||void 0,hraReceived:g.hra,leaveTravelAllowance:g.lta,leaveEncashment:g.leaveEncashment,anyOtherAllowance:g.other,totalTdsDeposited:sd(a,o,r)??Be(a.totalTdsDeposited)}}));const n=Je(e.houseProperties);n.length&&(t.hpDetails=n.map(a=>{const c=Je(a.loanDetails),u=c.length?c[0]:void 0,h=Be(a.grossAnnualRentReceived),p=c.length?c.reduce((w,m)=>w+(Be(m.interest)??0),0):void 0,g=Je(a.tenant),f=Je(a.coOwners),b=g[0],y=f[0];return{typeOfHouseProperty:Ue(a.propertyType),loanTakenFrom:Ue(u?.loanTakenFrom),lenderName:Ue(u?.bankOrInstituteName),loanAccountNumber:Ue(u?.loanAccountNo),sanctionDate:Ue(u?.loanSanctionDate),totalLoanAmount:Be(u?.totalLoanAmount),outstandingAmount:Be(u?.loanOutstandingAmount),homeLoanInterest:p,homeLoanPrinciple:void 0,housePropertyAddress:Ue(a.address),housePropertyPincode:Ue(a.pinCode),rentalIncome:h,nameOfTenant:Ue(b?.name),propertyTax:Be(a.propertyTax),hasCoOwnedProperty:f.length>0,coOwnerName:Ue(y?.name),coOwnerPan:Ue(y?.panNumber),coOwnerShare:Be(y?.share)?.toString()}})),t.us80cAmount=Yr(Je(e.deductionUS80CDetails).map(a=>Be(a.amount))),t.us80dForSelfAndFamilyAmount=Yr(Je(e.deductionUS80DDetails).map(a=>Be(a.healthInsuranceAmount))),t.anyOtherIncome=Yr(Je(e.incomes).filter(a=>Ue(a.incomeType)!=="SALARY"&&Ue(a.incomeType)!=="BUSINESS").map(a=>Be(a.amount))),t.dividend=Yr(Je(e.dividendIncomes).map(a=>Be(a.income)));const i=e.business;i&&(t.businessName=Ue(i.businessName),t.grossReceipts=Be(i.grossReceipts),t.netProfit=Be(i.netProfit)),t.agricultureIncome=Be(e.agriculturalDetails?.income),t.aadhaarNumber=Ue(e.aadharNumber);const l=Je(e.bankDetails)[0];return l&&(t.bankAccountNumber=Ue(l.accountNumber),t.bankIfscCode=Ue(l.ifsCode)),Rl(t)}function ko(s){return Je(s).reduce((e,t)=>e+(Be(t.taxableAmount)??0),0)}function sd(s,e,t){if(!e.length)return;const r=Ue(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ue(n.deductorTAN)?.trim().toUpperCase()===r)return Be(n.totalTdsDeposited)}const o=Ue(s.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Ue(n.deductorName)?.trim().toLowerCase()===o)return Be(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Be(e[0].totalTdsDeposited)}function ad(s){const e=Je(s);if(!e.length)return{};let t,r,o,n;for(const i of e){const l=Be(i.exemptAmount)??Be(i.allowanceAmount);switch(Ue(i.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=l;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=l;break;case"LEAVE_ENCASHMENT":o=l;break;default:n=(n??0)+(Be(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Yr(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function Je(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Be(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Ue(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function Rl(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"?Rl(o):o):e[t]=r);return e}function xo(){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=fd(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=pd(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,l=async()=>n||await i(),a=(o&&o.userId!=null&&o.userId!==""?String(o.userId):gd(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",a??"(none)"),{baseUrl:r,getToken:l,headers:md(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||bd(),isRevised:"N",userId:a,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function ld(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 od(Eo(await r.json().catch(()=>({}))))}async function cd(s,e){const t=await s.getToken(),r=s.userId,o=Xh(e,{userId:r,assessmentYear:s.assessmentYear,isRevised:s.isRevised}),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 l=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!l.ok){const a=await l.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${l.status} ${a.slice(0,200)}`)}return Eo(await l.json().catch(()=>({})))}async function ud(s,e){return So(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function hd(s,e){return So(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function dd(s,e){return So(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function So(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 Eo(await n.json().catch(()=>({})))}function fd(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 pd(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 md(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 gd(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function Eo(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function bd(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class yd{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Tl(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:Qh,data:{}});const t=xo();if(!(!t||!t.baseUrl))try{const r=await ld(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=xo();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=td(n,o);i&&await ud(r,i)}else if(e==="bank-details"){const n=rd(t,o);n&&await hd(r,n)}else e==="other-sources"&&await dd(r,nd(t,o))}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=xo();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await cd(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 Ll extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||Oc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Uo,position:this.getAttribute("position")||this._config.position||Cc,width:Number(this.getAttribute("width"))||this._config.width||Ec,height:Number(this.getAttribute("height"))||this._config.height||Ac,fontFamily:this._config.fontFamily||Tc,borderRadius:this._config.borderRadius??Ic,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Bo,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||Pc,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=(l,a)=>{a!==void 0&&a!==""&&n.style.setProperty(`--aikaara-${l}`,a)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??o),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
9
9
  `)}setUploadAdapter(e){this._config.uploadAdapter=e,this.controller?.getClient().setUploadAdapter(e)}setHistoryAdapter(e){this._config.historyAdapter=e}render(){const e=this.getConfig(),t=e.display==="embed";this.propagateThemeToDocument(e.themeTokens,e.primaryColor,e.borderRadius,e.fontFamily);const r=`
10
10
  font-family: var(--aikaara-font);
11
11
  position: fixed;
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
- `,i=`
15
+ `,o=`
16
16
  font-family: var(--aikaara-font);
17
17
  display: flex;
18
18
  flex-direction: column;
@@ -30,7 +30,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
30
30
  bottom: calc(var(--aikaara-bubble-size) + 16px);
31
31
  ${e.position==="bottom-left"?"left":"right"}: 0;
32
32
  transition: opacity 200ms ease, transform 200ms ease;
33
- `,o=`
33
+ `,i=`
34
34
  width: 100%;
35
35
  flex: 1 1 auto;
36
36
  min-height: 0;
@@ -41,7 +41,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
41
41
  <style>
42
42
  :host {
43
43
  --aikaara-primary: ${e.primaryColor};
44
- --aikaara-primary-hover: ${this.darkenColor(e.primaryColor||jo)};
44
+ --aikaara-primary-hover: ${this.darkenColor(e.primaryColor||Uo)};
45
45
  /* Cascade through descriptor.theme.surface / surfaceMuted /
46
46
  * text / textMuted / border when those are present (themeVars
47
47
  * sets the canonical token below). When the descriptor doesn't
@@ -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?i:r}
63
+ ${t?o:r}
64
64
  }
65
65
 
66
66
  .aikaara-panel {
@@ -68,7 +68,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
68
68
  display: flex;
69
69
  flex-direction: column;
70
70
  overflow: hidden;
71
- ${t?o:n}
71
+ ${t?i:n}
72
72
  }
73
73
 
74
74
  .aikaara-panel[hidden] {
@@ -112,14 +112,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
112
112
  ></aikaara-chat-header>`}
113
113
  <aikaara-message-list></aikaara-message-list>
114
114
  <aikaara-chat-input
115
- placeholder="${e.placeholder||Uo}"
115
+ placeholder="${e.placeholder||Bo}"
116
116
  ${this._config.uploadAdapter?"":"disable-attach"}
117
117
  ${e.input?.attachPosition==="right"?'attach-position="right"':""}
118
118
  ${e.input?.sendButtonShape==="square"?'send-shape="square"':""}
119
119
  ></aikaara-chat-input>
120
120
  <aikaara-error-banner></aikaara-error-banner>
121
121
  </div>
122
- `;const l=this.shadow.querySelector("aikaara-message-list");if(l){e.hideSystemMessages?.length&&l.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&l.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&l.setShowTimestamps?.(e.showTimestamps);const a=e.templateLayout;a&&l.setTemplateLayout?.(a)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new wh(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),i=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|i<<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=`
122
+ `;const l=this.shadow.querySelector("aikaara-message-list");if(l){e.hideSystemMessages?.length&&l.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&l.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&l.setShowTimestamps?.(e.showTimestamps);const a=e.templateLayout;a&&l.setTemplateLayout?.(a)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new yd(e,this.shadow,{uploadAdapter:this._config.uploadAdapter,historyAdapter:this._config.historyAdapter}),await this.controller.connect())}sendUserEvent(e,t,r){this.controller?.sendUserEvent(e,t,r)}getClient(){return this.controller?.getClient()??null}darkenColor(e){try{const t=parseInt(e.replace("#",""),16),r=Math.max(0,(t>>16)-20),o=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|o<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class Nl 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 _h=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class Ul extends HTMLElement{shadow;actions=_h;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 i=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:i,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"),i=this.getAttribute("status")||"connected",n=i==="connected"?"#10b981":i==="connecting"||i==="reconnecting"?"#f59e0b":"#ef4444",o=this.actions.map(l=>`
157
+ `}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const vd=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class jl extends HTMLElement{shadow;actions=vd;menuOpen=!1;outsideClickHandler=null;static get observedAttributes(){return["title","subtitle","avatar-url","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.bindHandlers()}disconnectedCallback(){this.outsideClickHandler&&document.removeEventListener("click",this.outsideClickHandler,!0)}attributeChangedCallback(){this.render(),this.bindHandlers()}setActions(e){this.actions=e,this.render(),this.bindHandlers()}bindHandlers(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))}),this.shadow.querySelector(".menu-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.toggleMenu()}),this.shadow.querySelectorAll(".menu-item").forEach(t=>{t.addEventListener("click",r=>{r.stopPropagation();const o=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:o,label:n},bubbles:!0,composed:!0}))})}),this.outsideClickHandler||(this.outsideClickHandler=t=>{!this.menuOpen||t.composedPath().includes(this)||this.closeMenu()},document.addEventListener("click",this.outsideClickHandler,!0))}toggleMenu(){this.menuOpen=!this.menuOpen;const e=this.shadow.querySelector(".menu");e&&e.classList.toggle("open",this.menuOpen)}closeMenu(){if(!this.menuOpen)return;this.menuOpen=!1;const e=this.shadow.querySelector(".menu");e&&e.classList.remove("open")}iconSvg(e){return e==="edit"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>':e==="mail"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>':e==="star"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>':""}render(){const e=this.getAttribute("title")||"Chat",t=this.getAttribute("subtitle")||"",r=this.getAttribute("avatar-url"),o=this.getAttribute("status")||"connected",n=o==="connected"?"#10b981":o==="connecting"||o==="reconnecting"?"#f59e0b":"#ef4444",i=this.actions.map(l=>`
158
158
  <button class="menu-item" type="button" data-action-id="${l.id}" data-action-label="${l.label}">
159
159
  <span class="menu-item-icon">${this.iconSvg(l.icon)}</span>
160
160
  <span class="menu-item-label">${l.label}</span>
@@ -304,7 +304,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
304
304
  <svg viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="12" cy="19" r="1.6"/></svg>
305
305
  </button>
306
306
  <div class="menu" role="menu">
307
- ${o}
307
+ ${i}
308
308
  </div>
309
309
  </div>`:""}
310
310
  <button class="icon-btn close-btn" aria-label="Close chat" type="button">
@@ -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 kh=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,xh=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,Sh={"&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">","&amp;":"&","&nbsp;":" "};function Eh(s){return s.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>Sh[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(/&amp;/gi,"&")}function Wt(s){if(kh.test(s))return s;const e=xh.test(s)?Eh(s):s;let t=Ah(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,i,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,i,n)=>{const o=/[.,!?;:]+$/.exec(n),l=o?o[0]:"",a=l?n.slice(0,n.length-l.length):n;return`${i}<a href="${a}" target="_self" rel="noopener noreferrer">${a}</a>${l}`}),t=t.replace(/\n/g,"<br>"),t}function Ah(s){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return s.replace(/[&<>"']/g,t=>e[t])}const Ih=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"]),Th={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 zt(s){const e=document.createElement("template");return e.innerHTML=s,Bl(e.content),e.innerHTML}function Bl(s){const e=Array.from(s.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,i=r.tagName.toLowerCase();if(!Ih.has(i)){const l=document.createTextNode(r.textContent||"");s.replaceChild(l,t);continue}const n=Th[i]||new Set,o=Array.from(r.attributes);for(const l of o)n.has(l.name)||r.removeAttribute(l.name);if(r.hasAttribute("href")){const l=r.getAttribute("href")||"";!l.startsWith("http://")&&!l.startsWith("https://")&&!l.startsWith("/")&&r.removeAttribute("href")}Bl(t)}}function Dl(s,e={}){const{width:t=600,height:r=700,closeOnTypes:i}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),o=Math.round(window.screenY+(window.outerHeight-r)/2),l=window.open(s,"aikaara_popup",`width=${t},height=${r},left=${n},top=${o},resizable=yes,scrollbars=yes,status=yes`);if(!l)return null;const a=u=>{if(u.source!==l)return;const d=u.data?.type;i&&typeof d=="string"&&!i.includes(d)||(l.close(),window.removeEventListener("message",a))};window.addEventListener("message",a);const c=setInterval(()=>{l.closed&&(window.removeEventListener("message",a),clearInterval(c))},500);return l}function Ch(s){const e=Date.now()-s.getTime(),t=Math.round(e/1e3);if(t<5)return"just now";if(t<60)return`${t}s ago`;const r=Math.round(t/60);if(r<60)return`${r} min ago`;const i=Math.round(r/60);if(i<24)return`${i} hr ago`;const n=Math.round(i/24);return n===1?"Yesterday":n<7?`${n} d ago`:s.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class Fl extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(e.template?.contentType)return!1;const t=e.content;if(!t)return!1;const r=t.trim().toLowerCase();return r==="chat_initiated"||r==="group created"||r==="file_uploaded"||r==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(i=>r.includes(i)):!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(o=>o&&o.tagName==="A");if(!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment"))return;const i=this.linkHandlers.some(o=>$l(r.href,o.match));r.target==="_self"&&!i||t.some(o=>{if(!o||!o.classList)return!1;const l=o.classList;return l.contains("bubble")&&l.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
317
+ `}setStatus(e){this.setAttribute("status",e)}}const wd=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,_d=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,kd={"&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">","&amp;":"&","&nbsp;":" "};function xd(s){return s.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>kd[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(/&amp;/gi,"&")}function Wt(s){if(wd.test(s))return s;const e=_d.test(s)?xd(s):s;let t=Sd(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,o,n)=>`<pre><code>${n.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_self" rel="noopener noreferrer">$1</a>'),t=t.replace(/(^|[^"'>=(])(https?:\/\/[^\s<]+)/g,(r,o,n)=>{const i=/[.,!?;:]+$/.exec(n),l=i?i[0]:"",a=l?n.slice(0,n.length-l.length):n;return`${o}<a href="${a}" target="_self" rel="noopener noreferrer">${a}</a>${l}`}),t=t.replace(/\n/g,"<br>"),t}function Sd(s){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return s.replace(/[&<>"']/g,t=>e[t])}const Ed=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"]),Ad={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 zt(s){const e=document.createElement("template");return e.innerHTML=s,Ul(e.content),e.innerHTML}function Ul(s){const e=Array.from(s.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,o=r.tagName.toLowerCase();if(!Ed.has(o)){const l=document.createTextNode(r.textContent||"");s.replaceChild(l,t);continue}const n=Ad[o]||new Set,i=Array.from(r.attributes);for(const l of i)n.has(l.name)||r.removeAttribute(l.name);if(r.hasAttribute("href")){const l=r.getAttribute("href")||"";!l.startsWith("http://")&&!l.startsWith("https://")&&!l.startsWith("/")&&r.removeAttribute("href")}Ul(t)}}function Bl(s,e={}){const{width:t=600,height:r=700,closeOnTypes:o}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),i=Math.round(window.screenY+(window.outerHeight-r)/2),l=window.open(s,"aikaara_popup",`width=${t},height=${r},left=${n},top=${i},resizable=yes,scrollbars=yes,status=yes`);if(!l)return null;const a=u=>{if(u.source!==l)return;const h=u.data?.type;o&&typeof h=="string"&&!o.includes(h)||(l.close(),window.removeEventListener("message",a))};window.addEventListener("message",a);const c=setInterval(()=>{l.closed&&(window.removeEventListener("message",a),clearInterval(c))},500);return l}function Id(s){const e=Date.now()-s.getTime(),t=Math.round(e/1e3);if(t<5)return"just now";if(t<60)return`${t}s ago`;const r=Math.round(t/60);if(r<60)return`${r} min ago`;const o=Math.round(r/60);if(o<24)return`${o} hr ago`;const n=Math.round(o/24);return n===1?"Yesterday":n<7?`${n} d ago`:s.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class Dl extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(e.template?.contentType)return!1;const t=e.content;if(!t)return!1;const r=t.trim().toLowerCase();return r==="chat_initiated"||r==="group created"||r==="file_uploaded"||r==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(o=>r.includes(o)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(i=>i&&i.tagName==="A");if(!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment"))return;const o=this.linkHandlers.some(i=>Fl(r.href,i.match));r.target==="_self"&&!o||t.some(i=>{if(!i||!i.classList)return!1;const l=i.classList;return l.contains("bubble")&&l.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">${zt(Wt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const i=r.externalId??r.id;this.appendMessageElement(r,t.get(i))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;let r=-1;for(let i=e.length-1;i>=0;i--)if(e[i].role==="user"){r=i;break}for(let i=0;i<e.length;i++){const n=e[i];if(n.role==="user"){const o=n.metadata?.attributes?.action;if(o){const l=Ph(o);if(o.message_id&&t.set(o.message_id,l),Object.keys(l).length>0)for(let a=i-1;a>=0;a--){const c=e[a];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,l);break}}}}if(n.role!=="user"&&n.template?.contentType&&i<r){const o=n.externalId??n.id;t.has(o)||t.set(o,{})}}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=zt(Wt(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 i=document.createElement("div");i.classList.add("bubble",e.role);const o=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?i.classList.add("attachment-only"):i.textContent=e.content:o?e.content&&(i.innerHTML=zt(Wt(e.content))):(i.innerHTML=zt(Wt(e.content||"")),e.status==="streaming"&&i.classList.add("streaming-cursor"));let l=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"),l=d):i.appendChild(d)}const a=e.template?.templateId==="7";if(e.attachments?.length&&!a){const d=document.createElement("div");d.classList.add("attachments");for(const p of e.attachments){const g=document.createElement("aikaara-template-renderer");g.setAttribute("content-type","300"),g.setAttribute("template-id","7");const f={elements:[{description:p.fileName,action:{url:p.fileUrl,type:"link",isDeepLink:!0}}]};g.setPayload(f,""),d.appendChild(g)}i.appendChild(d)}const u=!(i.childNodes.length===0&&(i.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(i),l&&r.appendChild(l),(u||l)&&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 Ch(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(g=>$l(e,g.match)),i=r?.target??"iframe";if(i==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(i==="popup"){Dl(e);return}const n=this.getOrCreateModal(),o=r?.title??t??"Link";if(i==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,o));return}const l=Oh(e),a=ql(r.fetch.url,l),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const g=await this.getLinkBearer(u);g&&(c.authorization=`Bearer ${g}`)}const d={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",d.body=JSON.stringify(Eo(r.fetch.body,l)));let p=null;try{const g=await fetch(a,d);g.ok&&(p=await g.json().catch(()=>null))}catch(g){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",g)}requestAnimationFrame(()=>{n.showElement?.(r.render,o,g=>{const f=r.props??{setData:p};for(const[b,w]of Object.entries(f)){const m=g[b];typeof m=="function"&&m.call(g,w)}const y=b=>{const w=b,m=w.detail?.message??w.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...w.detail?.attributes??{}}},bubbles:!0,composed:!0})))};g.addEventListener("aikaara-plan-select",y),g.addEventListener("aikaara-select",y)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function Ph(s){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,i]of Object.entries(s))e.has(r)||(Array.isArray(i)&&i.every(n=>typeof n=="string")?t[r]=i:typeof i=="string"&&(t[r]=[i]));return t}function $l(s,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(s)}function Oh(s){try{const e=new URL(s),t={};return e.searchParams.forEach((r,i)=>{t[i]=r}),t}catch{return{}}}function ql(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Eo(s,e){if(typeof s=="string")return ql(s,e);if(Array.isArray(s))return s.map(t=>Eo(t,e));if(s&&typeof s=="object"){const t={};for(const[r,i]of Object.entries(s))t[r]=Eo(i,e);return t}return s}class Hl 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")||"",i=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",o=this.getAttribute("template-id")||"",l=this.getAttribute("inner-message")||"",a=e==="user"?document.createTextNode(t).textContent||"":zt(Wt(t)),c=e==="user"&&i,u=i==="sending"?"○":i==="sent"?"✓":i==="delivered"||i==="read"?"✓✓":"";this.shadow.innerHTML=`
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">${zt(Wt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const o=r.externalId??r.id;this.appendMessageElement(r,t.get(o))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;let r=-1;for(let o=e.length-1;o>=0;o--)if(e[o].role==="user"){r=o;break}for(let o=0;o<e.length;o++){const n=e[o];if(n.role==="user"){const i=n.metadata?.attributes?.action;if(i){const l=Td(i);if(i.message_id&&t.set(i.message_id,l),Object.keys(l).length>0)for(let a=o-1;a>=0;a--){const c=e[a];if(c.role!=="user"&&c.template?.contentType){const u=c.externalId??c.id,h=t.get(u);(!h||Object.keys(h).length===0)&&t.set(u,l);break}}}}if(n.role!=="user"&&n.template?.contentType&&o<r){const i=n.externalId??n.id;t.has(i)||t.set(i,{})}}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=zt(Wt(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 h=document.createElement("div");h.classList.add("message-wrap","system"),h.dataset.messageId=e.id,e.externalId&&(h.dataset.externalId=e.externalId);const p=document.createElement("aikaara-system-pill");p.setAttribute("text",e.content),h.appendChild(p),this.container.appendChild(h);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const o=document.createElement("div");o.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?o.classList.add("attachment-only"):o.textContent=e.content:i?e.content&&(o.innerHTML=zt(Wt(e.content))):(o.innerHTML=zt(Wt(e.content||"")),e.status==="streaming"&&o.classList.add("streaming-cursor"));let l=null;if(e.template?.contentType){const h=document.createElement("aikaara-template-renderer");h.setAttribute("content-type",e.template.contentType),e.template.templateId&&h.setAttribute("template-id",e.template.templateId);const p=e.externalId??e.id;p&&h.setAttribute("message-id",p),h.setPayload(e.template.payload),t!==void 0&&(h.dataset.consumed="true",Object.keys(t).length>0&&h.setConsumedValues?.(t)),this.templateLayout==="outside"?(h.classList.add("template-outside"),l=h):o.appendChild(h)}const a=e.template?.templateId==="7";if(e.attachments?.length&&!a){const h=document.createElement("div");h.classList.add("attachments");for(const p of e.attachments){const g=document.createElement("aikaara-template-renderer");g.setAttribute("content-type","300"),g.setAttribute("template-id","7");const f={elements:[{description:p.fileName,action:{url:p.fileUrl,type:"link",isDeepLink:!0}}]};g.setPayload(f,""),h.appendChild(g)}o.appendChild(h)}const u=!(o.childNodes.length===0&&(o.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(o),l&&r.appendChild(l),(u||l)&&this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const h=document.createElement("div");if(h.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(h.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]??"",h.appendChild(p)}r.appendChild(h)}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 Id(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(g=>Fl(e,g.match)),o=r?.target??"iframe";if(o==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(o==="popup"){Bl(e);return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(o==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const l=Cd(e),a=$l(r.fetch.url,l),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const g=await this.getLinkBearer(u);g&&(c.authorization=`Bearer ${g}`)}const h={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",h.body=JSON.stringify(Ao(r.fetch.body,l)));let p=null;try{const g=await fetch(a,h);g.ok&&(p=await g.json().catch(()=>null))}catch(g){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",g)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,g=>{const f=r.props??{setData:p};for(const[y,w]of Object.entries(f)){const m=g[y];typeof m=="function"&&m.call(g,w)}const b=y=>{const w=y,m=w.detail?.message??w.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...w.detail?.attributes??{}}},bubbles:!0,composed:!0})))};g.addEventListener("aikaara-plan-select",b),g.addEventListener("aikaara-select",b)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function Td(s){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,o]of Object.entries(s))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}function Fl(s,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(s)}function Cd(s){try{const e=new URL(s),t={};return e.searchParams.forEach((r,o)=>{t[o]=r}),t}catch{return{}}}function $l(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Ao(s,e){if(typeof s=="string")return $l(s,e);if(Array.isArray(s))return s.map(t=>Ao(t,e));if(s&&typeof s=="object"){const t={};for(const[r,o]of Object.entries(s))t[r]=Ao(o,e);return t}return s}class ql extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",o=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",l=this.getAttribute("inner-message")||"",a=e==="user"?document.createTextNode(t).textContent||"":zt(Wt(t)),c=e==="user"&&o,u=o==="sending"?"○":o==="sent"?"✓":o==="delivered"||o==="read"?"✓✓":"";this.shadow.innerHTML=`
479
479
  <style>
480
480
  :host { display: flex; flex-direction: column; }
481
481
  :host([role="user"]) { align-items: flex-end; }
@@ -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: ${i==="read"?"var(--aikaara-primary, #6366f1)":"var(--aikaara-text-secondary, #6b7280)"};
517
+ color: ${o==="read"?"var(--aikaara-primary, #6366f1)":"var(--aikaara-text-secondary, #6b7280)"};
518
518
  margin-left: 4px;
519
519
  }
520
520
  .attachments {
@@ -542,8 +542,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
542
542
  <div class="content">${a}</div>
543
543
  ${n?`<aikaara-template-renderer
544
544
  content-type="${n}"
545
- template-id="${o}"
546
- inner-message="${Wl(l)}"
545
+ template-id="${i}"
546
+ inner-message="${Hl(l)}"
547
547
  ></aikaara-template-renderer>`:""}
548
548
  ${this.renderAttachments()}
549
549
  </div>
@@ -552,20 +552,20 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
552
552
  ${r}${c?`<span class="status">${u}</span>`:""}
553
553
  </div>
554
554
  `:""}
555
- `;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,l),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="${Wl(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
556
- 📎 ${Mh(t.fileName)}
557
- </a>`).join("")}</div>`:""}}function Wl(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Mh(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class zl 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")??"",i=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",o=this.getAttribute("send-shape")==="square",l=t?`
555
+ `;const h=this.shadow.querySelector("aikaara-template-renderer");h&&this.templatePayload!==null&&h.setPayload(this.templatePayload,l),h&&h.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="${Hl(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
556
+ 📎 ${Od(t.fileName)}
557
+ </a>`).join("")}</div>`:""}}function Hl(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Od(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Wl extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",o=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",i=this.getAttribute("send-shape")==="square",l=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}"`:""} ${i?"multiple":""} />`:"",a=`
563
+ <input type="file" ${r?`accept="${r}"`:""} ${o?"multiple":""} />`:"",a=`
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"/>
567
567
  </svg>
568
- </button>`,c=o?"border-radius: var(--aikaara-button-radius, 8px);":"border-radius: 50%;";this.shadow.innerHTML=`
568
+ </button>`,c=i?"border-radius: var(--aikaara-button-radius, 8px);":"border-radius: 50%;";this.shadow.innerHTML=`
569
569
  <style>
570
570
  .input-container {
571
571
  display: flex;
@@ -632,7 +632,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
632
632
  ${n?l:""}
633
633
  ${a}
634
634
  </div>
635
- `,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.attachBtn=this.shadow.querySelector(".attach-btn"),this.fileInput=this.shadow.querySelector('input[type="file"]'),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.refreshSendDisabled()}),this.textarea.addEventListener("keydown",u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend()),this.attachBtn?.addEventListener("click",()=>{this._disabled||this._uploading||this.fileInput?.click()}),this.fileInput?.addEventListener("change",()=>{const u=this.fileInput?.files;if(u?.length){for(const d of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:d},bubbles:!0,composed:!0}));this.fileInput&&(this.fileInput.value="")}})}set disabled(e){this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.attachBtn&&(this.attachBtn.disabled=e||this._uploading),this.refreshSendDisabled()}get disabled(){return this._disabled}set uploading(e){this._uploading=e,this.attachBtn&&(this.attachBtn.dataset.uploading=String(e),this.attachBtn.disabled=this._disabled||e)}get uploading(){return this._uploading}focus(){this.textarea?.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.refreshSendDisabled())}refreshSendDisabled(){this.sendBtn&&(this.sendBtn.disabled=this._disabled||this._uploading||!this.textarea.value.trim())}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class Vl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
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 h of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:h},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 zl 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 Gl extends HTMLElement{shadow;bubble;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
669
+ `}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class Vl 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;
@@ -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 Ao=new Map;function Yl(s){const e=Ao.get(s);if(e)return e;const t=new Promise((r,i)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(s)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>i(new Error(`Failed to load ${s}`)),{once:!0}));return}const o=document.createElement("script");o.src=s,o.async=!0,o.crossOrigin="anonymous",o.dataset.aikaaraSrc=s,o.addEventListener("load",()=>{o.dataset.aikaaraReady="1",r()},{once:!0}),o.addEventListener("error",()=>{Ao.delete(s),i(new Error(`Failed to load ${s}`))},{once:!0}),document.head.appendChild(o)});return Ao.set(s,t),t}function Rh(s,e=5e3){return new Promise((t,r)=>{const i=setTimeout(()=>r(new Error(`Custom element <${s}> not registered within ${e}ms`)),e);customElements.whenDefined(s).then(()=>{clearTimeout(i),t()})})}const Lh={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>Mf).then(({registerAikaaraPaymentLink:s})=>s())};function Nh(s){const e=`template:${s}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[s]}class jh 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 i=Dh(t.attributes.action);if(Object.keys(i).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(i))}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 i=localStorage.getItem(`aikaara_form:${r}`);i&&(e=JSON.parse(i))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(i=>{const n=i,o=n.getName?.();o&&r[o]?.length&&n.setPreSelected?.(r[o])})}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=`
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 Io=new Map;function Gl(s){const e=Io.get(s);if(e)return e;const t=new Promise((r,o)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(s)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>o(new Error(`Failed to load ${s}`)),{once:!0}));return}const i=document.createElement("script");i.src=s,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=s,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{Io.delete(s),o(new Error(`Failed to load ${s}`))},{once:!0}),document.head.appendChild(i)});return Io.set(s,t),t}function Pd(s,e=5e3){return new Promise((t,r)=>{const o=setTimeout(()=>r(new Error(`Custom element <${s}> not registered within ${e}ms`)),e);customElements.whenDefined(s).then(()=>{clearTimeout(o),t()})})}const Md={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>Of).then(({registerAikaaraPaymentLink:s})=>s())};function Rd(s){const e=`template:${s}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[s]}class Ld extends HTMLElement{shadow;payloadData=null;innerMessage="";renderGen=0;_consumedValues=null;static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",e=>{const t=e.detail,r=this.getAttribute("message-id");if(r&&t?.attributes?.action){const o=Ud(t.attributes.action);if(Object.keys(o).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(o))}catch{}}this.dataset.consumed="true",this._applyConsumedToChildren()})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}setConsumedValues(e){this._consumedValues=e,this._applyConsumedToChildren()}_applyConsumedToChildren(){let e=this._consumedValues;if(!e){const r=this.getAttribute("message-id");if(r)try{const o=localStorage.getItem(`aikaara_form:${r}`);o&&(e=JSON.parse(o))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(o=>{const n=o,i=n.getName?.();i&&r[i]?.length&&n.setPreSelected?.(r[i])})}this.querySelectorAll("aikaara-submit-action, aikaara-modal-action, aikaara-link-button").forEach(r=>{r.style.display="none"});const t=new Set(["aikaara-option-list","aikaara-submit-action","aikaara-modal-action","aikaara-link-button"]);this.querySelectorAll("*").forEach(r=>{if(t.has(r.tagName.toLowerCase()))return;e&&r.setConsumedValues?.(e),r.dataset.consumed="true"})}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.renderGen+=1,this.shadow.innerHTML=`
747
747
  <style>
748
748
  :host { display: block; }
749
749
  ::slotted(*) { display: block; }
@@ -757,7 +757,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
757
757
  }
758
758
  </style>
759
759
  <slot></slot>
760
- `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Nh(t):void 0,i=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Lh[i];if(n&&!customElements.get(i)?n().then(()=>this.render()).catch(o=>console.warn(`[aikaara-template-renderer] native template ${i} failed to load`,o)):r?.scriptUrl&&!customElements.get(i)&&Yl(r.scriptUrl).then(()=>Rh(i)).then(()=>this.render()).catch(o=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,o)),customElements.get(i)){const o=document.createElement(i);if(r?.props){for(const[l,a]of Object.entries(r.props))if(typeof o[l]=="function")try{o[l](a)}catch(c){console.warn(`[aikaara-template-renderer] props.${l} threw on <${i}>`,c)}}o.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(o),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&o.setConsumedValues?.(this._consumedValues),o.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const o=this.payloadData;if(o.length>0&&o.every(a=>a&&typeof a=="object"&&!Array.isArray(a)&&!("type"in a)&&!("data"in a)&&typeof a.message=="string")){const a=document.createElement("aikaara-option-list");a.setPayload({name:"quick-reply",type:"button",options:o.map(c=>{const u=typeof c.title=="string"?c.title:"",d=c.message;return{label:u||d,value:d}})}),this.appendChild(a);return}for(const a of o)this.mountField(a)}else if(this.payloadData&&typeof this.payloadData=="object"){const o=this.payloadData;typeof o.message=="string"&&(o.okLabel||o.action||o.ok)&&this.mountModal(o)}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 i=document.createElement("aikaara-text-input");i.setPayload(r),this.appendChild(i);return}if(t==="checkbox"||t==="radio"||t==="button"){const i=document.createElement("aikaara-option-list");i.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(i);return}if(t==="submit"){const i=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;i.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(i);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(()=>jf).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:i})=>{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:Bh(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 Uh=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Bh(s){const e={};for(const[t,r]of Object.entries(s))Uh.has(t)||(e[t]=r);return e}function Dh(s){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,i]of Object.entries(s))e.has(r)||(Array.isArray(i)&&i.every(n=>typeof n=="string")?t[r]=i:typeof i=="string"&&(t[r]=[i]));return t}class Fh 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=`
760
+ `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Rd(t):void 0,o=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Md[o];if(n&&!customElements.get(o)?n().then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] native template ${o} failed to load`,i)):r?.scriptUrl&&!customElements.get(o)&&Gl(r.scriptUrl).then(()=>Pd(o)).then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,i)),customElements.get(o)){const i=document.createElement(o);if(r?.props){for(const[l,a]of Object.entries(r.props))if(typeof i[l]=="function")try{i[l](a)}catch(c){console.warn(`[aikaara-template-renderer] props.${l} threw on <${o}>`,c)}}i.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(i),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&i.setConsumedValues?.(this._consumedValues),i.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const i=this.payloadData;if(i.length>0&&i.every(a=>a&&typeof a=="object"&&!Array.isArray(a)&&!("type"in a)&&!("data"in a)&&typeof a.message=="string")){const a=document.createElement("aikaara-option-list");a.setPayload({name:"quick-reply",type:"button",options:i.map(c=>{const u=typeof c.title=="string"?c.title:"",h=c.message;return{label:u||h,value:h}})}),this.appendChild(a);return}for(const a of i)this.mountField(a)}else if(this.payloadData&&typeof this.payloadData=="object"){const i=this.payloadData;typeof i.message=="string"&&(i.okLabel||i.action||i.ok)&&this.mountModal(i)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="text"){const o=document.createElement("aikaara-text-input");o.setPayload(r),this.appendChild(o);return}if(t==="checkbox"||t==="radio"||t==="button"){const o=document.createElement("aikaara-option-list");o.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(o);return}if(t==="submit"){const o=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;o.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(o);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>Lf).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:o})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:jd(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 Nd=new Set(["type","url","name","openLinkInNewTab","orderId"]);function jd(s){const e={};for(const[t,r]of Object.entries(s))Nd.has(t)||(e[t]=r);return e}function Ud(s){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,o]of Object.entries(s))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}class Bd 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">${Jl(e)}</span>
786
- ${t?`<span class="sub">${Jl(t)}</span>`:""}
787
- `}}function Jl(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class $h 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,i=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const o=t[0],l=this.selected.has(o.value),a=this.preSelectedDisabled?"cursor: default; pointer-events: none;":"cursor: pointer;";if(this.shadow.innerHTML=`
785
+ <span class="pill">${Yl(e)}</span>
786
+ ${t?`<span class="sub">${Yl(t)}</span>`:""}
787
+ `}}function Yl(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Dd extends HTMLElement{shadow;data=null;selected=new Set;preSelectedDisabled=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.selected.clear(),this.preSelectedDisabled=!1,this.render()}getName(){return this.data?.name??""}setPreSelected(e){this.selected=new Set(e),this.preSelectedDisabled=!0,this.render()}getValues(){return{name:this.data?.name??"",values:[...this.selected],type:this.data?.type??"checkbox"}}toggle(e){this.data&&(this.data.type==="radio"||this.data.type==="button"?(this.selected.clear(),this.selected.add(e)):this.selected.has(e)?this.selected.delete(e):this.selected.add(e),this.data.type==="button"?this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e,attributes:{action:{[this.data.name]:e}}},bubbles:!0,composed:!0})):this.dispatchEvent(new CustomEvent("option-change",{detail:this.getValues(),bubbles:!0,composed:!0})),this.render())}render(){if(!this.data){this.shadow.innerHTML="";return}const{title:e,options:t,type:r}=this.data,o=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const i=t[0],l=this.selected.has(i.value),a=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 {
@@ -819,7 +819,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
819
819
  .row[aria-checked="true"] .check { opacity: 1; }
820
820
  .text { flex: 1; }
821
821
  </style>
822
- <div class="row" role="checkbox" tabindex="${this.preSelectedDisabled?"-1":"0"}" aria-checked="${l}" aria-disabled="${this.preSelectedDisabled}" data-value="${Io(o.value)}">
822
+ <div class="row" role="checkbox" tabindex="${this.preSelectedDisabled?"-1":"0"}" aria-checked="${l}" aria-disabled="${this.preSelectedDisabled}" data-value="${To(i.value)}">
823
823
  <span class="box" aria-hidden="true">
824
824
  <svg class="check" viewBox="0 0 16 16" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
825
825
  <path d="M3 8 L7 12 L13 4" />
@@ -827,7 +827,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
827
827
  </span>
828
828
  <span class="text">${Rt(e)}</span>
829
829
  </div>
830
- `,!this.preSelectedDisabled){const c=this.shadow.querySelector(".row");if(c){const u=()=>this.toggle(o.value);c.addEventListener("click",u),c.addEventListener("keydown",d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),u())})}}return}if(r==="radio"){const o=this.preSelectedDisabled?"default":"pointer";this.shadow.innerHTML=`
830
+ `,!this.preSelectedDisabled){const c=this.shadow.querySelector(".row");if(c){const u=()=>this.toggle(i.value);c.addEventListener("click",u),c.addEventListener("keydown",h=>{(h.key===" "||h.key==="Enter")&&(h.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 {
@@ -839,7 +839,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
839
839
  .list { display: flex; flex-direction: column; gap: 10px; }
840
840
  .row {
841
841
  display: flex; align-items: center; gap: 10px;
842
- cursor: ${o};
842
+ cursor: ${i};
843
843
  font-family: inherit;
844
844
  font-size: 14px;
845
845
  color: var(--aikaara-option-color, var(--aikaara-text, #1f2937));
@@ -872,7 +872,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
872
872
  ${t.map(l=>{const a=this.selected.has(l.value);return`
873
873
  <div class="row" role="radio" tabindex="${this.preSelectedDisabled?"-1":"0"}"
874
874
  aria-checked="${a}" aria-disabled="${this.preSelectedDisabled}"
875
- data-value="${Io(l.value)}">
875
+ data-value="${To(l.value)}">
876
876
  <span class="circle" aria-hidden="true"><span class="dot"></span></span>
877
877
  <span class="label">${Rt(l.label)}</span>
878
878
  </div>`}).join("")}
@@ -911,17 +911,17 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
911
911
  }
912
912
  </style>
913
913
  ${e?`<div class="title">${Rt(e)}</div>`:""}
914
- <div class="grid" role="${i?"group":"radiogroup"}" aria-label="${Rt(e??this.data.name)}">
915
- ${t.map(o=>`
914
+ <div class="grid" role="${o?"group":"radiogroup"}" aria-label="${Rt(e??this.data.name)}">
915
+ ${t.map(i=>`
916
916
  <button class="opt" type="button"
917
- data-value="${Io(o.value)}"
918
- role="${i?"checkbox":"radio"}"
919
- aria-pressed="${this.selected.has(o.value)}"
917
+ data-value="${To(i.value)}"
918
+ role="${o?"checkbox":"radio"}"
919
+ aria-pressed="${this.selected.has(i.value)}"
920
920
  ${this.preSelectedDisabled?'disabled aria-disabled="true"':""}>
921
- ${Rt(o.label)}
921
+ ${Rt(i.label)}
922
922
  </button>`).join("")}
923
923
  </div>
924
- `,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(o=>{o.addEventListener("click",()=>this.toggle(o.dataset.value||""))})}}function Rt(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function Io(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class qh 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(i=>{(i.validate?.()??!0)||(r=!1)}),r?(t.querySelectorAll("aikaara-option-list").forEach(i=>{const n=i.getValues?.();n?.name&&(e[n.name]=n.type==="radio"?n.values[0]??"":n.values)}),t.querySelectorAll("aikaara-text-input").forEach(i=>{const n=i.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=`
924
+ `,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(i=>{i.addEventListener("click",()=>this.toggle(i.dataset.value||""))})}}function Rt(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function To(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Fd extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;if(!t)return e;let r=!0;return t.querySelectorAll("aikaara-text-input").forEach(o=>{(o.validate?.()??!0)||(r=!1)}),r?(t.querySelectorAll("aikaara-option-list").forEach(o=>{const n=o.getValues?.();n?.name&&(e[n.name]=n.type==="radio"?n.values[0]??"":n.values)}),t.querySelectorAll("aikaara-text-input").forEach(o=>{const n=o.getValues?.();n?.name&&(e[n.name]=n.values[0]??"")}),e):null}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues();if(t===null)return;const r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
925
925
  <style>
926
926
  :host { display: block; margin: 12px 0 4px; }
927
927
  button {
@@ -939,8 +939,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
939
939
  button:hover { background: var(--aikaara-submit-hover-bg, var(--aikaara-primary-hover, #4f46e5)); }
940
940
  button:disabled { opacity: var(--aikaara-submit-disabled-opacity, 0.5); cursor: not-allowed; }
941
941
  </style>
942
- <button type="button">${Hh(e)}</button>
943
- `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Hh(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Wh 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=`
942
+ <button type="button">${$d(e)}</button>
943
+ `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function $d(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class qd 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">${To(this.data.message)}</div>
984
+ <div class="msg">${Co(this.data.message)}</div>
985
985
  <div class="actions">
986
- ${t?`<button class="cancel" type="button">${To(t)}</button>`:""}
987
- <button class="ok" type="button">${To(e)}</button>
986
+ ${t?`<button class="cancel" type="button">${Co(t)}</button>`:""}
987
+ <button class="ok" type="button">${Co(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 To(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class zh 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,i=r?'<span aria-hidden="true" style="color:var(--aikaara-input-error-color,#ef4444);margin-left:2px;">*</span>':"";this.shadow.innerHTML=`
991
+ `,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function Co(s){return String(s).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Hd extends HTMLElement{shadow;data=null;_value="";_error="";_touched=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}getValues(){return{name:this.data?.label??"",values:[this._value],type:"text"}}validate(){this._touched=!0;const e=this._computeError(this._value);return this._error=e,this._updateError(),!e}_computeError(e){if(!this.data)return"";if(this.data.required&&!e.trim())return this.data.validation?.errorText??`${this.data.label} is required`;if(e&&this.data.validation?.regex)try{if(!new RegExp(this.data.validation.regex).test(e))return this.data.validation.errorText}catch{}return""}_updateError(){const e=this.shadow.querySelector(".error");e&&(e.textContent=this._error);const t=this.shadow.querySelector("input");t&&t.setAttribute("aria-invalid",this._error?"true":"false")}render(){if(!this.data){this.shadow.innerHTML="";return}const{label:e,placeholder:t="",required:r=!1}=this.data,o=r?'<span aria-hidden="true" style="color:var(--aikaara-input-error-color,#ef4444);margin-left:2px;">*</span>':"";this.shadow.innerHTML=`
992
992
  <style>
993
993
  :host { display: block; margin-bottom: 12px; }
994
994
  label {
@@ -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>${nr(e)}${i}</label>
1025
+ <label>${nr(e)}${o}</label>
1026
1026
  <input
1027
1027
  type="text"
1028
1028
  placeholder="${nr(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">${nr(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 nr(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Vh 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"),i=this.tokenGetter??r;if(!i){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},o=Object.keys(n).find(c=>c.toLowerCase()==="x-api-key"),l=this.apiKey??this.getAttribute("api-key")??(o?n[o]:void 0);l&&(o&&o!=="X-Api-Key"&&delete n[o],n["X-Api-Key"]=l);const a=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await dc({container:this,slug:e,configBase:this.getAttribute("config-base")??void 0,configHeaders:a,user:{id:t,name:this.getAttribute("user-name")??void 0,departmentId:this.getAttribute("department-id")??void 0,token:i,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 Gh 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 i=!1;this.iframe.addEventListener("load",()=>{i=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{i||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const i=this.shadow.querySelector(".modal-title");i&&(i.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const o=document.createElement(e);n.appendChild(o),requestAnimationFrame(()=>r?.(o))}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=`
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 nr(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Wd extends HTMLElement{static get observedAttributes(){return["slug","user-id","user-name","user-token","department-id","config-base","api-key"]}tokenGetter;apiKey;configHeaders;identity;credentialProviders;mounted=null;mountInflight=null;connectedCallback(){this.style.display||(this.style.display="flex"),this.style.flexDirection||(this.style.flexDirection="column"),this.style.minHeight||(this.style.minHeight="0"),this.tryMount()}disconnectedCallback(){this.mounted?.destroy(),this.mounted=null}attributeChangedCallback(){this.isConnected&&(this.mounted?.destroy(),this.mounted=null,this.tryMount())}async refreshAuth(){await this.mounted?.refreshAuth()}async tryMount(){if(this.mountInflight)return this.mountInflight;const e=this.getAttribute("slug"),t=this.getAttribute("user-id");if(!e||!t)return;const r=this.getAttribute("user-token"),o=this.tokenGetter??r;if(!o){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},i=Object.keys(n).find(c=>c.toLowerCase()==="x-api-key"),l=this.apiKey??this.getAttribute("api-key")??(i?n[i]:void 0);l&&(i&&i!=="X-Api-Key"&&delete n[i],n["X-Api-Key"]=l);const a=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await uc({container:this,slug:e,configBase:this.getAttribute("config-base")??void 0,configHeaders:a,user:{id:t,name:this.getAttribute("user-name")??void 0,departmentId:this.getAttribute("department-id")??void 0,token:o,identity:this.identity,credentialProviders:this.credentialProviders},hooks:{onError:c=>this.dispatchEvent(new CustomEvent("error",{detail:c}))}}),this.dispatchEvent(new CustomEvent("ready",{detail:{requestId:this.mounted.requestId,fullName:this.mounted.fullName}}))}catch(c){this.dispatchEvent(new CustomEvent("error",{detail:c}))}finally{this.mountInflight=null}})(),this.mountInflight}}class zd extends HTMLElement{shadow;root=null;iframe=null;fallbackTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.render()}show(e,t){if(this.root||this.render(),!this.root||!this.iframe)return;const r=this.shadow.querySelector(".modal-title");r&&(r.textContent=t||"Link"),this.swapBody("iframe"),this.iframe.src=e,this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{url:e},bubbles:!0,composed:!0})),this.fallbackTimer&&window.clearTimeout(this.fallbackTimer);let o=!1;this.iframe.addEventListener("load",()=>{o=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{o||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const o=this.shadow.querySelector(".modal-title");o&&(o.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const i=document.createElement(e);n.appendChild(i),requestAnimationFrame(()=>r?.(i))}this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{element:e},bubbles:!0,composed:!0}))}swapBody(e){if(!this.iframe)return;const t=this.shadow.querySelector(".modal-body-element");e==="iframe"?(this.iframe.style.display="",t&&(t.style.display="none")):(this.iframe.style.display="none",t&&(t.style.display=""))}close(){this.root&&(this.root.classList.remove("open"),this.iframe&&(this.iframe.src="about:blank"),this.fallbackTimer&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.dispatchEvent(new CustomEvent("aikaara-link-modal-close",{bubbles:!0,composed:!0})))}render(){this.shadow.innerHTML=`
1035
1035
  <style>
1036
1036
  :host { display: block; }
1037
1037
  .backdrop {
@@ -1081,7 +1081,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1081
1081
  <div class="modal-body-element" style="display:none; flex:1; overflow:auto; padding:18px;"></div>
1082
1082
  </div>
1083
1083
  </div>
1084
- `,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const Kh=[{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"}],Yh=[{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 Jh extends HTMLElement{shadow;data=null;columns=Yh;features=Kh;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=`
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 Vd=[{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"}],Kd=[{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 Gd extends HTMLElement{shadow;data=null;columns=Kd;features=Vd;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>${Co(r.label)}</th>`).join("")}
1140
+ ${e.map(r=>`<th>${Oo(r.label)}</th>`).join("")}
1141
1141
  </tr>
1142
1142
  </thead>
1143
1143
  <tbody>
1144
- ${t.map((r,i)=>`
1144
+ ${t.map((r,o)=>`
1145
1145
  <tr>
1146
- <td>${Co(r.label)}</td>
1147
- ${e.map(n=>n.features[i]?'<td><span class="check">✓</span></td>':'<td><span class="cross">✕</span></td>').join("")}
1146
+ <td>${Oo(r.label)}</td>
1147
+ ${e.map(n=>n.features[o]?'<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 i=this.priceFor(r);return`<td>${i!=null?"₹"+Math.round(i):"—"}</td>`}).join("")}
1151
+ ${e.map(r=>{const o=this.priceFor(r);return`<td>${o!=null?"₹"+Math.round(o):"—"}</td>`}).join("")}
1152
1152
  </tr>
1153
1153
  </tbody>
1154
1154
  </table>
1155
1155
  <div class="actions">
1156
- ${e.map((r,i)=>{const n=this.priceFor(r),o=r.selectLabel.replace("{price}",n!=null?String(Math.round(n)):"—");return`<button class="action" data-col="${i}" type="button">
1157
- <span>${Co(o)}</span>
1156
+ ${e.map((r,o)=>{const n=this.priceFor(r),i=r.selectLabel.replace("{price}",n!=null?String(Math.round(n)):"—");return`<button class="action" data-col="${o}" type="button">
1157
+ <span>${Oo(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 i=Number(r.dataset.col),n=e[i];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function Co(s){return s.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Qh 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("[]"),i=r?t.slice(0,-2):t,n=this.data[i];return r?Array.isArray(n)?n:[]:n??null}handleSectionSubmit(e,t){const r=this.schemas.find(i=>i.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=`
1161
+ `,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const o=Number(r.dataset.col),n=e[o];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function Oo(s){return s.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Yd extends HTMLElement{shadow;root=null;schemas=[];data={};view="picker";activeSectionId=null;keydownHandler=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.renderShell()}disconnectedCallback(){this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null)}open(e){this.root||this.renderShell(),this.root&&(this.schemas=e.schemas,this.data=e.data?{...e.data}:{},e.activeSectionId&&this.schemas.some(t=>t.id===e.activeSectionId)?(this.activeSectionId=e.activeSectionId,this.view="form"):(this.activeSectionId=null,this.view="picker"),this.renderView(),this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("smart-edit-open",{bubbles:!0,composed:!0})))}close(){this.root&&(this.root.classList.remove("open"),this.dispatchEvent(new CustomEvent("smart-edit-close",{bubbles:!0,composed:!0})))}setData(e){this.data={...e},this.view==="form"&&this.mountActiveForm()}openSection(e){this.activeSectionId=e,this.view="form",this.renderView()}backToPicker(){this.activeSectionId=null,this.view="picker",this.renderView()}extractSlice(e){const t=e.dataPath;if(!t)return this.data;const r=t.endsWith("[]"),o=r?t.slice(0,-2):t,n=this.data[o];return r?Array.isArray(n)?n:[]:n??null}handleSectionSubmit(e,t){const r=this.schemas.find(o=>o.id===e);if(r){if(r.dataPath){const n=r.dataPath.endsWith("[]")?r.dataPath.slice(0,-2):r.dataPath;this.data={...this.data,[n]:t}}else t&&typeof t=="object"&&(this.data={...this.data,...t});this.dispatchEvent(new CustomEvent("smart-edit-submit",{detail:{sectionId:e,record:this.data},bubbles:!0,composed:!0})),this.backToPicker()}}handleRecalculate(){this.dispatchEvent(new CustomEvent("smart-edit-recalculate",{detail:{record:this.data},bubbles:!0,composed:!0})),this.close()}renderView(){this.view==="form"?this.renderForm():this.renderPicker()}renderPicker(){const e=this.shadow.querySelector(".modal");if(!e)return;e.classList.remove("view-form"),e.classList.add("view-picker");const t=this.shadow.querySelector(".modal-header");t.innerHTML=`
1162
1162
  <span class="header-spacer"></span>
1163
1163
  <div class="modal-title">Correct Your ITR Details</div>
1164
- <button class="icon-btn close-btn" type="button" aria-label="Close">${Ql}</button>
1165
- `;const r=this.shadow.querySelector(".modal-body"),i=this.schemas.map(o=>`
1166
- <button class="chip" type="button" data-section-id="${Zh(o.id)}">
1167
- <span class="chip-icon">${o.icon??"📄"}</span>
1168
- <span class="chip-label">${Xl(o.title)}</span>
1164
+ <button class="icon-btn close-btn" type="button" aria-label="Close">${Jl}</button>
1165
+ `;const r=this.shadow.querySelector(".modal-body"),o=this.schemas.map(i=>`
1166
+ <button class="chip" type="button" data-section-id="${Qd(i.id)}">
1167
+ <span class="chip-icon">${i.icon??"📄"}</span>
1168
+ <span class="chip-label">${Ql(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">${i}</div>
1178
+ <div class="chip-grid">${o}</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 &amp; Recalculate</button>
1182
- `,this.bindCommon(),r.querySelectorAll(".chip").forEach(o=>{o.addEventListener("click",()=>{const l=o.dataset.sectionId;l&&this.openSection(l)})}),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">${Xh}</button>
1184
- <div class="modal-title">${Xl(t?.title??"Edit")}</div>
1185
- <button class="icon-btn close-btn" type="button" aria-label="Close">${Ql}</button>
1186
- `;const i=this.shadow.querySelector(".modal-footer");i.style.display="none",i.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(i=>i.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",(i=>{const n=i.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=`
1182
+ `,this.bindCommon(),r.querySelectorAll(".chip").forEach(i=>{i.addEventListener("click",()=>{const l=i.dataset.sectionId;l&&this.openSection(l)})}),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">${Jd}</button>
1184
+ <div class="modal-title">${Ql(t?.title??"Edit")}</div>
1185
+ <button class="icon-btn close-btn" type="button" aria-label="Close">${Jl}</button>
1186
+ `;const o=this.shadow.querySelector(".modal-footer");o.style.display="none",o.innerHTML="",this.bindCommon(),r.querySelector(".back-btn")?.addEventListener("click",()=>this.backToPicker()),this.mountActiveForm()}mountActiveForm(){const e=this.shadow.querySelector(".modal-body");if(!e)return;e.innerHTML="";const t=this.schemas.find(o=>o.id===this.activeSectionId);if(!t){e.innerHTML='<div class="empty">Section not found.</div>';return}const r=document.createElement("aikaara-schema-form");r.addEventListener("aikaara-form-submit",(o=>{const n=o.detail;this.handleSectionSubmit(n.sectionId,n.value)})),e.appendChild(r),requestAnimationFrame(()=>{r.setSchema(t),r.setValue(this.extractSlice(t))})}bindCommon(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>this.close())}renderShell(){this.shadow.innerHTML=`
1187
1187
  <style>${this.css()}</style>
1188
1188
  <div class="backdrop" part="backdrop">
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 Ql='<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>',Xh='<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 Zh(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Xl(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class ef extends HTMLElement{shadow;schema=null;value={};errors=new Map;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setSchema(e){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 i=this.getEntries(),n={...i[e]||{}};n[t]=r,i[e]=n,this.isRepeatable()?this.value=i: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=o=>{if(!o)return null;const l=t[o.field];return"equals"in o?l===o.equals:Array.isArray(o.in)?o.in.includes(l):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||[],i=>{if(!this.fieldVisible(i,t)||i.type==="group")return;const n=t[i.id],o=`${r}.${i.id}`;if(i.required&&(n==null||n==="")){this.errors.set(o,"Required");return}if(i.type==="text"&&typeof n=="string"&&(i.pattern&&n&&!new RegExp(i.pattern).test(n)?this.errors.set(o,"Invalid format"):i.maxLength&&n.length>i.maxLength&&this.errors.set(o,`Max ${i.maxLength} characters`)),i.type==="textarea"&&typeof n=="string"&&i.maxLength&&n.length>i.maxLength&&this.errors.set(o,`Max ${i.maxLength} characters`),i.type==="number"&&n!==void 0&&n!==null&&n!==""){const l=typeof n=="number"?n:Number(n),a=i;Number.isNaN(l)?this.errors.set(o,"Must be a number"):a.min!==void 0&&l<a.min?this.errors.set(o,`Minimum ${a.min}`):a.max!==void 0&&l>a.max&&this.errors.set(o,`Maximum ${a.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((i,n)=>this.renderEntry(i,n)).join(""),r=this.isRepeatable()&&e.length<(this.schema.repeatable?.maxCount||1);this.shadow.innerHTML=`
1324
+ `}}const Jl='<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>',Jd='<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 Qd(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ql(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class Xd extends HTMLElement{shadow;schema=null;value={};errors=new Map;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setSchema(e){this.schema=e,this.isRepeatable()&&!Array.isArray(this.value)?this.value=[]:!this.isRepeatable()&&Array.isArray(this.value)&&(this.value={}),this.render()}setValue(e){this.isRepeatable()?(this.value=Array.isArray(e)?[...e]:[],this.value.length===0&&this.value.push({})):this.value=e&&typeof e=="object"?{...e}:{},this.render()}isRepeatable(){return!!this.schema?.repeatable&&this.schema.repeatable.maxCount>0}getEntries(){return this.isRepeatable()?this.value:[this.value]}setEntry(e,t,r){this.setEntryNoRender(e,t,r),this.render()}setEntryNoRender(e,t,r){const o=this.getEntries(),n={...o[e]||{}};n[t]=r,o[e]=n,this.isRepeatable()?this.value=o:this.value=n}addEntry(){if(!this.isRepeatable()||!this.schema?.repeatable)return;const e=this.getEntries();e.length>=this.schema.repeatable.maxCount||(e.push({}),this.value=e,this.render())}removeEntry(e){if(!this.isRepeatable())return;const t=this.getEntries();t.length<=1||(t.splice(e,1),this.value=t,this.render())}fieldVisible(e,t){const r=i=>{if(!i)return null;const l=t[i.field];return"equals"in i?l===i.equals:Array.isArray(i.in)?i.in.includes(l):null};return!(r(e.showWhen)===!1||r(e.hideWhen)===!0)}validate(){return this.errors.clear(),this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],o=>{if(!this.fieldVisible(o,t)||o.type==="group")return;const n=t[o.id],i=`${r}.${o.id}`;if(o.required&&(n==null||n==="")){this.errors.set(i,"Required");return}if(o.type==="text"&&typeof n=="string"&&(o.pattern&&n&&!new RegExp(o.pattern).test(n)?this.errors.set(i,"Invalid format"):o.maxLength&&n.length>o.maxLength&&this.errors.set(i,`Max ${o.maxLength} characters`)),o.type==="textarea"&&typeof n=="string"&&o.maxLength&&n.length>o.maxLength&&this.errors.set(i,`Max ${o.maxLength} characters`),o.type==="number"&&n!==void 0&&n!==null&&n!==""){const l=typeof n=="number"?n:Number(n),a=o;Number.isNaN(l)?this.errors.set(i,"Must be a number"):a.min!==void 0&&l<a.min?this.errors.set(i,`Minimum ${a.min}`):a.max!==void 0&&l>a.max&&this.errors.set(i,`Maximum ${a.max.toLocaleString("en-IN")}`)}})}),this.errors.size===0}walkFields(e,t){for(const r of e)t(r),r.type==="group"&&this.walkFields(r.fields,t)}handleSubmit(){if(!this.schema)return;if(!this.validate()){this.render(),this.shadow.querySelector(".field.has-error")?.scrollIntoView({behavior:"smooth",block:"center"});return}const e=this.isRepeatable()?this.getEntries():this.value;this.dispatchEvent(new CustomEvent("aikaara-form-submit",{detail:{sectionId:this.schema.id,value:e},bubbles:!0,composed:!0}))}render(){if(!this.schema){this.shadow.innerHTML="<style>:host{display:block;}</style>";return}const e=this.getEntries(),t=e.map((o,n)=>this.renderEntry(o,n)).join(""),r=this.isRepeatable()&&e.length<(this.schema.repeatable?.maxCount||1);this.shadow.innerHTML=`
1325
1325
  <style>${this.css()}</style>
1326
1326
  <div class="container">
1327
1327
  <div class="scroll">
@@ -1341,48 +1341,48 @@ 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 i=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>`:"",o=(this.schema?.fields||[]).map(a=>this.renderField(a,e,t)).join("");return`<section class="entry-card">${i?`<div class="entry-header">
1344
+ `,this.bindHandlers()}renderEntry(e,t){const o=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(a=>this.renderField(a,e,t)).join("");return`<section class="entry-card">${o?`<div class="entry-header">
1345
1345
  <span class="entry-label">
1346
1346
  ${this.schema?.entryIcon?`<span class="entry-icon">${this.schema.entryIcon}</span>`:""}
1347
- ${Ze(i)}
1347
+ ${Ze(o)}
1348
1348
  </span>
1349
1349
  ${n}
1350
- </div>`:""}<div class="entry-body">${o}</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("");return`
1350
+ </div>`:""}<div class="entry-body">${i}</div></section>`}renderField(e,t,r){if(!this.fieldVisible(e,t))return"";if(e.type==="group"){const h=e,p=h.fields.map(g=>this.renderField(g,t,r)).join("");return`
1351
1351
  <fieldset class="group">
1352
- ${d.title?`<legend class="group-title">${Ze(d.title)}</legend>`:""}
1353
- ${d.hint?`<div class="group-hint">${Ze(d.hint)}</div>`:""}
1352
+ ${h.title?`<legend class="group-title">${Ze(h.title)}</legend>`:""}
1353
+ ${h.hint?`<div class="group-hint">${Ze(h.hint)}</div>`:""}
1354
1354
  <div class="group-body">${p}</div>
1355
- </fieldset>`}const i=`${r}.${e.id}`,n=this.errors.get(i),o=n?"has-error":"",l=e.required?'<span class="req">*</span>':"",a=e.label?`<label class="field-label" for="${this.fieldHtmlId(e,r)}">${Ze(e.label)} ${l}</label>`:"",c=this.renderInput(e,t,r),u=n?`<div class="field-error">${Ze(n)}</div>`:"";return`
1356
- <div class="field ${o}" data-field-id="${e.id}" data-entry-index="${r}">
1355
+ </fieldset>`}const o=`${r}.${e.id}`,n=this.errors.get(o),i=n?"has-error":"",l=e.required?'<span class="req">*</span>':"",a=e.label?`<label class="field-label" for="${this.fieldHtmlId(e,r)}">${Ze(e.label)} ${l}</label>`:"",c=this.renderInput(e,t,r),u=n?`<div class="field-error">${Ze(n)}</div>`:"";return`
1356
+ <div class="field ${i}" data-field-id="${e.id}" data-entry-index="${r}">
1357
1357
  ${a}
1358
1358
  ${c}
1359
1359
  ${u}
1360
- </div>`}renderInput(e,t,r){const i=t[e.id],n=this.fieldHtmlId(e,r),o=`data-field-id="${e.id}" data-entry-index="${r}"`;if(e.type==="text"){const l=e;return`<input type="text" class="input" id="${n}" ${o} value="${Lt(String(i??""))}" placeholder="${Lt(l.placeholder??"")}" ${l.maxLength?`maxlength="${l.maxLength}"`:""}/>`}if(e.type==="textarea"){const l=e;return`<textarea class="input textarea" id="${n}" ${o} rows="${l.rows??4}" placeholder="${Lt(l.placeholder??"")}" ${l.maxLength?`maxlength="${l.maxLength}"`:""}>${Ze(String(i??""))}</textarea>`}if(e.type==="number"){const l=e;return`
1360
+ </div>`}renderInput(e,t,r){const o=t[e.id],n=this.fieldHtmlId(e,r),i=`data-field-id="${e.id}" data-entry-index="${r}"`;if(e.type==="text"){const l=e;return`<input type="text" class="input" id="${n}" ${i} value="${Lt(String(o??""))}" placeholder="${Lt(l.placeholder??"")}" ${l.maxLength?`maxlength="${l.maxLength}"`:""}/>`}if(e.type==="textarea"){const l=e;return`<textarea class="input textarea" id="${n}" ${i} rows="${l.rows??4}" placeholder="${Lt(l.placeholder??"")}" ${l.maxLength?`maxlength="${l.maxLength}"`:""}>${Ze(String(o??""))}</textarea>`}if(e.type==="number"){const l=e;return`
1361
1361
  <div class="input-with-prefix">
1362
1362
  ${l.currency?`<span class="prefix">${Ze(l.currency)}</span>`:""}
1363
- <input type="number" class="input" id="${n}" ${o} value="${Lt(String(i??""))}" placeholder="${Lt(l.placeholder??"")}" ${l.min!==void 0?`min="${l.min}"`:""} ${l.max!==void 0?`max="${l.max}"`:""}/>
1364
- </div>`}if(e.type==="date")return`<input type="date" class="input" id="${n}" ${o} value="${Lt(String(i??""))}"/>`;if(e.type==="radio")return`
1363
+ <input type="number" class="input" id="${n}" ${i} value="${Lt(String(o??""))}" placeholder="${Lt(l.placeholder??"")}" ${l.min!==void 0?`min="${l.min}"`:""} ${l.max!==void 0?`max="${l.max}"`:""}/>
1364
+ </div>`}if(e.type==="date")return`<input type="date" class="input" id="${n}" ${i} value="${Lt(String(o??""))}"/>`;if(e.type==="radio")return`
1365
1365
  <div class="radio-group">
1366
- ${e.options.map(a=>{const c=i===a.value?"checked":"",u=`${n}-${a.value}`;return`
1366
+ ${e.options.map(a=>{const c=o===a.value?"checked":"",u=`${n}-${a.value}`;return`
1367
1367
  <label class="radio-item ${c?"selected":""}" for="${u}">
1368
- <input type="radio" id="${u}" ${o} name="${n}" value="${Lt(a.value)}" ${c}/>
1368
+ <input type="radio" id="${u}" ${i} name="${n}" value="${Lt(a.value)}" ${c}/>
1369
1369
  <span class="radio-label">${Ze(a.label)}</span>
1370
1370
  </label>`}).join("")}
1371
- </div>`;if(e.type==="yes-no"){const l=i===!0?"checked":"",a=i===!1?"checked":"";return`
1371
+ </div>`;if(e.type==="yes-no"){const l=o===!0?"checked":"",a=o===!1?"checked":"";return`
1372
1372
  <div class="radio-group">
1373
1373
  <label class="radio-item ${l?"selected":""}">
1374
- <input type="radio" ${o} name="${n}" value="true" ${l}/>
1374
+ <input type="radio" ${i} name="${n}" value="true" ${l}/>
1375
1375
  <span class="radio-label">Yes</span>
1376
1376
  </label>
1377
1377
  <label class="radio-item ${a?"selected":""}">
1378
- <input type="radio" ${o} name="${n}" value="false" ${a}/>
1378
+ <input type="radio" ${i} name="${n}" value="false" ${a}/>
1379
1379
  <span class="radio-label">No</span>
1380
1380
  </label>
1381
1381
  </div>`}return e.type==="checkbox"?`
1382
1382
  <label class="checkbox-item">
1383
- <input type="checkbox" id="${n}" ${o} ${i===!0?"checked":""}/>
1383
+ <input type="checkbox" id="${n}" ${i} ${o===!0?"checked":""}/>
1384
1384
  <span class="checkbox-label">${Ze(e.label??"")}</span>
1385
- </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,i=Number(t.dataset.entryIndex||0),o=t.type==="radio"||t.type==="checkbox"?"change":"input";t.addEventListener(o,()=>{let l;t.type==="checkbox"?l=t.checked:t.type==="radio"?t.value==="true"?l=!0:t.value==="false"?l=!1:l=t.value:t.type==="number"?l=t.value===""?null:Number(t.value):l=t.value,o==="input"?this.setEntryNoRender(i,r,l):this.setEntry(i,r,l)})}),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="remove-entry"]').forEach(e=>{e.addEventListener("click",()=>{const t=Number(e.dataset.entryIndex||0);this.removeEntry(t)})})}css(){return`
1385
+ </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,o=Number(t.dataset.entryIndex||0),i=t.type==="radio"||t.type==="checkbox"?"change":"input";t.addEventListener(i,()=>{let l;t.type==="checkbox"?l=t.checked:t.type==="radio"?t.value==="true"?l=!0:t.value==="false"?l=!1:l=t.value:t.type==="number"?l=t.value===""?null:Number(t.value):l=t.value,i==="input"?this.setEntryNoRender(o,r,l):this.setEntry(o,r,l)})}),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="remove-entry"]').forEach(e=>{e.addEventListener("click",()=>{const t=Number(e.dataset.entryIndex||0);this.removeEntry(t)})})}css(){return`
1386
1386
  /* Pure-flex height chain — no percentage heights, which do not
1387
1387
  resolve reliably through a max-height-only flex ancestor. The
1388
1388
  modal makes this element a flex item (flex:1; min-height:0); we
@@ -1561,7 +1561,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1561
1561
  }
1562
1562
  .save-btn:hover { filter: brightness(1.07); }
1563
1563
  .save-btn:active { filter: brightness(0.95); }
1564
- `}}function Lt(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ze(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Po(){const s=[["aikaara-chat-widget",Nl],["aikaara-chat-bubble",jl],["aikaara-chat-header",Ul],["aikaara-message-list",Fl],["aikaara-message-bubble",Hl],["aikaara-chat-input",zl],["aikaara-typing-indicator",Vl],["aikaara-streaming-message",Gl],["aikaara-error-banner",Kl],["aikaara-template-renderer",jh],["aikaara-system-pill",Fh],["aikaara-option-list",$h],["aikaara-submit-action",qh],["aikaara-modal-action",Wh],["aikaara-text-input",zh],["aikaara-chat",Vh],["aikaara-link-modal",Gh],["aikaara-compare-plans",Jh],["aikaara-smart-edit-modal",Qh],["aikaara-schema-form",ef]];for(const[e,t]of s)customElements.get(e)||customElements.define(e,t)}Po();function Yr(s,e,t=""){if(!e)return t;const r=e.split(".");let i=s;for(const n of r)if(i&&typeof i=="object"&&n in i)i=i[n];else return t;return typeof i=="string"?i:t}function Zl(s){try{const e=s.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Vt(s){return typeof s=="function"?await s():s}class ec{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=Zl(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Vt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",i={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",o={method:n,headers:i};n==="POST"&&(i["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const l=await fetch(this.descriptor.endpoint,o);if(!l.ok){const w=await l.text().catch(()=>"");throw new Error(`Session auth failed: ${l.status} ${w.slice(0,200)}`)}const a=await l.json().catch(()=>({})),c=Yr(a,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=Yr(a,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||p||"",f=Yr(a,this.descriptor.fullNamePath??"data.fullName"),y=Yr(a,this.descriptor.userPath??"data.userId"),b=Zl(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:f,userId:y,expiresAt:b},this.cache}}async function tc(s){const e={};for(const t of s.spec){const r=await tf(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 tf(s,e){const t=s.key??s.name;switch(s.source){case"cookie":return rf(t);case"localStorage":return Jr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Jr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Jr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Jr(()=>document.querySelector(`meta[name="${nf(t)}"]`)?.content??void 0);case"callback":{const r=e?.[s.name];if(!r)return;const i=await r();return typeof i=="string"?i:void 0}default:return}}function rf(s){if(typeof document>"u")return;const e=encodeURIComponent(s),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===s||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function Jr(s){try{return s()}catch{return}}function nf(s){return s.replace(/["\\]/g,"\\$&")}const of=1800;class rc{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await tc({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const i=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!i)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(i,{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 l=(await n.json().catch(()=>({}))).user??{},a=String(l.ext_uid??l.extUid??""),c=String(l.token??l.user_token??l.userToken??"");if(!a)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:l.id,extUid:a,userToken:c,email:typeof l.email=="string"?l.email:void 0,displayName:typeof l.display_name=="string"?l.display_name:typeof l.displayName=="string"?l.displayName:void 0,properties:l.properties&&typeof l.properties=="object"?l.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??of;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 sf=3e4,af=2e3,lf=100;async function nc(s){const{descriptor:e}=s,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!s.initToken)throw new Qe("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",i=cf(r);if(!i)throw new Qe("query",`?${r}= not present`);return{token:i,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=uf(r);if(!i)throw new Qe("hash",`#${r}= not present`);return{token:i,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",i=typeof t.key=="string"&&t.key?t.key:"token",n=mf(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:sf;return{token:await pf({type:r,key:i,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Qe("cookie","cookie.name not configured");const i=df(r);if(!i)throw new Qe("cookie",`cookie "${r}" not set`);return{token:i,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",i=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!i)throw new Qe("storage","storage.key not configured");const o=hf(r,i,n);if(!o)throw new Qe("storage",`${r}Storage["${i}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Qe("global","global.path not configured");const i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:af,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:lf,o=await ff(r,i,n);if(!o)throw new Qe("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Qe("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class ic{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await nc(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Qe extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function cf(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 uf(s){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(s)??void 0}catch{return}}function df(s){if(typeof document>"u")return;const e=encodeURIComponent(s),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===s||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function hf(s,e,t){if(!(typeof window>"u"))try{const i=(s==="session"?window.sessionStorage:window.localStorage).getItem(e);if(i==null)return;if(!t)return i;let n;try{n=JSON.parse(i)}catch{return i}const o=oc(n,t);return typeof o=="string"?o:void 0}catch{return}}async function ff(s,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const i=oc(window,s);if(typeof i=="string"&&i.length>0)return i;if(typeof i=="function")try{const n=i();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function pf(s){return new Promise((e,t)=>{if(typeof window>"u"){t(new Qe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(i)},i=setTimeout(()=>{r(),t(new Qe("postmsg",`timeout after ${s.timeoutMs}ms`))},s.timeoutMs),n=o=>{if(s.origins.length>0&&!s.origins.includes(o.origin))return;const l=o.data;if(!l||typeof l!="object")return;const a=l;if(s.type&&a.type!==s.type)return;const c=a[s.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function mf(s){return s?s.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function oc(s,e){if(!e)return s;const t=e.split(".").filter(Boolean);let r=s;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function gf(){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 yf="aikaara_chat:requestId";function Oo(s,e,t){const r=`${yf}:${s}:${e}`;return t?`${r}:${t}`:r}function sc(s,e,t){try{return localStorage.getItem(Oo(s,e,t))}catch{return null}}function bf(s,e,t,r){try{localStorage.setItem(Oo(s,e,r),t)}catch{}}function vf(s,e,t){try{localStorage.removeItem(Oo(s,e,t))}catch{}}async function Mo(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 i={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(i[u]=d);typeof e.serviceType=="string"&&(i.serviceType=e.serviceType),typeof e.userType=="string"&&(i.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,p)=>p in i?i[p]:""),o=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(o);if(u&&typeof u=="object"){const d={};for(const[p,g]of Object.entries(u))d[p]=o(g);return d}return u},l=await Vt(e.sessionToken),a={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const d=r[u],p=n(d.url),g=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}",l)}const y={method:g,headers:f};d.body&&(f["content-type"]="application/json",y.body=JSON.stringify(o(d.body)));let b=0,w="",m=0,_=null;for(;;)try{const x=await fetch(p,y);if(x.ok){_=x;break}if(b=x.status,w=await x.text().catch(()=>""),m<c.length&&_f(b,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${p} → ${b} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${g} ${p} → ${b} ${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)),a[d.capture.as]=E,i[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:a}}async function wf(s){const e=s.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await Mo(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 _f(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 i=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${i.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function lc(s,e){return s.replace("{projectId}",e).replace("{uuid}",gf().replace(/-/g,""))}function cc(s){const e=s._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>Yl(r)))}async function uc(s){const e={...s.config??(s.configUrl?await ac(s.configUrl,s.configHeaders):{}),...s.overrides??{}};cc(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const i=r?.projectId??"",n=s.identity.userId,o=s.conversationScope||void 0,l=s.forceNewConversation?null:sc(n,i,o),a=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=s.conversationId??l??lc(a,i);(s.conversationId||!l||s.forceNewConversation)&&i&&bf(n,i,c,o);const u=await s.tokenProvider(),d=s.tokenProvider,p=s.historyTokenProvider??d,g=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:s.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...s.identity.departmentId?{departmentId:s.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:s.identity.senderFullname??s.identity.userName,tokenProvider:d}:void 0,f=s.uploadAdapter??(e.uploadEndpoint?bo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),y=s.historyAdapter??(e.historyApiBase?Pl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),b={transport:t,baseUrl:"",userToken:s.userToken??n,conversationId:c,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:s.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:g,tiledeskIdentity:{userId:n,userName:s.identity.userName,departmentId:s.identity.departmentId,senderFullname:s.identity.senderFullname??s.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:f,historyAdapter:y,onError:s.onError,onMessage:s.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(b),b.title&&w.setAttribute("title",b.title),b.primaryColor&&w.setAttribute("primary-color",b.primaryColor),b.display&&w.setAttribute("display",b.display),b.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:b,destroy(){w.remove()}}}function kf(s){if(typeof s!="string")return s;const e=document.querySelector(s);if(!e)throw new Error(`mountFromSlug: container "${s}" not found`);return e}async function dc(s){const e=(s.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(s.slug)}`;let r=null;try{r=await ac(t,s.configHeaders)}catch(I){if(!s.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${s.slug}" — using fallbackConfig.`,I)}const i={...s.fallbackConfig??{},...r??{},...s.overrides??{}};if(cc(i),i.templates&&Object.keys(i.templates).length>0){i.components={...i.components??{}};for(const[I,P]of Object.entries(i.templates)){const O=`template:${I}`;i.components[O]||!P?.scriptUrl||!P?.render||(i.components[O]={kind:"iife-element",scriptUrl:P.scriptUrl,tag:P.render,...P.props?{props:P.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:i.templates,components:i.components,razorpay:i.razorpay,title:i.title,cloud:i.cloud??n.__aikaara_descriptor__?.cloud,upload:i.upload??n.__aikaara_descriptor__?.upload,themeSource:i.themeSource??n.__aikaara_descriptor__?.themeSource,api:i.api,auth:i.auth},!i.auth)throw new Error(`mountFromSlug: widget_configs/${s.slug} descriptor must include "auth" block`);let o=null,l=s.user.id,a=s.user.name,c="",u=s.user.token,d=null;const p=await Vt(s.user.token).catch(()=>""),g=typeof p=="string"&&p.length>0;if(!g&&i.sso?.tokenSource){d=new ic({descriptor:{provider:i.sso.provider,flow:i.sso.flow,skipLogin:i.sso.skipLogin,autoRefresh:i.sso.autoRefresh,tokenSource:i.sso.tokenSource,tokenSourceConfig:i.sso.tokenSourceConfig,fallback:i.sso.fallback,map:i.sso.map},initToken:s.user.partnerToken});const I=await d.get();u=async()=>(await d.get()).token,s.user.identity&&!s.user.identity.partnerToken&&(s.user.identity.partnerToken=I.token)}else if(!g&&i.sso&&i.sso.collect&&i.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(s.slug)}/sso_exchange`;o=await new rc({descriptor:i.sso,providers:s.user.credentialProviders,exchangeUrl:I}).get(),l=o.extUid||l,a=a??o.displayName,c=o.userToken}let f="",y="";if(i.preflight&&i.preflight.length){const I=await Mo(i.preflight,{sessionToken:u,userId:l,projectId:i.tiledesk?.projectId??"",slug:s.slug,identity:s.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const P=f;u=()=>P}I.captured.userId&&(l=I.captured.userId),I.captured.requestId&&(y=I.captured.requestId)}const b=new ec(i.auth,u);if(f){const I=i.tiledesk?.projectId??"",P=I?sc(l,I):null,O=i.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=P??(I?lc(O,I):"");b.prime(f,{requestId:j,fullName:a})}const w=await b.get();l=l||w.userId;const m=w.fullName||a||l;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,getSessionToken:()=>Vt(s.user.token),identity:s.user.identity,slug:s.slug,configBase:e};const _=d&&i.sso?.autoRefresh?async()=>{try{return await d.refresh(),b.reset(),(await b.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=i.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await b.get()).token:await Vt(s.user.token)}`,E=s.hooks?.upload??(x&&x.mode==="presigned-3step"?Cl({...x,authHeader:v}):x&&x.mode==="direct"?bo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await uc({container:kf(s.container),config:i,userToken:c||void 0,identity:{userId:l,userName:m,departmentId:s.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:E,historyAdapter:s.hooks?.history,conversationId:w.requestId||y||void 0,conversationScope:s.conversationScope,onError:s.hooks?.onError,onMessage:s.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await b.get()).token:Vt(s.user.token)});return Object.assign(S,{fullName:m,requestId:w.requestId,descriptor:i,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return _?_():null},async runMethodSelectPreflight(I){const P=i.preflight;return!P||!P.length?{}:P.some(j=>j.trigger==="on-method-select")?(await Mo(P,{sessionToken:u,userId:l,projectId:i.tiledesk?.projectId??"",slug:s.slug,identity:{...s.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}function xf(s){Po();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,i]of Object.entries(t)){const n=s[r];n!=null&&e.setAttribute(i,String(n))}return e.configure(s),document.body.appendChild(e),e}function Sf(){const s=document.querySelector("aikaara-chat-widget");s&&s.remove()}const Ef="https://checkout.razorpay.com/v1/checkout.js";let ir=null;function Qr(){return window}class hc extends HTMLElement{shadow;payloadData=[];message="";paidIdx={};constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}setPayload(e,t){this.payloadData=Array.isArray(e)?e:[],this.message=t??"",this.render()}render(){const e=this.payloadData.filter(r=>!!r&&typeof r=="object"&&r.type==="link"&&typeof r.url=="string"),t=e.map((r,i)=>{const n=r.name||"Open link",o=!!this.paidIdx[i];return`<button class="link${o?" paid":""}" data-i="${i}" type="button"${o?" disabled":""}><span class="lbl">${Af(o?"Paid":n)}</span>`+(o?'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8.5 L7 12 L13 5"/></svg>':'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 11 L11 5 M6 5 H11 V10"/></svg>')+"</button>"}).join("");this.shadow.innerHTML="<style>:host { display:block; margin:6px 0; font-family:inherit; }.bubble { padding:12px 16px; border-radius:14px; background:var(--aikaara-bot-bubble-bg, #d8e5f5); color:var(--aikaara-bot-bubble-text, #1a2845); font-size:14px; line-height:1.55; margin-bottom:10px; }.links { display:flex; flex-direction:column; gap:8px; }.link { display:inline-flex; align-items:center; justify-content:center; gap:8px; padding:11px 22px; border:1.5px solid var(--aikaara-primary, #1849a9); background:var(--aikaara-primary, #1849a9); color:var(--aikaara-primary-contrast, #fff); border-radius:24px; font-size:14px; font-weight:600; cursor:pointer; font-family:inherit; text-decoration:none; transition: filter 120ms; width:150px; align-self:flex-start; }.link:hover:not(:disabled) { filter: brightness(0.94); }.link.paid, .link:disabled { background:#e7f5ec; color:#0e7c3a; border-color:#0e7c3a; cursor:default; }.icon { width:13px; height:13px; }</style>"+(this.message?`<div class="bubble">${this.message}</div>`:"")+`<div class="links">${t}</div>`,this.shadow.querySelectorAll(".link").forEach(r=>{r.addEventListener("click",()=>{if(r.disabled)return;const i=Number(r.dataset.i||0),n=e[i];n&&this.handleClick(i,n)})})}handleClick(e,t){const r=If(t),i=Qr().__aikaara_descriptor__?.razorpay;if(!r||!i?.keyId){Pf(t.url,t.name||"Pay"),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t.name||"link-click",attributes:{action:{type:"link",url:t.url,orderId:r||t.orderId,openedIn:"modal"}}},bubbles:!0,composed:!0}));return}Cf(i.preferredBanksUrl,r,i.preferredBanksMethod,i.preferredBanksHeaders).catch(n=>(console.warn("[payment_link] preferred-banks fetch failed; continuing with default UI",n),[])).then(n=>Tf().then(()=>this.openRazorpay(e,r,i,n))).catch(n=>{console.error("[payment_link] Razorpay launch failed",n)})}openRazorpay(e,t,r,i){const n=Qr(),o=n.__aikaara_runtime__?.identity??{},l={key:r.keyId,order_id:t,name:r.name||n.__aikaara_descriptor__?.title||"Payment",prefill:{},handler:()=>{this.paidIdx[e]=!0,this.render()},modal:{ondismiss:()=>{}}};typeof o.mobile=="string"?l.prefill.contact=o.mobile:typeof o.phone=="string"&&(l.prefill.contact=o.phone),typeof o.email=="string"&&(l.prefill.email=o.email),typeof o.name=="string"?l.prefill.name=o.name:typeof o.userName=="string"&&(l.prefill.name=o.userName),Array.isArray(i)&&i.length&&(l.config={display:{blocks:{utib:{name:"Pay Using Preferred Netbanking",instruments:[{method:"netbanking",banks:i}]}},sequence:["block.utib","netbanking","card","upi"],preferences:{show_default_blocks:!0}}});const a=n.Razorpay;if(typeof a!="function")throw new Error("Razorpay Checkout script not available");const c=new a(l);c.on("payment.failed",u=>{console.warn("[payment_link] payment.failed",u?.error)}),c.open()}}function Af(s){return String(s??"").replace(/[&<>]/g,e=>e==="&"?"&amp;":e==="<"?"&lt;":"&gt;")}function If(s){if(typeof s.orderId=="string"&&s.orderId)return s.orderId;try{const e=new URL(s.url,window.location.origin),t=e.searchParams.get("orderId")||e.searchParams.get("order_id");if(t)return t;if(e.hash&&e.hash.length>1){const r=new URLSearchParams(e.hash.replace(/^#/,"")),i=r.get("orderId")||r.get("order_id");if(i)return i}}catch{}return null}function Tf(){return typeof Qr().Razorpay=="function"?Promise.resolve():ir||(ir=new Promise((s,e)=>{const t=document.querySelector('script[data-aikaara-razorpay="1"]');if(t){t.addEventListener("load",()=>s()),t.addEventListener("error",()=>e(new Error("checkout.js failed to load")));return}const r=document.createElement("script");r.src=Ef,r.async=!0,r.dataset.aikaaraRazorpay="1",r.onload=()=>s(),r.onerror=()=>{ir=null,e(new Error("checkout.js failed to load"))},document.head.appendChild(r)}),ir)}function Cf(s,e,t,r){if(!s)return Promise.resolve([]);const i=String(t||"GET").toUpperCase()==="POST"?"POST":"GET",n=s.includes("{orderId}")?s.replace("{orderId}",encodeURIComponent(e)):s+(s.includes("?")?"&":"?")+"orderId="+encodeURIComponent(e),o=Qr().__aikaara_runtime__??{};return(typeof o.getSessionToken=="function"?o.getSessionToken():typeof o.getChatJwt=="function"?o.getChatJwt():Promise.resolve(null)).then(a=>{const c={Accept:"application/json",...r??{}};a&&(c.Authorization=`Bearer ${a}`);const u={method:i,headers:c,credentials:"omit"};return i==="POST"&&(c["Content-Type"]="application/json",u.body=JSON.stringify({orderId:e})),fetch(n,u)}).then(a=>{if(!a.ok)throw new Error(`preferred-banks ${a.status}`);return a.json()}).then(a=>{const c=a,u=c?.data&&typeof c.data=="object"&&!Array.isArray(c.data)?c.data:null;return(Array.isArray(a)?a:Array.isArray(c?.banks)?c.banks:Array.isArray(c?.data)?c.data:Array.isArray(u?.preferredPaymentBank)?u.preferredPaymentBank:Array.isArray(u?.banks)?u.banks:[]).map(p=>{if(typeof p=="string")return p;if(p&&typeof p=="object"){const g=p;return g.code||g.bankCode||g.bank_code||null}return null}).filter(p=>!!p)})}function Pf(s,e){if(!s)return;let t=document.querySelector("aikaara-link-modal");t||(t=document.createElement("aikaara-link-modal"),document.body.appendChild(t)),typeof t.show=="function"?t.show(s,e):window.open(s,"_blank","noopener,noreferrer")}function Of(){typeof customElements>"u"||customElements.get("aikaara-template-payment-link")||customElements.define("aikaara-template-payment-link",hc)}const Mf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraPaymentLink:hc,registerAikaaraPaymentLink:Of},Symbol.toStringTag,{value:"Module"}));class fc extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
1564
+ `}}function Lt(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ze(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Po(){const s=[["aikaara-chat-widget",Ll],["aikaara-chat-bubble",Nl],["aikaara-chat-header",jl],["aikaara-message-list",Dl],["aikaara-message-bubble",ql],["aikaara-chat-input",Wl],["aikaara-typing-indicator",zl],["aikaara-streaming-message",Vl],["aikaara-error-banner",Kl],["aikaara-template-renderer",Ld],["aikaara-system-pill",Bd],["aikaara-option-list",Dd],["aikaara-submit-action",Fd],["aikaara-modal-action",qd],["aikaara-text-input",Hd],["aikaara-chat",Wd],["aikaara-link-modal",zd],["aikaara-compare-plans",Gd],["aikaara-smart-edit-modal",Yd],["aikaara-schema-form",Xd]];for(const[e,t]of s)customElements.get(e)||customElements.define(e,t)}Po();function Jr(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 Xl(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 Vt(s){return typeof s=="function"?await s():s}class Zl{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=Xl(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 Vt(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 l=await fetch(this.descriptor.endpoint,i);if(!l.ok){const w=await l.text().catch(()=>"");throw new Error(`Session auth failed: ${l.status} ${w.slice(0,200)}`)}const a=await l.json().catch(()=>({})),c=Jr(a,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=Jr(a,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||p||"",f=Jr(a,this.descriptor.fullNamePath??"data.fullName"),b=Jr(a,this.descriptor.userPath??"data.userId"),y=Xl(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:g,fullName:f,userId:b,expiresAt:y},this.cache}}async function ec(s){const e={};for(const t of s.spec){const r=await Zd(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 Zd(s,e){const t=s.key??s.name;switch(s.source){case"cookie":return ef(t);case"localStorage":return Qr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Qr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Qr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Qr(()=>document.querySelector(`meta[name="${tf(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 ef(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 Qr(s){try{return s()}catch{return}}function tf(s){return s.replace(/["\\]/g,"\\$&")}const rf=1800;class tc{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 ec({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 l=(await n.json().catch(()=>({}))).user??{},a=String(l.ext_uid??l.extUid??""),c=String(l.token??l.user_token??l.userToken??"");if(!a)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:l.id,extUid:a,userToken:c,email:typeof l.email=="string"?l.email:void 0,displayName:typeof l.display_name=="string"?l.display_name:typeof l.displayName=="string"?l.displayName:void 0,properties:l.properties&&typeof l.properties=="object"?l.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??rf;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 nf=3e4,of=2e3,sf=100;async function rc(s){const{descriptor:e}=s,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!s.initToken)throw new Qe("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=af(r);if(!o)throw new Qe("query",`?${r}= not present`);return{token:o,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=lf(r);if(!o)throw new Qe("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=ff(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:nf;return{token:await df({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 Qe("cookie","cookie.name not configured");const o=cf(r);if(!o)throw new Qe("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 Qe("storage","storage.key not configured");const i=uf(r,o,n);if(!i)throw new Qe("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 Qe("global","global.path not configured");const o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:of,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:sf,i=await hf(r,o,n);if(!i)throw new Qe("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Qe("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class nc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await rc(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 Qe extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function af(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 lf(s){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(s)??void 0}catch{return}}function cf(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 uf(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=ic(n,t);return typeof i=="string"?i:void 0}catch{return}}async function hf(s,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const o=ic(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 df(s){return new Promise((e,t)=>{if(typeof window>"u"){t(new Qe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(o)},o=setTimeout(()=>{r(),t(new Qe("postmsg",`timeout after ${s.timeoutMs}ms`))},s.timeoutMs),n=i=>{if(s.origins.length>0&&!s.origins.includes(i.origin))return;const l=i.data;if(!l||typeof l!="object")return;const a=l;if(s.type&&a.type!==s.type)return;const c=a[s.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function ff(s){return s?s.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function ic(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 pf(){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 mf="aikaara_chat:requestId";function Mo(s,e,t){const r=`${mf}:${s}:${e}`;return t?`${r}:${t}`:r}function oc(s,e,t){try{return localStorage.getItem(Mo(s,e,t))}catch{return null}}function gf(s,e,t,r){try{localStorage.setItem(Mo(s,e,r),t)}catch{}}function bf(s,e,t){try{localStorage.removeItem(Mo(s,e,t))}catch{}}async function Ro(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,g]of Object.entries(u))h[p]=i(g);return h}return u},l=await Vt(e.sessionToken),a={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const h=r[u],p=n(h.url),g=h.method??(h.body?"POST":"GET"),f={accept:"application/json",...h.headers??{}};if((h.authHeader??"session")==="session"){const x=h.authHeaderTemplate??"Bearer {token}";f.authorization=x.replace("{token}",l)}const b={method:g,headers:f};h.body&&(f["content-type"]="application/json",b.body=JSON.stringify(i(h.body)));let y=0,w="",m=0,_=null;for(;;)try{const x=await fetch(p,b);if(x.ok){_=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&vf(y,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${p} → ${y} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${g} ${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)),a[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:a}}async function yf(s){const e=s.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await Ro(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 vf(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 sc(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 ac(s,e){return s.replace("{projectId}",e).replace("{uuid}",pf().replace(/-/g,""))}function lc(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=>Gl(r)))}async function cc(s){const e={...s.config??(s.configUrl?await sc(s.configUrl,s.configHeaders):{}),...s.overrides??{}};lc(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,l=s.forceNewConversation?null:oc(n,o,i),a=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=s.conversationId??l??ac(a,o);(s.conversationId||!l||s.forceNewConversation)&&o&&gf(n,o,c,i);const u=await s.tokenProvider(),h=s.tokenProvider,p=s.historyTokenProvider??h,g=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:s.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...s.identity.departmentId?{departmentId:s.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:s.identity.senderFullname??s.identity.userName,tokenProvider:h}:void 0,f=s.uploadAdapter??(e.uploadEndpoint?vo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),b=s.historyAdapter??(e.historyApiBase?Pl({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:g,tiledeskIdentity:{userId:n,userName:s.identity.userName,departmentId:s.identity.departmentId,senderFullname:s.identity.senderFullname??s.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:f,historyAdapter:b,onError:s.onError,onMessage:s.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(y),y.title&&w.setAttribute("title",y.title),y.primaryColor&&w.setAttribute("primary-color",y.primaryColor),y.display&&w.setAttribute("display",y.display),y.display==="embed"&&(w.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),s.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function wf(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 uc(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 sc(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(lc(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,l=s.user.id,a=s.user.name,c="",u=s.user.token,h=null;const p=await Vt(s.user.token).catch(()=>""),g=typeof p=="string"&&p.length>0;if(!g&&o.sso?.tokenSource){h=new nc({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(!g&&o.sso&&o.sso.collect&&o.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(s.slug)}/sso_exchange`;i=await new tc({descriptor:o.sso,providers:s.user.credentialProviders,exchangeUrl:I}).get(),l=i.extUid||l,a=a??i.displayName,c=i.userToken}let f="",b="";if(o.preflight&&o.preflight.length){const I=await Ro(o.preflight,{sessionToken:u,userId:l,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:s.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const O=f;u=()=>O}I.captured.userId&&(l=I.captured.userId),I.captured.requestId&&(b=I.captured.requestId)}const y=new Zl(o.auth,u);if(f){const I=o.tiledesk?.projectId??"",O=I?oc(l,I):null,P=o.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=O??(I?ac(P,I):"");y.prime(f,{requestId:j,fullName:a})}const w=await y.get();l=l||w.userId;const m=w.fullName||a||l;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,getSessionToken:()=>Vt(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 Vt(s.user.token)}`,E=s.hooks?.upload??(x&&x.mode==="presigned-3step"?Ol({...x,authHeader:v}):x&&x.mode==="direct"?vo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await cc({container:wf(s.container),config:o,userToken:c||void 0,identity:{userId:l,userName:m,departmentId:s.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:E,historyAdapter:s.hooks?.history,conversationId:w.requestId||b||void 0,conversationScope:s.conversationScope,onError:s.hooks?.onError,onMessage:s.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Vt(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 Ro(O,{sessionToken:u,userId:l,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:{...s.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}function _f(s){Po();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,o]of Object.entries(t)){const n=s[r];n!=null&&e.setAttribute(o,String(n))}return e.configure(s),document.body.appendChild(e),e}function kf(){const s=document.querySelector("aikaara-chat-widget");s&&s.remove()}const xf="https://checkout.razorpay.com/v1/checkout.js";let ir=null;function Xr(){return window}class hc extends HTMLElement{shadow;payloadData=[];message="";paidIdx={};constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}setPayload(e,t){this.payloadData=Array.isArray(e)?e:[],this.message=t??"",this.render()}render(){const e=this.payloadData.filter(r=>!!r&&typeof r=="object"&&r.type==="link"&&typeof r.url=="string"),t=e.map((r,o)=>{const n=r.name||"Open link",i=!!this.paidIdx[o];return`<button class="link${i?" paid":""}" data-i="${o}" type="button"${i?" disabled":""}><span class="lbl">${Sf(i?"Paid":n)}</span>`+(i?'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8.5 L7 12 L13 5"/></svg>':'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 11 L11 5 M6 5 H11 V10"/></svg>')+"</button>"}).join("");this.shadow.innerHTML="<style>:host { display:block; margin:6px 0; font-family:inherit; }.bubble { padding:12px 16px; border-radius:14px; background:var(--aikaara-bot-bubble-bg, #d8e5f5); color:var(--aikaara-bot-bubble-text, #1a2845); font-size:14px; line-height:1.55; margin-bottom:10px; }.links { display:flex; flex-direction:column; gap:8px; }.link { display:inline-flex; align-items:center; justify-content:center; gap:8px; padding:11px 22px; border:1.5px solid var(--aikaara-primary, #1849a9); background:var(--aikaara-primary, #1849a9); color:var(--aikaara-primary-contrast, #fff); border-radius:24px; font-size:14px; font-weight:600; cursor:pointer; font-family:inherit; text-decoration:none; transition: filter 120ms; width:150px; align-self:flex-start; }.link:hover:not(:disabled) { filter: brightness(0.94); }.link.paid, .link:disabled { background:#e7f5ec; color:#0e7c3a; border-color:#0e7c3a; cursor:default; }.icon { width:13px; height:13px; }</style>"+(this.message?`<div class="bubble">${this.message}</div>`:"")+`<div class="links">${t}</div>`,this.shadow.querySelectorAll(".link").forEach(r=>{r.addEventListener("click",()=>{if(r.disabled)return;const o=Number(r.dataset.i||0),n=e[o];n&&this.handleClick(o,n)})})}handleClick(e,t){const r=Ef(t),o=Xr().__aikaara_descriptor__?.razorpay;if(!r||!o?.keyId){Tf(t.url,t.name||"Pay"),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t.name||"link-click",attributes:{action:{type:"link",url:t.url,orderId:r||t.orderId,openedIn:"modal"}}},bubbles:!0,composed:!0}));return}If(o.preferredBanksUrl,r,o.preferredBanksMethod,o.preferredBanksHeaders).catch(n=>(console.warn("[payment_link] preferred-banks fetch failed; continuing with default UI",n),[])).then(n=>Af().then(()=>this.openRazorpay(e,r,o,n))).catch(n=>{console.error("[payment_link] Razorpay launch failed",n)})}openRazorpay(e,t,r,o){const n=Xr(),i=n.__aikaara_runtime__?.identity??{},l={key:r.keyId,order_id:t,name:r.name||n.__aikaara_descriptor__?.title||"Payment",prefill:{},handler:()=>{this.paidIdx[e]=!0,this.render()},modal:{ondismiss:()=>{}}};typeof i.mobile=="string"?l.prefill.contact=i.mobile:typeof i.phone=="string"&&(l.prefill.contact=i.phone),typeof i.email=="string"&&(l.prefill.email=i.email),typeof i.name=="string"?l.prefill.name=i.name:typeof i.userName=="string"&&(l.prefill.name=i.userName),Array.isArray(o)&&o.length&&(l.config={display:{blocks:{utib:{name:"Pay Using Preferred Netbanking",instruments:[{method:"netbanking",banks:o}]}},sequence:["block.utib","netbanking","card","upi"],preferences:{show_default_blocks:!0}}});const a=n.Razorpay;if(typeof a!="function")throw new Error("Razorpay Checkout script not available");const c=new a(l);c.on("payment.failed",u=>{console.warn("[payment_link] payment.failed",u?.error)}),c.open()}}function Sf(s){return String(s??"").replace(/[&<>]/g,e=>e==="&"?"&amp;":e==="<"?"&lt;":"&gt;")}function Ef(s){if(typeof s.orderId=="string"&&s.orderId)return s.orderId;try{const e=new URL(s.url,window.location.origin),t=e.searchParams.get("orderId")||e.searchParams.get("order_id");if(t)return t;if(e.hash&&e.hash.length>1){const r=new URLSearchParams(e.hash.replace(/^#/,"")),o=r.get("orderId")||r.get("order_id");if(o)return o}}catch{}return null}function Af(){return typeof Xr().Razorpay=="function"?Promise.resolve():ir||(ir=new Promise((s,e)=>{const t=document.querySelector('script[data-aikaara-razorpay="1"]');if(t){t.addEventListener("load",()=>s()),t.addEventListener("error",()=>e(new Error("checkout.js failed to load")));return}const r=document.createElement("script");r.src=xf,r.async=!0,r.dataset.aikaaraRazorpay="1",r.onload=()=>s(),r.onerror=()=>{ir=null,e(new Error("checkout.js failed to load"))},document.head.appendChild(r)}),ir)}function If(s,e,t,r){if(!s)return Promise.resolve([]);const o=String(t||"GET").toUpperCase()==="POST"?"POST":"GET",n=s.includes("{orderId}")?s.replace("{orderId}",encodeURIComponent(e)):s+(s.includes("?")?"&":"?")+"orderId="+encodeURIComponent(e),i=Xr().__aikaara_runtime__??{};return(typeof i.getSessionToken=="function"?i.getSessionToken():typeof i.getChatJwt=="function"?i.getChatJwt():Promise.resolve(null)).then(a=>{const c={Accept:"application/json",...r??{}};a&&(c.Authorization=`Bearer ${a}`);const u={method:o,headers:c,credentials:"omit"};return o==="POST"&&(c["Content-Type"]="application/json",u.body=JSON.stringify({orderId:e})),fetch(n,u)}).then(a=>{if(!a.ok)throw new Error(`preferred-banks ${a.status}`);return a.json()}).then(a=>{const c=a,u=c?.data&&typeof c.data=="object"&&!Array.isArray(c.data)?c.data:null;return(Array.isArray(a)?a:Array.isArray(c?.banks)?c.banks:Array.isArray(c?.data)?c.data:Array.isArray(u?.preferredPaymentBank)?u.preferredPaymentBank:Array.isArray(u?.banks)?u.banks:[]).map(p=>{if(typeof p=="string")return p;if(p&&typeof p=="object"){const g=p;return g.code||g.bankCode||g.bank_code||null}return null}).filter(p=>!!p)})}function Tf(s,e){if(!s)return;let t=document.querySelector("aikaara-link-modal");t||(t=document.createElement("aikaara-link-modal"),document.body.appendChild(t)),typeof t.show=="function"?t.show(s,e):window.open(s,"_blank","noopener,noreferrer")}function Cf(){typeof customElements>"u"||customElements.get("aikaara-template-payment-link")||customElements.define("aikaara-template-payment-link",hc)}const Of=Object.freeze(Object.defineProperty({__proto__:null,AikaaraPaymentLink:hc,registerAikaaraPaymentLink:Cf},Symbol.toStringTag,{value:"Module"}));class dc extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
1565
1565
  <style>
1566
1566
  :host { display: block; margin-top: 8px; }
1567
1567
  button {
@@ -1582,7 +1582,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1582
1582
  button[disabled] { opacity: 0.5; cursor: not-allowed; }
1583
1583
  </style>
1584
1584
  <button type="button" ${e?"":"disabled"}>
1585
- ${Rf(e?.name??"Open")}
1585
+ ${Pf(e?.name??"Open")}
1586
1586
  <span aria-hidden="true">↗</span>
1587
1587
  </button>
1588
- `,this.shadow.querySelector("button")?.addEventListener("click",()=>this.handleClick())}handleClick(){if(!this.payload)return;const{url:e,name:t,openLinkInNewTab:r,openInPopup:i,orderId:n,extra:o,messageId:l}=this.payload,a=i?"popup":r?"tab":"modal",c=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:n,openedIn:a,extra:o,messageId:l},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(c))if(i)Dl(e);else if(r)window.open(e,"_blank","noopener,noreferrer");else{const d=Lf();requestAnimationFrame(()=>d?.show?.(e,t))}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t,attributes:{action:{type:"link",url:e,orderId:n,openedIn:a,...o??{}},...l?{message_id:l}:{}}},bubbles:!0,composed:!0}))}}function Rf(s){return s.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Lf(){if(typeof document>"u")return null;let s=document.querySelector("aikaara-link-modal");if(!s){const e=document.createElement("aikaara-link-modal");document.body.appendChild(e),s=e}return s}function Nf(){typeof customElements>"u"||customElements.get("aikaara-link-button")||customElements.define("aikaara-link-button",fc)}const jf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraLinkButton:fc,registerAikaaraLinkButton:Nf},Symbol.toStringTag,{value:"Module"}));return Ce.ActionCableClient=en,Ce.AikaaraChatBubble=jl,Ce.AikaaraChatClient=Il,Ce.AikaaraChatHeader=Ul,Ce.AikaaraChatInput=zl,Ce.AikaaraChatWidget=Nl,Ce.AikaaraErrorBanner=Kl,Ce.AikaaraMessageBubble=Hl,Ce.AikaaraMessageList=Fl,Ce.AikaaraStreamingMessage=Gl,Ce.AikaaraTypingIndicator=Vl,Ce.ApiClient=Do,Ce.ChannelSubscription=No,Ce.ConnectionManager=Bo,Ce.ConversationManager=zo,Ce.EventEmitter=ur,Ce.FormBridge=Gd,Ce.MessageStore=Fo,Ce.SessionAuthAdapter=ec,Ce.SsoExchangeAdapter=rc,Ce.TiledeskTransport=kl,Ce.TokenDiscoveryError=Qe,Ce.TokenDiscoveryReader=ic,Ce.clearPersistedConversationId=vf,Ce.collectSsoCredentials=tc,Ce.createFetchUploadAdapter=bo,Ce.createPresigned3StepUploadAdapter=Cl,Ce.createTiledeskHistoryAdapter=Pl,Ce.discoverToken=nc,Ce.extractTiledeskFileEnvelope=El,Ce.inferTiledeskRole=Sl,Ce.isTiledeskSelfEcho=xl,Ce.mount=xf,Ce.mountFromSlug=dc,Ce.mountTenantWidget=uc,Ce.parseTiledeskTemplate=go,Ce.registerComponents=Po,Ce.runMethodSelectPreflight=wf,Ce.unmount=Sf,Object.defineProperty(Ce,Symbol.toStringTag,{value:"Module"}),Ce})({});
1588
+ `,this.shadow.querySelector("button")?.addEventListener("click",()=>this.handleClick())}handleClick(){if(!this.payload)return;const{url:e,name:t,openLinkInNewTab:r,openInPopup:o,orderId:n,extra:i,messageId:l}=this.payload,a=o?"popup":r?"tab":"modal",c=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:n,openedIn:a,extra:i,messageId:l},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(c))if(o)Bl(e);else if(r)window.open(e,"_blank","noopener,noreferrer");else{const h=Mf();requestAnimationFrame(()=>h?.show?.(e,t))}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t,attributes:{action:{type:"link",url:e,orderId:n,openedIn:a,...i??{}},...l?{message_id:l}:{}}},bubbles:!0,composed:!0}))}}function Pf(s){return s.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Mf(){if(typeof document>"u")return null;let s=document.querySelector("aikaara-link-modal");if(!s){const e=document.createElement("aikaara-link-modal");document.body.appendChild(e),s=e}return s}function Rf(){typeof customElements>"u"||customElements.get("aikaara-link-button")||customElements.define("aikaara-link-button",dc)}const Lf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraLinkButton:dc,registerAikaaraLinkButton:Rf},Symbol.toStringTag,{value:"Module"}));return Oe.ActionCableClient=tn,Oe.AikaaraChatBubble=Nl,Oe.AikaaraChatClient=Tl,Oe.AikaaraChatHeader=jl,Oe.AikaaraChatInput=Wl,Oe.AikaaraChatWidget=Ll,Oe.AikaaraErrorBanner=Kl,Oe.AikaaraMessageBubble=ql,Oe.AikaaraMessageList=Dl,Oe.AikaaraStreamingMessage=Vl,Oe.AikaaraTypingIndicator=zl,Oe.ApiClient=Fo,Oe.ChannelSubscription=jo,Oe.ConnectionManager=Do,Oe.ConversationManager=Vo,Oe.EventEmitter=ur,Oe.FormBridge=Vh,Oe.MessageStore=$o,Oe.SessionAuthAdapter=Zl,Oe.SsoExchangeAdapter=tc,Oe.TiledeskTransport=xl,Oe.TokenDiscoveryError=Qe,Oe.TokenDiscoveryReader=nc,Oe.clearPersistedConversationId=bf,Oe.collectSsoCredentials=ec,Oe.createFetchUploadAdapter=vo,Oe.createPresigned3StepUploadAdapter=Ol,Oe.createTiledeskHistoryAdapter=Pl,Oe.discoverToken=rc,Oe.extractTiledeskFileEnvelope=Al,Oe.inferTiledeskRole=El,Oe.isTiledeskSelfEcho=Sl,Oe.mount=_f,Oe.mountFromSlug=uc,Oe.mountTenantWidget=cc,Oe.parseTiledeskTemplate=bo,Oe.registerComponents=Po,Oe.runMethodSelectPreflight=yf,Oe.unmount=kf,Object.defineProperty(Oe,Symbol.toStringTag,{value:"Module"}),Oe})({});