@aikaara/chat-sdk 1.5.30 → 1.5.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AikaaraLinkButton-DJYY1qZX.mjs → AikaaraLinkButton-DcpwQwOm.mjs} +1 -1
- package/dist/{AikaaraLinkButton-DRYE4ZFn.cjs → AikaaraLinkButton-Dzrg6Bni.cjs} +1 -1
- package/dist/{MountTenant-BVgARrQ4.cjs → MountTenant-CGt-9_Jz.cjs} +31 -31
- package/dist/{MountTenant-BAwzMvJH.mjs → MountTenant-D54KyaPo.mjs} +329 -324
- package/dist/cdn/aikaara-chat.iife.js +40 -40
- package/dist/headless.cjs +1 -1
- package/dist/headless.mjs +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +2 -2
- package/dist/ui.cjs +1 -1
- package/dist/ui.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var AikaaraChat=(function(Ne){"use strict";class Yo{identifier;callbacks={};sendFn;constructor(e,t){this.identifier=e,this.sendFn=t}onReceived(e){return this.callbacks.received=e,this}onConnected(e){return this.callbacks.connected=e,this}onDisconnected(e){return this.callbacks.disconnected=e,this}onRejected(e){return this.callbacks.rejected=e,this}perform(e,t={}){this.sendFn({action:e,...t})}_notifyReceived(e){this.callbacks.received?.(e)}_notifyConnected(){this.callbacks.connected?.()}_notifyDisconnected(){this.callbacks.disconnected?.()}_notifyRejected(){this.callbacks.rejected?.()}}class fn{ws=null;url;subscriptions=new Map;welcomePromise=null;pendingSubscriptions=new Map;constructor(e){this.url=e}connect(){return new Promise((e,t)=>{this.welcomePromise={resolve:e,reject:t},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=r=>{this.handleMessage(r)},this.ws.onerror=()=>{const r=new Error("WebSocket connection error");this.welcomePromise?.reject(r),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(r=>r._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(e=>e._notifyDisconnected()),this.subscriptions.clear()}subscribe(e){const t=JSON.stringify(e),r=new Yo(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 _r{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 Wc=1e3,zc=10,Vc=400,Kc=600,Jo="#6366f1",Gc=12,Yc="system-ui, -apple-system, sans-serif",Qo="Type a message...",Jc="bottom-right",Qc="light",Xc={x:20,y:20},mn="aikaara_conversation_id";class Xo extends _r{client;config;state="disconnected";reconnectAttempt=0;reconnectTimer=null;constructor(e){super(),this.config=e;const t=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new fn(t)}async connect(){const e=this.reconnectAttempt>0;this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0,e&&this.emit("reconnected",void 0)}catch(t){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw t}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,t){const r=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(r,"send_message",{content:t})}sendUserEvent(e,t,r,o){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...o&&{source:o}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??zc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Wc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const o=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new fn(o),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const o=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${o}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class Zo{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,o){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=o}setAuthRefreshHook(e){this.refreshHook=e}getAuthToken(){return this.authToken}setAuthToken(e){this.authToken=e}async createConversation(e){const t={conversation:{...e.extUid&&{ext_uid:e.extUid},...e.systemPromptId&&{system_prompt_id:e.systemPromptId},...e.channel&&{channel:e.channel},...e.title&&{title:e.title}}};return this.request("POST","/api/v1/conversations",t)}async updateContext(e,t){const r=this.authToken?`/dashboard/sidekick_conversations/${e}`:`/api/v1/conversations/${e}`;await this.request("PATCH",r,t)}async getMessages(e){return(await this.request("GET",`/api/v1/conversations/${e}/messages`)).map(this.mapMessage)}mapMessage(e){return{id:String(e.id),conversationId:String(e.conversation_id),role:e.role,content:e.content||"",toolCalls:e.tool_calls?.map(t=>({id:t.id,type:t.type,function:t.function})),toolCallResults:e.tool_call_results,tokensInput:e.tokens_input,tokensOutput:e.tokens_output,metadata:e.metadata,createdAt:e.created_at,status:"complete"}}async request(e,t,r){const o=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(o,e,r);if(n.status===401&&this.refreshHook){let a=null;try{a=await this.refreshHook()}catch(l){console.warn("[aikaara-chat-sdk] auth refresh hook threw",l)}a&&(this.authToken=a,n=await this.fetchWithHeaders(o,e,r))}if(!n.ok){const a=await n.text();let l;try{const c=JSON.parse(a);l=c.error||c.message||a}catch{l=a}throw new Error(`API error ${n.status}: ${l}`)}const s=await n.json();if(s&&typeof s=="object"&&"success"in s){if(!s.success)throw new Error(`API error: ${s.message||"Request failed"}`);return s.data}return s}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 es{_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=ts(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=ts(t,r);if(o){const n=xr(o),s=xr(r);!n&&s&&Object.assign(o,r,{id:o.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function ts(i,e,t=15e3){const r=e.attachments&&e.attachments[0],o=(e.metadata??{}).attributes;if(!(!!r||!!(o&&o.fileMessage)))return null;const s=xr(e),a=rs(e),l=ns(e);if(!s&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=i.length-1;u>=0;u--){const d=i[u],f=d.attachments&&d.attachments[0],g=(d.metadata??{}).attributes;if(!(!!f||!!(g&&g.fileMessage)))continue;const b=(d.content||"").trim().toLowerCase();if(b==="file_uploaded"||b==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const y=xr(d);if(s&&y&&s===y)return d;const w=rs(d);if(a&&w&&a===w)return d;const m=ns(d);if(l&&m&&l===m)return d}return null}function rs(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=is(i);if(t)return t}function ns(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(i.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=i.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function xr(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(i.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=is(i);if(r){const o=/[?&]cloudFileId=([^&]+)/.exec(r);if(o)return decodeURIComponent(o[1])}}function is(i){const e=i.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class os{_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(mn)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(mn)}catch{return null}}saveToStorage(e){try{localStorage.setItem(mn,e)}catch{}}}var gn=Object.defineProperty,Zc=Object.getOwnPropertyDescriptor,eu=Object.getOwnPropertyNames,tu=Object.prototype.hasOwnProperty,Qe=(i,e)=>()=>(i&&(e=i(i=0)),e),me=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Ht=(i,e)=>{for(var t in e)gn(i,t,{get:e[t],enumerable:!0})},ru=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of eu(e))!tu.call(i,o)&&o!==t&&gn(i,o,{get:()=>e[o],enumerable:!(r=Zc(e,o))||r.enumerable});return i},je=i=>ru(gn({},"__esModule",{value:!0}),i),le=Qe(()=>{}),De={};Ht(De,{_debugEnd:()=>Qn,_debugProcess:()=>Jn,_events:()=>pi,_eventsCount:()=>fi,_exiting:()=>jn,_fatalExceptions:()=>Kn,_getActiveHandles:()=>hs,_getActiveRequests:()=>ds,_kill:()=>Un,_linkedBinding:()=>cs,_maxListeners:()=>hi,_preload_modules:()=>ci,_rawDebug:()=>Mn,_startProfilerIdleNotifier:()=>Xn,_stopProfilerIdleNotifier:()=>Zn,_tickCallback:()=>Yn,abort:()=>ni,addListener:()=>mi,allowedNodeEnvironmentFlags:()=>zn,arch:()=>vn,argv:()=>_n,argv0:()=>li,assert:()=>ps,binding:()=>In,browser:()=>Ln,chdir:()=>Pn,config:()=>$n,cpuUsage:()=>ir,cwd:()=>Cn,debugPort:()=>ai,default:()=>xi,dlopen:()=>us,domain:()=>Rn,emit:()=>wi,emitWarning:()=>An,env:()=>kn,execArgv:()=>xn,execPath:()=>si,exit:()=>Hn,features:()=>Vn,hasUncaughtExceptionCaptureCallback:()=>fs,hrtime:()=>Sr,kill:()=>qn,listeners:()=>gs,memoryUsage:()=>Fn,moduleLoadList:()=>Nn,nextTick:()=>as,off:()=>bi,on:()=>ft,once:()=>gi,openStdin:()=>Wn,pid:()=>ii,platform:()=>wn,ppid:()=>oi,prependListener:()=>ki,prependOnceListener:()=>_i,reallyExit:()=>Dn,release:()=>On,removeAllListeners:()=>vi,removeListener:()=>yi,resourceUsage:()=>Bn,setSourceMapsEnabled:()=>ui,setUncaughtExceptionCaptureCallback:()=>Gn,stderr:()=>ti,stdin:()=>ri,stdout:()=>ei,title:()=>yn,umask:()=>Tn,uptime:()=>ms,version:()=>Sn,versions:()=>En});function bn(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function nu(){!Mt||!Nt||(Mt=!1,Nt.length?ot=Nt.concat(ot):nr=-1,ot.length&&ss())}function ss(){if(!Mt){var i=setTimeout(nu,0);Mt=!0;for(var e=ot.length;e;){for(Nt=ot,ot=[];++nr<e;)Nt&&Nt[nr].run();nr=-1,e=ot.length}Nt=null,Mt=!1,clearTimeout(i)}}function as(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];ot.push(new ls(i,e)),ot.length===1&&!Mt&&setTimeout(ss,0)}function ls(i,e){this.fun=i,this.array=e}function We(){}function cs(i){bn("_linkedBinding")}function us(i){bn("dlopen")}function ds(){return[]}function hs(){return[]}function ps(i,e){if(!i)throw new Error(e||"assertion error")}function fs(){return!1}function ms(){return mt.now()/1e3}function Sr(i){var e=Math.floor((Date.now()-mt.now())*.001),t=mt.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return i&&(r=r-i[0],o=o-i[1],o<0&&(r--,o+=Er)),[r,o]}function ft(){return xi}function gs(i){return[]}var ot,Mt,Nt,nr,yn,vn,wn,kn,_n,xn,Sn,En,An,In,Tn,Cn,Pn,On,Ln,Mn,Nn,Rn,jn,$n,Dn,Un,ir,Bn,Fn,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ni,ii,oi,si,ai,li,ci,ui,mt,di,Er,hi,pi,fi,mi,gi,bi,yi,vi,wi,ki,_i,xi,iu=Qe(()=>{le(),ue(),ce(),ot=[],Mt=!1,nr=-1,ls.prototype.run=function(){this.fun.apply(null,this.array)},yn="browser",vn="x64",wn="browser",kn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},_n=["/usr/bin/node"],xn=[],Sn="v16.8.0",En={},An=function(i,e){console.warn((e?e+": ":"")+i)},In=function(i){bn("binding")},Tn=function(i){return 0},Cn=function(){return"/"},Pn=function(i){},On={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Ln=!0,Mn=We,Nn=[],Rn={},jn=!1,$n={},Dn=We,Un=We,ir=function(){return{}},Bn=ir,Fn=ir,qn=We,Hn=We,Wn=We,zn={},Vn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Kn=We,Gn=We,Yn=We,Jn=We,Qn=We,Xn=We,Zn=We,ei=void 0,ti=void 0,ri=void 0,ni=We,ii=2,oi=1,si="/bin/usr/node",ai=9229,li="node",ci=[],ui=We,mt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},mt.now===void 0&&(di=Date.now(),mt.timing&&mt.timing.navigationStart&&(di=mt.timing.navigationStart),mt.now=()=>Date.now()-di),Er=1e9,Sr.bigint=function(i){var e=Sr(i);return typeof BigInt>"u"?e[0]*Er+e[1]:BigInt(e[0]*Er)+BigInt(e[1])},hi=10,pi={},fi=0,mi=ft,gi=ft,bi=ft,yi=ft,vi=ft,wi=We,ki=ft,_i=ft,xi={version:Sn,versions:En,arch:vn,platform:wn,browser:Ln,release:On,_rawDebug:Mn,moduleLoadList:Nn,binding:In,_linkedBinding:cs,_events:pi,_eventsCount:fi,_maxListeners:hi,on:ft,addListener:mi,once:gi,off:bi,removeListener:yi,removeAllListeners:vi,emit:wi,prependListener:ki,prependOnceListener:_i,listeners:gs,domain:Rn,_exiting:jn,config:$n,dlopen:us,uptime:ms,_getActiveRequests:ds,_getActiveHandles:hs,reallyExit:Dn,_kill:Un,cpuUsage:ir,resourceUsage:Bn,memoryUsage:Fn,kill:qn,exit:Hn,openStdin:Wn,allowedNodeEnvironmentFlags:zn,assert:ps,features:Vn,_fatalExceptions:Kn,setUncaughtExceptionCaptureCallback:Gn,hasUncaughtExceptionCaptureCallback:fs,emitWarning:An,nextTick:as,_tickCallback:Yn,_debugProcess:Jn,_debugEnd:Qn,_startProfilerIdleNotifier:Xn,_stopProfilerIdleNotifier:Zn,stdout:ei,stdin:ri,stderr:ti,abort:ni,umask:Tn,chdir:Pn,cwd:Cn,env:kn,title:yn,argv:_n,execArgv:xn,pid:ii,ppid:oi,execPath:si,debugPort:ai,hrtime:Sr,argv0:li,_preload_modules:ci,setSourceMapsEnabled:ui}}),ce=Qe(()=>{iu()});function ou(){if(Si)return Wt;Si=!0,Wt.byteLength=a,Wt.toByteArray=c,Wt.fromByteArray=f;for(var i=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,n=r.length;o<n;++o)i[o]=r[o],e[r.charCodeAt(o)]=o;e[45]=62,e[95]=63;function s(g){var h=g.length;if(h%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=g.indexOf("=");b===-1&&(b=h);var y=b===h?0:4-b%4;return[b,y]}function a(g){var h=s(g),b=h[0],y=h[1];return(b+y)*3/4-y}function l(g,h,b){return(h+b)*3/4-b}function c(g){var h,b=s(g),y=b[0],w=b[1],m=new t(l(g,y,w)),k=0,x=w>0?y-4:y,v;for(v=0;v<x;v+=4)h=e[g.charCodeAt(v)]<<18|e[g.charCodeAt(v+1)]<<12|e[g.charCodeAt(v+2)]<<6|e[g.charCodeAt(v+3)],m[k++]=h>>16&255,m[k++]=h>>8&255,m[k++]=h&255;return w===2&&(h=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[k++]=h&255),w===1&&(h=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[k++]=h>>8&255,m[k++]=h&255),m}function u(g){return i[g>>18&63]+i[g>>12&63]+i[g>>6&63]+i[g&63]}function d(g,h,b){for(var y,w=[],m=h;m<b;m+=3)y=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(y));return w.join("")}function f(g){for(var h,b=g.length,y=b%3,w=[],m=16383,k=0,x=b-y;k<x;k+=m)w.push(d(g,k,k+m>x?x:k+m));return y===1?(h=g[b-1],w.push(i[h>>2]+i[h<<4&63]+"==")):y===2&&(h=(g[b-2]<<8)+g[b-1],w.push(i[h>>10]+i[h>>4&63]+i[h<<2&63]+"=")),w.join("")}return Wt}function su(){return Ei?or:(Ei=!0,or.read=function(i,e,t,r,o){var n,s,a=o*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?o-1:0,f=t?-1:1,g=i[e+d];for(d+=f,n=g&(1<<-u)-1,g>>=-u,u+=a;u>0;n=n*256+i[e+d],d+=f,u-=8);for(s=n&(1<<-u)-1,n>>=-u,u+=r;u>0;s=s*256+i[e+d],d+=f,u-=8);if(n===0)n=1-c;else{if(n===l)return s?NaN:(g?-1:1)*(1/0);s=s+Math.pow(2,r),n=n-c}return(g?-1:1)*s*Math.pow(2,n-r)},or.write=function(i,e,t,r,o,n){var s,a,l,c=n*8-o-1,u=(1<<c)-1,d=u>>1,f=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,h=r?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+d>=1?e+=f/l:e+=f*Math.pow(2,1-d),e*l>=2&&(s++,l/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(e*l-1)*Math.pow(2,o),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;i[t+g]=a&255,g+=h,a/=256,o-=8);for(s=s<<o|a,c+=o;c>0;i[t+g]=s&255,g+=h,s/=256,c-=8);i[t+g-h]|=b*128},or)}function au(){if(Ai)return Et;Ai=!0;let i=ou(),e=su(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Et.Buffer=s,Et.SlowBuffer=w,Et.INSPECT_MAX_BYTES=50;let r=2147483647;Et.kMaxLength=r,s.TYPED_ARRAY_SUPPORT=o(),!s.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function o(){try{let p=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(p,_),p.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function n(p){if(p>r)throw new RangeError('The value "'+p+'" is invalid for option "size"');let _=new Uint8Array(p);return Object.setPrototypeOf(_,s.prototype),_}function s(p,_,A){if(typeof p=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(p)}return a(p,_,A)}s.poolSize=8192;function a(p,_,A){if(typeof p=="string")return d(p,_);if(ArrayBuffer.isView(p))return g(p);if(p==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof p);if(z(p,ArrayBuffer)||p&&z(p.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(z(p,SharedArrayBuffer)||p&&z(p.buffer,SharedArrayBuffer)))return h(p,_,A);if(typeof p=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=p.valueOf&&p.valueOf();if(B!=null&&B!==p)return s.from(B,_,A);let Z=b(p);if(Z)return Z;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof p[Symbol.toPrimitive]=="function")return s.from(p[Symbol.toPrimitive]("string"),_,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof p)}s.from=function(p,_,A){return a(p,_,A)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(p){if(typeof p!="number")throw new TypeError('"size" argument must be of type number');if(p<0)throw new RangeError('The value "'+p+'" is invalid for option "size"')}function c(p,_,A){return l(p),p<=0?n(p):_!==void 0?typeof A=="string"?n(p).fill(_,A):n(p).fill(_):n(p)}s.alloc=function(p,_,A){return c(p,_,A)};function u(p){return l(p),n(p<0?0:y(p)|0)}s.allocUnsafe=function(p){return u(p)},s.allocUnsafeSlow=function(p){return u(p)};function d(p,_){if((typeof _!="string"||_==="")&&(_="utf8"),!s.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let A=m(p,_)|0,B=n(A),Z=B.write(p,_);return Z!==A&&(B=B.slice(0,Z)),B}function f(p){let _=p.length<0?0:y(p.length)|0,A=n(_);for(let B=0;B<_;B+=1)A[B]=p[B]&255;return A}function g(p){if(z(p,Uint8Array)){let _=new Uint8Array(p);return h(_.buffer,_.byteOffset,_.byteLength)}return f(p)}function h(p,_,A){if(_<0||p.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(p.byteLength<_+(A||0))throw new RangeError('"length" is outside of buffer bounds');let B;return _===void 0&&A===void 0?B=new Uint8Array(p):A===void 0?B=new Uint8Array(p,_):B=new Uint8Array(p,_,A),Object.setPrototypeOf(B,s.prototype),B}function b(p){if(s.isBuffer(p)){let _=y(p.length)|0,A=n(_);return A.length===0||p.copy(A,0,0,_),A}if(p.length!==void 0)return typeof p.length!="number"||ge(p.length)?n(0):f(p);if(p.type==="Buffer"&&Array.isArray(p.data))return f(p.data)}function y(p){if(p>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return p|0}function w(p){return+p!=p&&(p=0),s.alloc(+p)}s.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==s.prototype},s.compare=function(p,_){if(z(p,Uint8Array)&&(p=s.from(p,p.offset,p.byteLength)),z(_,Uint8Array)&&(_=s.from(_,_.offset,_.byteLength)),!s.isBuffer(p)||!s.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===_)return 0;let A=p.length,B=_.length;for(let Z=0,de=Math.min(A,B);Z<de;++Z)if(p[Z]!==_[Z]){A=p[Z],B=_[Z];break}return A<B?-1:B<A?1:0},s.isEncoding=function(p){switch(String(p).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(p,_){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return s.alloc(0);let A;if(_===void 0)for(_=0,A=0;A<p.length;++A)_+=p[A].length;let B=s.allocUnsafe(_),Z=0;for(A=0;A<p.length;++A){let de=p[A];if(z(de,Uint8Array))Z+de.length>B.length?(s.isBuffer(de)||(de=s.from(de)),de.copy(B,Z)):Uint8Array.prototype.set.call(B,de,Z);else if(s.isBuffer(de))de.copy(B,Z);else throw new TypeError('"list" argument must be an Array of Buffers');Z+=de.length}return B};function m(p,_){if(s.isBuffer(p))return p.length;if(ArrayBuffer.isView(p)||z(p,ArrayBuffer))return p.byteLength;if(typeof p!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof p);let A=p.length,B=arguments.length>2&&arguments[2]===!0;if(!B&&A===0)return 0;let Z=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return H(p).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(p).length;default:if(Z)return B?-1:H(p).length;_=(""+_).toLowerCase(),Z=!0}}s.byteLength=m;function k(p,_,A){let B=!1;if((_===void 0||_<0)&&(_=0),_>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,_>>>=0,A<=_))return"";for(p||(p="utf8");;)switch(p){case"hex":return W(this,_,A);case"utf8":case"utf-8":return q(this,_,A);case"ascii":return oe(this,_,A);case"latin1":case"binary":return j(this,_,A);case"base64":return T(this,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,_,A);default:if(B)throw new TypeError("Unknown encoding: "+p);p=(p+"").toLowerCase(),B=!0}}s.prototype._isBuffer=!0;function x(p,_,A){let B=p[_];p[_]=p[A],p[A]=B}s.prototype.swap16=function(){let p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<p;_+=2)x(this,_,_+1);return this},s.prototype.swap32=function(){let p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<p;_+=4)x(this,_,_+3),x(this,_+1,_+2);return this},s.prototype.swap64=function(){let p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<p;_+=8)x(this,_,_+7),x(this,_+1,_+6),x(this,_+2,_+5),x(this,_+3,_+4);return this},s.prototype.toString=function(){let p=this.length;return p===0?"":arguments.length===0?q(this,0,p):k.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(p){if(!s.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:s.compare(this,p)===0},s.prototype.inspect=function(){let p="",_=Et.INSPECT_MAX_BYTES;return p=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(p+=" ... "),"<Buffer "+p+">"},t&&(s.prototype[t]=s.prototype.inspect),s.prototype.compare=function(p,_,A,B,Z){if(z(p,Uint8Array)&&(p=s.from(p,p.offset,p.byteLength)),!s.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(_===void 0&&(_=0),A===void 0&&(A=p?p.length:0),B===void 0&&(B=0),Z===void 0&&(Z=this.length),_<0||A>p.length||B<0||Z>this.length)throw new RangeError("out of range index");if(B>=Z&&_>=A)return 0;if(B>=Z)return-1;if(_>=A)return 1;if(_>>>=0,A>>>=0,B>>>=0,Z>>>=0,this===p)return 0;let de=Z-B,_e=A-_,K=Math.min(de,_e),ie=this.slice(B,Z),Te=p.slice(_,A);for(let Ce=0;Ce<K;++Ce)if(ie[Ce]!==Te[Ce]){de=ie[Ce],_e=Te[Ce];break}return de<_e?-1:_e<de?1:0};function v(p,_,A,B,Z){if(p.length===0)return-1;if(typeof A=="string"?(B=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,ge(A)&&(A=Z?0:p.length-1),A<0&&(A=p.length+A),A>=p.length){if(Z)return-1;A=p.length-1}else if(A<0)if(Z)A=0;else return-1;if(typeof _=="string"&&(_=s.from(_,B)),s.isBuffer(_))return _.length===0?-1:S(p,_,A,B,Z);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?Z?Uint8Array.prototype.indexOf.call(p,_,A):Uint8Array.prototype.lastIndexOf.call(p,_,A):S(p,[_],A,B,Z);throw new TypeError("val must be string, number or Buffer")}function S(p,_,A,B,Z){let de=1,_e=p.length,K=_.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(p.length<2||_.length<2)return-1;de=2,_e/=2,K/=2,A/=2}function ie(Ce,Le){return de===1?Ce[Le]:Ce.readUInt16BE(Le*de)}let Te;if(Z){let Ce=-1;for(Te=A;Te<_e;Te++)if(ie(p,Te)===ie(_,Ce===-1?0:Te-Ce)){if(Ce===-1&&(Ce=Te),Te-Ce+1===K)return Ce*de}else Ce!==-1&&(Te-=Te-Ce),Ce=-1}else for(A+K>_e&&(A=_e-K),Te=A;Te>=0;Te--){let Ce=!0;for(let Le=0;Le<K;Le++)if(ie(p,Te+Le)!==ie(_,Le)){Ce=!1;break}if(Ce)return Te}return-1}s.prototype.includes=function(p,_,A){return this.indexOf(p,_,A)!==-1},s.prototype.indexOf=function(p,_,A){return v(this,p,_,A,!0)},s.prototype.lastIndexOf=function(p,_,A){return v(this,p,_,A,!1)};function E(p,_,A,B){A=Number(A)||0;let Z=p.length-A;B?(B=Number(B),B>Z&&(B=Z)):B=Z;let de=_.length;B>de/2&&(B=de/2);let _e;for(_e=0;_e<B;++_e){let K=parseInt(_.substr(_e*2,2),16);if(ge(K))return _e;p[A+_e]=K}return _e}function I(p,_,A,B){return ye(H(_,p.length-A),p,A,B)}function P(p,_,A,B){return ye(te(_),p,A,B)}function L(p,_,A,B){return ye(fe(_),p,A,B)}function $(p,_,A,B){return ye(he(_,p.length-A),p,A,B)}s.prototype.write=function(p,_,A,B){if(_===void 0)B="utf8",A=this.length,_=0;else if(A===void 0&&typeof _=="string")B=_,A=this.length,_=0;else if(isFinite(_))_=_>>>0,isFinite(A)?(A=A>>>0,B===void 0&&(B="utf8")):(B=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let Z=this.length-_;if((A===void 0||A>Z)&&(A=Z),p.length>0&&(A<0||_<0)||_>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let de=!1;for(;;)switch(B){case"hex":return E(this,p,_,A);case"utf8":case"utf-8":return I(this,p,_,A);case"ascii":case"latin1":case"binary":return P(this,p,_,A);case"base64":return L(this,p,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return $(this,p,_,A);default:if(de)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),de=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(p,_,A){return _===0&&A===p.length?i.fromByteArray(p):i.fromByteArray(p.slice(_,A))}function q(p,_,A){A=Math.min(p.length,A);let B=[],Z=_;for(;Z<A;){let de=p[Z],_e=null,K=de>239?4:de>223?3:de>191?2:1;if(Z+K<=A){let ie,Te,Ce,Le;switch(K){case 1:de<128&&(_e=de);break;case 2:ie=p[Z+1],(ie&192)===128&&(Le=(de&31)<<6|ie&63,Le>127&&(_e=Le));break;case 3:ie=p[Z+1],Te=p[Z+2],(ie&192)===128&&(Te&192)===128&&(Le=(de&15)<<12|(ie&63)<<6|Te&63,Le>2047&&(Le<55296||Le>57343)&&(_e=Le));break;case 4:ie=p[Z+1],Te=p[Z+2],Ce=p[Z+3],(ie&192)===128&&(Te&192)===128&&(Ce&192)===128&&(Le=(de&15)<<18|(ie&63)<<12|(Te&63)<<6|Ce&63,Le>65535&&Le<1114112&&(_e=Le))}}_e===null?(_e=65533,K=1):_e>65535&&(_e-=65536,B.push(_e>>>10&1023|55296),_e=56320|_e&1023),B.push(_e),Z+=K}return D(B)}let F=4096;function D(p){let _=p.length;if(_<=F)return String.fromCharCode.apply(String,p);let A="",B=0;for(;B<_;)A+=String.fromCharCode.apply(String,p.slice(B,B+=F));return A}function oe(p,_,A){let B="";A=Math.min(p.length,A);for(let Z=_;Z<A;++Z)B+=String.fromCharCode(p[Z]&127);return B}function j(p,_,A){let B="";A=Math.min(p.length,A);for(let Z=_;Z<A;++Z)B+=String.fromCharCode(p[Z]);return B}function W(p,_,A){let B=p.length;(!_||_<0)&&(_=0),(!A||A<0||A>B)&&(A=B);let Z="";for(let de=_;de<A;++de)Z+=we[p[de]];return Z}function re(p,_,A){let B=p.slice(_,A),Z="";for(let de=0;de<B.length-1;de+=2)Z+=String.fromCharCode(B[de]+B[de+1]*256);return Z}s.prototype.slice=function(p,_){let A=this.length;p=~~p,_=_===void 0?A:~~_,p<0?(p+=A,p<0&&(p=0)):p>A&&(p=A),_<0?(_+=A,_<0&&(_=0)):_>A&&(_=A),_<p&&(_=p);let B=this.subarray(p,_);return Object.setPrototypeOf(B,s.prototype),B};function U(p,_,A){if(p%1!==0||p<0)throw new RangeError("offset is not uint");if(p+_>A)throw new RangeError("Trying to access beyond buffer length")}s.prototype.readUintLE=s.prototype.readUIntLE=function(p,_,A){p=p>>>0,_=_>>>0,A||U(p,_,this.length);let B=this[p],Z=1,de=0;for(;++de<_&&(Z*=256);)B+=this[p+de]*Z;return B},s.prototype.readUintBE=s.prototype.readUIntBE=function(p,_,A){p=p>>>0,_=_>>>0,A||U(p,_,this.length);let B=this[p+--_],Z=1;for(;_>0&&(Z*=256);)B+=this[p+--_]*Z;return B},s.prototype.readUint8=s.prototype.readUInt8=function(p,_){return p=p>>>0,_||U(p,1,this.length),this[p]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(p,_){return p=p>>>0,_||U(p,2,this.length),this[p]|this[p+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(p,_){return p=p>>>0,_||U(p,2,this.length),this[p]<<8|this[p+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(p,_){return p=p>>>0,_||U(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(p,_){return p=p>>>0,_||U(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},s.prototype.readBigUInt64LE=ae(function(p){p=p>>>0,X(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&be(p,this.length-8);let B=_+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,Z=this[++p]+this[++p]*2**8+this[++p]*2**16+A*2**24;return BigInt(B)+(BigInt(Z)<<BigInt(32))}),s.prototype.readBigUInt64BE=ae(function(p){p=p>>>0,X(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&be(p,this.length-8);let B=_*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],Z=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(Z)}),s.prototype.readIntLE=function(p,_,A){p=p>>>0,_=_>>>0,A||U(p,_,this.length);let B=this[p],Z=1,de=0;for(;++de<_&&(Z*=256);)B+=this[p+de]*Z;return Z*=128,B>=Z&&(B-=Math.pow(2,8*_)),B},s.prototype.readIntBE=function(p,_,A){p=p>>>0,_=_>>>0,A||U(p,_,this.length);let B=_,Z=1,de=this[p+--B];for(;B>0&&(Z*=256);)de+=this[p+--B]*Z;return Z*=128,de>=Z&&(de-=Math.pow(2,8*_)),de},s.prototype.readInt8=function(p,_){return p=p>>>0,_||U(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},s.prototype.readInt16LE=function(p,_){p=p>>>0,_||U(p,2,this.length);let A=this[p]|this[p+1]<<8;return A&32768?A|4294901760:A},s.prototype.readInt16BE=function(p,_){p=p>>>0,_||U(p,2,this.length);let A=this[p+1]|this[p]<<8;return A&32768?A|4294901760:A},s.prototype.readInt32LE=function(p,_){return p=p>>>0,_||U(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},s.prototype.readInt32BE=function(p,_){return p=p>>>0,_||U(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},s.prototype.readBigInt64LE=ae(function(p){p=p>>>0,X(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&be(p,this.length-8);let B=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(_+this[++p]*256+this[++p]*65536+this[++p]*16777216)}),s.prototype.readBigInt64BE=ae(function(p){p=p>>>0,X(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&be(p,this.length-8);let B=(_<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(B)<<BigInt(32))+BigInt(this[++p]*16777216+this[++p]*65536+this[++p]*256+A)}),s.prototype.readFloatLE=function(p,_){return p=p>>>0,_||U(p,4,this.length),e.read(this,p,!0,23,4)},s.prototype.readFloatBE=function(p,_){return p=p>>>0,_||U(p,4,this.length),e.read(this,p,!1,23,4)},s.prototype.readDoubleLE=function(p,_){return p=p>>>0,_||U(p,8,this.length),e.read(this,p,!0,52,8)},s.prototype.readDoubleBE=function(p,_){return p=p>>>0,_||U(p,8,this.length),e.read(this,p,!1,52,8)};function Q(p,_,A,B,Z,de){if(!s.isBuffer(p))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>Z||_<de)throw new RangeError('"value" argument is out of bounds');if(A+B>p.length)throw new RangeError("Index out of range")}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(p,_,A,B){if(p=+p,_=_>>>0,A=A>>>0,!B){let _e=Math.pow(2,8*A)-1;Q(this,p,_,A,_e,0)}let Z=1,de=0;for(this[_]=p&255;++de<A&&(Z*=256);)this[_+de]=p/Z&255;return _+A},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(p,_,A,B){if(p=+p,_=_>>>0,A=A>>>0,!B){let _e=Math.pow(2,8*A)-1;Q(this,p,_,A,_e,0)}let Z=A-1,de=1;for(this[_+Z]=p&255;--Z>=0&&(de*=256);)this[_+Z]=p/de&255;return _+A},s.prototype.writeUint8=s.prototype.writeUInt8=function(p,_,A){return p=+p,_=_>>>0,A||Q(this,p,_,1,255,0),this[_]=p&255,_+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(p,_,A){return p=+p,_=_>>>0,A||Q(this,p,_,2,65535,0),this[_]=p&255,this[_+1]=p>>>8,_+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(p,_,A){return p=+p,_=_>>>0,A||Q(this,p,_,2,65535,0),this[_]=p>>>8,this[_+1]=p&255,_+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(p,_,A){return p=+p,_=_>>>0,A||Q(this,p,_,4,4294967295,0),this[_+3]=p>>>24,this[_+2]=p>>>16,this[_+1]=p>>>8,this[_]=p&255,_+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(p,_,A){return p=+p,_=_>>>0,A||Q(this,p,_,4,4294967295,0),this[_]=p>>>24,this[_+1]=p>>>16,this[_+2]=p>>>8,this[_+3]=p&255,_+4};function O(p,_,A,B,Z){Y(_,B,Z,p,A,7);let de=Number(_&BigInt(4294967295));p[A++]=de,de=de>>8,p[A++]=de,de=de>>8,p[A++]=de,de=de>>8,p[A++]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return p[A++]=_e,_e=_e>>8,p[A++]=_e,_e=_e>>8,p[A++]=_e,_e=_e>>8,p[A++]=_e,A}function J(p,_,A,B,Z){Y(_,B,Z,p,A,7);let de=Number(_&BigInt(4294967295));p[A+7]=de,de=de>>8,p[A+6]=de,de=de>>8,p[A+5]=de,de=de>>8,p[A+4]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return p[A+3]=_e,_e=_e>>8,p[A+2]=_e,_e=_e>>8,p[A+1]=_e,_e=_e>>8,p[A]=_e,A+8}s.prototype.writeBigUInt64LE=ae(function(p,_=0){return O(this,p,_,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=ae(function(p,_=0){return J(this,p,_,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(p,_,A,B){if(p=+p,_=_>>>0,!B){let K=Math.pow(2,8*A-1);Q(this,p,_,A,K-1,-K)}let Z=0,de=1,_e=0;for(this[_]=p&255;++Z<A&&(de*=256);)p<0&&_e===0&&this[_+Z-1]!==0&&(_e=1),this[_+Z]=(p/de>>0)-_e&255;return _+A},s.prototype.writeIntBE=function(p,_,A,B){if(p=+p,_=_>>>0,!B){let K=Math.pow(2,8*A-1);Q(this,p,_,A,K-1,-K)}let Z=A-1,de=1,_e=0;for(this[_+Z]=p&255;--Z>=0&&(de*=256);)p<0&&_e===0&&this[_+Z+1]!==0&&(_e=1),this[_+Z]=(p/de>>0)-_e&255;return _+A},s.prototype.writeInt8=function(p,_,A){return p=+p,_=_>>>0,A||Q(this,p,_,1,127,-128),p<0&&(p=255+p+1),this[_]=p&255,_+1},s.prototype.writeInt16LE=function(p,_,A){return p=+p,_=_>>>0,A||Q(this,p,_,2,32767,-32768),this[_]=p&255,this[_+1]=p>>>8,_+2},s.prototype.writeInt16BE=function(p,_,A){return p=+p,_=_>>>0,A||Q(this,p,_,2,32767,-32768),this[_]=p>>>8,this[_+1]=p&255,_+2},s.prototype.writeInt32LE=function(p,_,A){return p=+p,_=_>>>0,A||Q(this,p,_,4,2147483647,-2147483648),this[_]=p&255,this[_+1]=p>>>8,this[_+2]=p>>>16,this[_+3]=p>>>24,_+4},s.prototype.writeInt32BE=function(p,_,A){return p=+p,_=_>>>0,A||Q(this,p,_,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[_]=p>>>24,this[_+1]=p>>>16,this[_+2]=p>>>8,this[_+3]=p&255,_+4},s.prototype.writeBigInt64LE=ae(function(p,_=0){return O(this,p,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=ae(function(p,_=0){return J(this,p,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function pe(p,_,A,B,Z,de){if(A+B>p.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function ee(p,_,A,B,Z){return _=+_,A=A>>>0,Z||pe(p,_,A,4),e.write(p,_,A,B,23,4),A+4}s.prototype.writeFloatLE=function(p,_,A){return ee(this,p,_,!0,A)},s.prototype.writeFloatBE=function(p,_,A){return ee(this,p,_,!1,A)};function ve(p,_,A,B,Z){return _=+_,A=A>>>0,Z||pe(p,_,A,8),e.write(p,_,A,B,52,8),A+8}s.prototype.writeDoubleLE=function(p,_,A){return ve(this,p,_,!0,A)},s.prototype.writeDoubleBE=function(p,_,A){return ve(this,p,_,!1,A)},s.prototype.copy=function(p,_,A,B){if(!s.isBuffer(p))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),_>=p.length&&(_=p.length),_||(_=0),B>0&&B<A&&(B=A),B===A||p.length===0||this.length===0)return 0;if(_<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),p.length-_<B-A&&(B=p.length-_+A);let Z=B-A;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,A,B):Uint8Array.prototype.set.call(p,this.subarray(A,B),_),Z},s.prototype.fill=function(p,_,A,B){if(typeof p=="string"){if(typeof _=="string"?(B=_,_=0,A=this.length):typeof A=="string"&&(B=A,A=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!s.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(p.length===1){let de=p.charCodeAt(0);(B==="utf8"&&de<128||B==="latin1")&&(p=de)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(_<0||this.length<_||this.length<A)throw new RangeError("Out of range index");if(A<=_)return this;_=_>>>0,A=A===void 0?this.length:A>>>0,p||(p=0);let Z;if(typeof p=="number")for(Z=_;Z<A;++Z)this[Z]=p;else{let de=s.isBuffer(p)?p:s.from(p,B),_e=de.length;if(_e===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(Z=0;Z<A-_;++Z)this[Z+_]=de[Z%_e]}return this};let G={};function R(p,_,A){G[p]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${p}]`,this.stack,delete this.name}get code(){return p}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${p}]: ${this.message}`}}}R("ERR_BUFFER_OUT_OF_BOUNDS",function(p){return p?`${p} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),R("ERR_INVALID_ARG_TYPE",function(p,_){return`The "${p}" argument must be of type number. Received type ${typeof _}`},TypeError),R("ERR_OUT_OF_RANGE",function(p,_,A){let B=`The value of "${p}" is out of range.`,Z=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?Z=ne(String(A)):typeof A=="bigint"&&(Z=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(Z=ne(Z)),Z+="n"),B+=` It must be ${_}. Received ${Z}`,B},RangeError);function ne(p){let _="",A=p.length,B=p[0]==="-"?1:0;for(;A>=B+4;A-=3)_=`_${p.slice(A-3,A)}${_}`;return`${p.slice(0,A)}${_}`}function V(p,_,A){X(_,"offset"),(p[_]===void 0||p[_+A]===void 0)&&be(_,p.length-(A+1))}function Y(p,_,A,B,Z,de){if(p>A||p<_){let _e=typeof _=="bigint"?"n":"",K;throw _===0||_===BigInt(0)?K=`>= 0${_e} and < 2${_e} ** ${(de+1)*8}${_e}`:K=`>= -(2${_e} ** ${(de+1)*8-1}${_e}) and < 2 ** ${(de+1)*8-1}${_e}`,new G.ERR_OUT_OF_RANGE("value",K,p)}V(B,Z,de)}function X(p,_){if(typeof p!="number")throw new G.ERR_INVALID_ARG_TYPE(_,"number",p)}function be(p,_,A){throw Math.floor(p)!==p?(X(p,A),new G.ERR_OUT_OF_RANGE("offset","an integer",p)):_<0?new G.ERR_BUFFER_OUT_OF_BOUNDS:new G.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,p)}let se=/[^+/0-9A-Za-z-_]/g;function M(p){if(p=p.split("=")[0],p=p.trim().replace(se,""),p.length<2)return"";for(;p.length%4!==0;)p=p+"=";return p}function H(p,_){_=_||1/0;let A,B=p.length,Z=null,de=[];for(let _e=0;_e<B;++_e){if(A=p.charCodeAt(_e),A>55295&&A<57344){if(!Z){if(A>56319){(_-=3)>-1&&de.push(239,191,189);continue}else if(_e+1===B){(_-=3)>-1&&de.push(239,191,189);continue}Z=A;continue}if(A<56320){(_-=3)>-1&&de.push(239,191,189),Z=A;continue}A=(Z-55296<<10|A-56320)+65536}else Z&&(_-=3)>-1&&de.push(239,191,189);if(Z=null,A<128){if((_-=1)<0)break;de.push(A)}else if(A<2048){if((_-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((_-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((_-=4)<0)break;de.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return de}function te(p){let _=[];for(let A=0;A<p.length;++A)_.push(p.charCodeAt(A)&255);return _}function he(p,_){let A,B,Z,de=[];for(let _e=0;_e<p.length&&!((_-=2)<0);++_e)A=p.charCodeAt(_e),B=A>>8,Z=A%256,de.push(Z),de.push(B);return de}function fe(p){return i.toByteArray(M(p))}function ye(p,_,A,B){let Z;for(Z=0;Z<B&&!(Z+A>=_.length||Z>=p.length);++Z)_[Z+A]=p[Z];return Z}function z(p,_){return p instanceof _||p!=null&&p.constructor!=null&&p.constructor.name!=null&&p.constructor.name===_.name}function ge(p){return p!==p}let we=(function(){let p="0123456789abcdef",_=new Array(256);for(let A=0;A<16;++A){let B=A*16;for(let Z=0;Z<16;++Z)_[B+Z]=p[A]+p[Z]}return _})();function ae(p){return typeof BigInt>"u"?Me:p}function Me(){throw new Error("BigInt not supported")}return Et}var Wt,Si,or,Ei,Et,Ai,lu=Qe(()=>{le(),ue(),ce(),Wt={},Si=!1,or={},Ei=!1,Et={},Ai=!1}),qe={};Ht(qe,{Buffer:()=>Ar,INSPECT_MAX_BYTES:()=>bs,default:()=>gt,kMaxLength:()=>ys});var gt,Ar,bs,ys,He=Qe(()=>{le(),ue(),ce(),lu(),gt=au(),gt.Buffer,gt.SlowBuffer,gt.INSPECT_MAX_BYTES,gt.kMaxLength,Ar=gt.Buffer,bs=gt.INSPECT_MAX_BYTES,ys=gt.kMaxLength}),ue=Qe(()=>{He()}),Be=me((i,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}}),vs=me((i,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[o,n]){let s=r.shift();return n==="f"?s.toFixed(6):n==="j"?JSON.stringify(s):n==="s"&&typeof s=="object"?`${s.constructor!==Object?s.constructor.name:""} {}`.trim():s.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"{}"}}}}),Ye=me((i,e)=>{le(),ue(),ce();var{format:t,inspect:r}=vs(),{AggregateError:o}=Be(),n=globalThis.AggregateError||o,s=Symbol("kIsNodeError"),a=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function d(m,k){if(!m)throw new u.ERR_INTERNAL_ASSERTION(k)}function f(m){let k="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)k=`_${m.slice(x-3,x)}${k}`;return`${m.slice(0,x)}${k}`}function g(m,k,x){if(typeof k=="function")return d(k.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${k.length}).`),k(...x);let v=(k.match(/%[dfijoOs]/g)||[]).length;return d(v===x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${v}).`),x.length===0?k:t(k,...x)}function h(m,k,x){x||(x=Error);class v extends x{constructor(...E){super(g(m,k,E))}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[s]=!0,u[m]=v}function b(m){let k=c+m.name;return Object.defineProperty(m,"name",{value:k}),m}function y(m,k){if(m&&k&&m!==k){if(Array.isArray(k.errors))return k.errors.push(m),k;let x=new n([k,m],k.message);return x.code=k.code,x}return m||k}var w=class extends Error{constructor(m="The operation was aborted",k=void 0){if(k!==void 0&&typeof k!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",k);super(m,k),this.code="ABORT_ERR",this.name="AbortError"}};h("ERR_ASSERTION","%s",Error),h("ERR_INVALID_ARG_TYPE",(m,k,x)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(k)||(k=[k]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let S=[],E=[],I=[];for(let L of k)d(typeof L=="string","All expected entries have to be of type string"),a.includes(L)?S.push(L.toLowerCase()):l.test(L)?E.push(L):(d(L!=="object",'The value "object" should be written as "Object"'),I.push(L));if(E.length>0){let L=S.indexOf("object");L!==-1&&(S.splice(S,L,1),E.push("Object"))}if(S.length>0){switch(S.length){case 1:v+=`of type ${S[0]}`;break;case 2:v+=`one of type ${S[0]} or ${S[1]}`;break;default:{let L=S.pop();v+=`one of type ${S.join(", ")}, or ${L}`}}(E.length>0||I.length>0)&&(v+=" or ")}if(E.length>0){switch(E.length){case 1:v+=`an instance of ${E[0]}`;break;case 2:v+=`an instance of ${E[0]} or ${E[1]}`;break;default:{let L=E.pop();v+=`an instance of ${E.join(", ")}, or ${L}`}}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 L=I.pop();v+=`one of ${I.join(", ")}, or ${L}`}}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 L=r(x,{depth:-1});v+=`. Received ${L}`}}else{let L=r(x,{colors:!1});L.length>25&&(L=`${L.slice(0,25)}...`),v+=`. Received type ${typeof x} (${L})`}return v},TypeError),h("ERR_INVALID_ARG_VALUE",(m,k,x="is invalid")=>{let v=r(k);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${x}. Received ${v}`},TypeError),h("ERR_INVALID_RETURN_VALUE",(m,k,x)=>{var v;let S=x!=null&&(v=x.constructor)!==null&&v!==void 0&&v.name?`instance of ${x.constructor.name}`:`type ${typeof x}`;return`Expected ${m} to be returned from the "${k}" function but got ${S}.`},TypeError),h("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let k,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:k+=`The ${m[0]} argument`;break;case 2:k+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();k+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${k} must be specified`},TypeError),h("ERR_OUT_OF_RANGE",(m,k,x)=>{d(k,'Missing "range" argument');let v;if(Number.isInteger(x)&&Math.abs(x)>2**32)v=f(String(x));else if(typeof x=="bigint"){v=String(x);let S=BigInt(2)**BigInt(32);(x>S||x<-S)&&(v=f(v)),v+="n"}else v=r(x);return`The value of "${m}" is out of range. It must be ${k}. Received ${v}`},RangeError),h("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),h("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),h("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),h("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),h("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),h("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),h("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),h("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),h("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),h("ERR_STREAM_WRITE_AFTER_END","write after end",Error),h("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:b(y),hideStackFrames:b,codes:u}}),sr=me((i,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}),At={};Ht(At,{EventEmitter:()=>ws,default:()=>zt,defaultMaxListeners:()=>ks,init:()=>_s,listenerCount:()=>xs,on:()=>Ss,once:()=>Es});function cu(){if(Ii)return ar;Ii=!0;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(x,v,S){return Function.prototype.apply.call(x,v,S)},t;i&&typeof i.ownKeys=="function"?t=i.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)}ar=n,ar.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var s=10;function a(x){if(typeof x!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof x)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return s},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+".");s=x}}),n.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(x){if(typeof x!="number"||x<0||o(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function l(x){return x._maxListeners===void 0?n.defaultMaxListeners:x._maxListeners}n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(x){for(var v=[],S=1;S<arguments.length;S++)v.push(arguments[S]);var E=x==="error",I=this._events;if(I!==void 0)E=E&&I.error===void 0;else if(!E)return!1;if(E){var P;if(v.length>0&&(P=v[0]),P instanceof Error)throw P;var L=new Error("Unhandled error."+(P?" ("+P.message+")":""));throw L.context=P,L}var $=I[x];if($===void 0)return!1;if(typeof $=="function")e($,this,v);else for(var T=$.length,q=h($,T),S=0;S<T;++S)e(q[S],this,v);return!0};function c(x,v,S,E){var I,P,L;if(a(S),P=x._events,P===void 0?(P=x._events=Object.create(null),x._eventsCount=0):(P.newListener!==void 0&&(x.emit("newListener",v,S.listener?S.listener:S),P=x._events),L=P[v]),L===void 0)L=P[v]=S,++x._eventsCount;else if(typeof L=="function"?L=P[v]=E?[S,L]:[L,S]:E?L.unshift(S):L.push(S),I=l(x),I>0&&L.length>I&&!L.warned){L.warned=!0;var $=new Error("Possible EventEmitter memory leak detected. "+L.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");$.name="MaxListenersExceededWarning",$.emitter=x,$.type=v,$.count=L.length,r($)}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,S){var E={fired:!1,wrapFn:void 0,target:x,type:v,listener:S},I=u.bind(E);return I.listener=S,E.wrapFn=I,I}n.prototype.once=function(x,v){return a(v),this.on(x,d(this,x,v)),this},n.prototype.prependOnceListener=function(x,v){return a(v),this.prependListener(x,d(this,x,v)),this},n.prototype.removeListener=function(x,v){var S,E,I,P,L;if(a(v),E=this._events,E===void 0)return this;if(S=E[x],S===void 0)return this;if(S===v||S.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete E[x],E.removeListener&&this.emit("removeListener",x,S.listener||v));else if(typeof S!="function"){for(I=-1,P=S.length-1;P>=0;P--)if(S[P]===v||S[P].listener===v){L=S[P].listener,I=P;break}if(I<0)return this;I===0?S.shift():b(S,I),S.length===1&&(E[x]=S[0]),E.removeListener!==void 0&&this.emit("removeListener",x,L||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(x){var v,S,E;if(S=this._events,S===void 0)return this;if(S.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):S[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete S[x]),this;if(arguments.length===0){var I=Object.keys(S),P;for(E=0;E<I.length;++E)P=I[E],P!=="removeListener"&&this.removeAllListeners(P);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=S[x],typeof v=="function")this.removeListener(x,v);else if(v!==void 0)for(E=v.length-1;E>=0;E--)this.removeListener(x,v[E]);return this};function f(x,v,S){var E=x._events;if(E===void 0)return[];var I=E[v];return I===void 0?[]:typeof I=="function"?S?[I.listener||I]:[I]:S?y(I):h(I,I.length)}n.prototype.listeners=function(x){return f(this,x,!0)},n.prototype.rawListeners=function(x){return f(this,x,!1)},n.listenerCount=function(x,v){return typeof x.listenerCount=="function"?x.listenerCount(v):g.call(x,v)},n.prototype.listenerCount=g;function g(x){var v=this._events;if(v!==void 0){var S=v[x];if(typeof S=="function")return 1;if(S!==void 0)return S.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function h(x,v){for(var S=new Array(v),E=0;E<v;++E)S[E]=x[E];return S}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),S=0;S<v.length;++S)v[S]=x[S].listener||x[S];return v}function w(x,v){return new Promise(function(S,E){function I(L){x.removeListener(v,P),E(L)}function P(){typeof x.removeListener=="function"&&x.removeListener("error",I),S([].slice.call(arguments))}k(x,v,P,{once:!0}),v!=="error"&&m(x,I,{once:!0})})}function m(x,v,S){typeof x.on=="function"&&k(x,"error",v,S)}function k(x,v,S,E){if(typeof x.on=="function")E.once?x.once(v,S):x.on(v,S);else if(typeof x.addEventListener=="function")x.addEventListener(v,function I(P){E.once&&x.removeEventListener(v,I),S(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return ar}var ar,Ii,zt,ws,ks,_s,xs,Ss,Es,Rt=Qe(()=>{le(),ue(),ce(),ar={},Ii=!1,zt=cu(),zt.once,zt.once=function(i,e){return new Promise((t,r)=>{function o(...s){n!==void 0&&i.removeListener("error",n),t(s)}let n;e!=="error"&&(n=s=>{i.removeListener(name,o),r(s)},i.once("error",n)),i.once(e,o)})},zt.on=function(i,e){let t=[],r=[],o=null,n=!1,s={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(o){let u=Promise.reject(o);return o=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){i.removeListener(e,a),i.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){o=c,i.removeListener(e,a),i.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return i.on(e,a),i.on("error",l),s;function a(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function l(c){n=!0;let u=r.shift();u?u.reject(c):o=c,s.return()}},{EventEmitter:ws,defaultMaxListeners:ks,init:_s,listenerCount:xs,on:Ss,once:Es}=zt}),Xe=me((i,e)=>{le(),ue(),ce();var t=(He(),je(qe)),{format:r,inspect:o}=vs(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ye(),{kResistStopPropagation:s,AggregateError:a,SymbolDispose:l}=Be(),c=globalThis.AbortSignal||sr().AbortSignal,u=globalThis.AbortController||sr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,f=globalThis.Blob||t.Blob,g=typeof f<"u"?function(y){return y instanceof f}:function(y){return!1},h=(y,w)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new n(w,"AbortSignal",y)},b=(y,w)=>{if(typeof y!="function")throw new n(w,"Function",y)};e.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(y){let w=!1;return function(...m){w||(w=!0,y.apply(this,m))}},createDeferredPromise:function(){let y,w;return{promise:new Promise((m,k)=>{y=m,w=k}),resolve:y,reject:w}},promisify(y){return new Promise((w,m)=>{y((k,...x)=>k?m(k):w(...x))})},debuglog(){return function(){}},format:r,inspect:o,types:{isAsyncFunction(y){return y instanceof d},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:g,deprecate(y,w){return y},addAbortListener:(Rt(),je(At)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);h(y,"signal"),b(w,"listener");let m;return y.aborted?queueMicrotask(()=>w()):(y.addEventListener("abort",w,{__proto__:null,once:!0,[s]:!0}),m=()=>{y.removeEventListener("abort",w)}),{__proto__:null,[l](){var k;(k=m)===null||k===void 0||k()}}},AbortSignalAny:c.any||function(y){if(y.length===1)return y[0];let w=new u,m=()=>w.abort();return y.forEach(k=>{h(k,"signals"),k.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{y.forEach(k=>k.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),lr=me((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:o,ArrayPrototypeMap:n,NumberIsInteger:s,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:f,String:g,StringPrototypeToUpperCase:h,StringPrototypeTrim:b}=Be(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:k,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ye(),{normalizeEncoding:S}=Xe(),{isAsyncFunction:E,isArrayBufferView:I}=Xe().types,P={};function L(z){return z===(z|0)}function $(z){return z===z>>>0}var T=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function F(z,ge,we){if(typeof z>"u"&&(z=we),typeof z=="string"){if(f(T,z)===null)throw new k(ge,z,q);z=u(z,8)}return j(z,ge),z}var D=y((z,ge,we=c,ae=l)=>{if(typeof z!="number")throw new m(ge,"number",z);if(!s(z))throw new x(ge,"an integer",z);if(z<we||z>ae)throw new x(ge,`>= ${we} && <= ${ae}`,z)}),oe=y((z,ge,we=-2147483648,ae=2147483647)=>{if(typeof z!="number")throw new m(ge,"number",z);if(!s(z))throw new x(ge,"an integer",z);if(z<we||z>ae)throw new x(ge,`>= ${we} && <= ${ae}`,z)}),j=y((z,ge,we=!1)=>{if(typeof z!="number")throw new m(ge,"number",z);if(!s(z))throw new x(ge,"an integer",z);let ae=we?1:0,Me=4294967295;if(z<ae||z>Me)throw new x(ge,`>= ${ae} && <= ${Me}`,z)});function W(z,ge){if(typeof z!="string")throw new m(ge,"string",z)}function re(z,ge,we=void 0,ae){if(typeof z!="number")throw new m(ge,"number",z);if(we!=null&&z<we||ae!=null&&z>ae||(we!=null||ae!=null)&&a(z))throw new x(ge,`${we!=null?`>= ${we}`:""}${we!=null&&ae!=null?" && ":""}${ae!=null?`<= ${ae}`:""}`,z)}var U=y((z,ge,we)=>{if(!r(we,z)){let ae="must be one of: "+o(n(we,Me=>typeof Me=="string"?`'${Me}'`:g(Me)),", ");throw new k(ge,z,ae)}});function Q(z,ge){if(typeof z!="boolean")throw new m(ge,"boolean",z)}function O(z,ge,we){return z==null||!d(z,ge)?we:z[ge]}var J=y((z,ge,we=null)=>{let ae=O(we,"allowArray",!1),Me=O(we,"allowFunction",!1);if(!O(we,"nullable",!1)&&z===null||!ae&&t(z)||typeof z!="object"&&(!Me||typeof z!="function"))throw new m(ge,"Object",z)}),pe=y((z,ge)=>{if(z!=null&&typeof z!="object"&&typeof z!="function")throw new m(ge,"a dictionary",z)}),ee=y((z,ge,we=0)=>{if(!t(z))throw new m(ge,"Array",z);if(z.length<we){let ae=`must be longer than ${we}`;throw new k(ge,z,ae)}});function ve(z,ge){ee(z,ge);for(let we=0;we<z.length;we++)W(z[we],`${ge}[${we}]`)}function G(z,ge){ee(z,ge);for(let we=0;we<z.length;we++)Q(z[we],`${ge}[${we}]`)}function R(z,ge){ee(z,ge);for(let we=0;we<z.length;we++){let ae=z[we],Me=`${ge}[${we}]`;if(ae==null)throw new m(Me,"AbortSignal",ae);be(ae,Me)}}function ne(z,ge="signal"){if(W(z,ge),P[z]===void 0)throw P[h(z)]!==void 0?new v(z+" (signals must use all capital letters)"):new v(z)}var V=y((z,ge="buffer")=>{if(!I(z))throw new m(ge,["Buffer","TypedArray","DataView"],z)});function Y(z,ge){let we=S(ge),ae=z.length;if(we==="hex"&&ae%2!==0)throw new k("encoding",ge,`is invalid for data of length ${ae}`)}function X(z,ge="Port",we=!0){if(typeof z!="number"&&typeof z!="string"||typeof z=="string"&&b(z).length===0||+z!==+z>>>0||z>65535||z===0&&!we)throw new w(ge,z,we);return z|0}var be=y((z,ge)=>{if(z!==void 0&&(z===null||typeof z!="object"||!("aborted"in z)))throw new m(ge,"AbortSignal",z)}),se=y((z,ge)=>{if(typeof z!="function")throw new m(ge,"Function",z)}),M=y((z,ge)=>{if(typeof z!="function"||E(z))throw new m(ge,"Function",z)}),H=y((z,ge)=>{if(z!==void 0)throw new m(ge,"undefined",z)});function te(z,ge,we){if(!r(we,z))throw new m(ge,`('${o(we,"|")}')`,z)}var he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(z,ge){if(typeof z>"u"||!f(he,z))throw new k(ge,z,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(z){if(typeof z=="string")return fe(z,"hints"),z;if(t(z)){let ge=z.length,we="";if(ge===0)return we;for(let ae=0;ae<ge;ae++){let Me=z[ae];fe(Me,"hints"),we+=Me,ae!==ge-1&&(we+=", ")}return we}throw new k("hints",z,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:L,isUint32:$,parseFileMode:F,validateArray:ee,validateStringArray:ve,validateBooleanArray:G,validateAbortSignalArray:R,validateBoolean:Q,validateBuffer:V,validateDictionary:pe,validateEncoding:Y,validateFunction:se,validateInt32:oe,validateInteger:D,validateNumber:re,validateObject:J,validateOneOf:U,validatePlainFunction:M,validatePort:X,validateSignalName:ne,validateString:W,validateUint32:j,validateUndefined:H,validateUnion:te,validateAbortSignal:be,validateLinkHeaderValue:ye}}),jt=me((i,e)=>{le(),ue(),ce();var t=e.exports={},r,o;function n(){throw new Error("setTimeout has not been defined")}function s(){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=s}catch{o=s}})();function a(w){if(r===setTimeout)return setTimeout(w,0);if((r===n||!r)&&setTimeout)return r=setTimeout,setTimeout(w,0);try{return r(w,0)}catch{try{return r.call(null,w,0)}catch{return r.call(this,w,0)}}}function l(w){if(o===clearTimeout)return clearTimeout(w);if((o===s||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(w);try{return o(w)}catch{try{return o.call(null,w)}catch{return o.call(this,w)}}}var c=[],u=!1,d,f=-1;function g(){!u||!d||(u=!1,d.length?c=d.concat(c):f=-1,c.length&&h())}function h(){if(!u){var w=a(g);u=!0;for(var m=c.length;m;){for(d=c,c=[];++f<m;)d&&d[f].run();f=-1,m=c.length}d=null,u=!1,l(w)}}t.nextTick=function(w){var m=new Array(arguments.length-1);if(arguments.length>1)for(var k=1;k<arguments.length;k++)m[k-1]=arguments[k];c.push(new b(w,m)),c.length===1&&!u&&a(h)};function b(w,m){this.fun=w,this.array=m}b.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function y(){}t.on=y,t.addListener=y,t.once=y,t.off=y,t.removeListener=y,t.removeAllListeners=y,t.emit=y,t.prependListener=y,t.prependOnceListener=y,t.listeners=function(w){return[]},t.binding=function(w){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(w){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),bt=me((i,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:o}=Be(),n=o("nodejs.stream.destroyed"),s=o("nodejs.stream.errored"),a=o("nodejs.stream.readable"),l=o("nodejs.stream.writable"),c=o("nodejs.stream.disturbed"),u=o("nodejs.webstream.isClosedPromise"),d=o("nodejs.webstream.controllerErrorFunction");function f(O,J=!1){var pe;return!!(O&&typeof O.pipe=="function"&&typeof O.on=="function"&&(!J||typeof O.pause=="function"&&typeof O.resume=="function")&&(!O._writableState||((pe=O._readableState)===null||pe===void 0?void 0:pe.readable)!==!1)&&(!O._writableState||O._readableState))}function g(O){var J;return!!(O&&typeof O.write=="function"&&typeof O.on=="function"&&(!O._readableState||((J=O._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function h(O){return!!(O&&typeof O.pipe=="function"&&O._readableState&&typeof O.on=="function"&&typeof O.write=="function")}function b(O){return O&&(O._readableState||O._writableState||typeof O.write=="function"&&typeof O.on=="function"||typeof O.pipe=="function"&&typeof O.on=="function")}function y(O){return!!(O&&!b(O)&&typeof O.pipeThrough=="function"&&typeof O.getReader=="function"&&typeof O.cancel=="function")}function w(O){return!!(O&&!b(O)&&typeof O.getWriter=="function"&&typeof O.abort=="function")}function m(O){return!!(O&&!b(O)&&typeof O.readable=="object"&&typeof O.writable=="object")}function k(O){return y(O)||w(O)||m(O)}function x(O,J){return O==null?!1:J===!0?typeof O[t]=="function":J===!1?typeof O[r]=="function":typeof O[t]=="function"||typeof O[r]=="function"}function v(O){if(!b(O))return null;let J=O._writableState,pe=O._readableState,ee=J||pe;return!!(O.destroyed||O[n]||ee!=null&&ee.destroyed)}function S(O){if(!g(O))return null;if(O.writableEnded===!0)return!0;let J=O._writableState;return J!=null&&J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function E(O,J){if(!g(O))return null;if(O.writableFinished===!0)return!0;let pe=O._writableState;return pe!=null&&pe.errored?!1:typeof pe?.finished!="boolean"?null:!!(pe.finished||J===!1&&pe.ended===!0&&pe.length===0)}function I(O){if(!f(O))return null;if(O.readableEnded===!0)return!0;let J=O._readableState;return!J||J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function P(O,J){if(!f(O))return null;let pe=O._readableState;return pe!=null&&pe.errored?!1:typeof pe?.endEmitted!="boolean"?null:!!(pe.endEmitted||J===!1&&pe.ended===!0&&pe.length===0)}function L(O){return O&&O[a]!=null?O[a]:typeof O?.readable!="boolean"?null:v(O)?!1:f(O)&&O.readable&&!P(O)}function $(O){return O&&O[l]!=null?O[l]:typeof O?.writable!="boolean"?null:v(O)?!1:g(O)&&O.writable&&!S(O)}function T(O,J){return b(O)?v(O)?!0:!(J?.readable!==!1&&L(O)||J?.writable!==!1&&$(O)):null}function q(O){var J,pe;return b(O)?O.writableErrored?O.writableErrored:(J=(pe=O._writableState)===null||pe===void 0?void 0:pe.errored)!==null&&J!==void 0?J:null:null}function F(O){var J,pe;return b(O)?O.readableErrored?O.readableErrored:(J=(pe=O._readableState)===null||pe===void 0?void 0:pe.errored)!==null&&J!==void 0?J:null:null}function D(O){if(!b(O))return null;if(typeof O.closed=="boolean")return O.closed;let J=O._writableState,pe=O._readableState;return typeof J?.closed=="boolean"||typeof pe?.closed=="boolean"?J?.closed||pe?.closed:typeof O._closed=="boolean"&&oe(O)?O._closed:null}function oe(O){return typeof O._closed=="boolean"&&typeof O._defaultKeepAlive=="boolean"&&typeof O._removedConnection=="boolean"&&typeof O._removedContLen=="boolean"}function j(O){return typeof O._sent100=="boolean"&&oe(O)}function W(O){var J;return typeof O._consuming=="boolean"&&typeof O._dumped=="boolean"&&((J=O.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function re(O){if(!b(O))return null;let J=O._writableState,pe=O._readableState,ee=J||pe;return!ee&&j(O)||!!(ee&&ee.autoDestroy&&ee.emitClose&&ee.closed===!1)}function U(O){var J;return!!(O&&((J=O[c])!==null&&J!==void 0?J:O.readableDidRead||O.readableAborted))}function Q(O){var J,pe,ee,ve,G,R,ne,V,Y,X;return!!(O&&((J=(pe=(ee=(ve=(G=(R=O[s])!==null&&R!==void 0?R:O.readableErrored)!==null&&G!==void 0?G:O.writableErrored)!==null&&ve!==void 0?ve:(ne=O._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&ee!==void 0?ee:(V=O._writableState)===null||V===void 0?void 0:V.errorEmitted)!==null&&pe!==void 0?pe:(Y=O._readableState)===null||Y===void 0?void 0:Y.errored)!==null&&J!==void 0?J:!((X=O._writableState)===null||X===void 0)&&X.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:U,kIsDisturbed:c,isErrored:Q,kIsErrored:s,isReadable:L,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:D,isDuplexNodeStream:h,isFinished:T,isIterable:x,isReadableNodeStream:f,isReadableStream:y,isReadableEnded:I,isReadableFinished:P,isReadableErrored:F,isNodeStream:b,isWebStream:k,isWritable:$,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:S,isWritableFinished:E,isWritableErrored:q,isServerRequest:W,isServerResponse:j,willEmitClose:re,isTransformStream:m}}),It=me((i,e)=>{le(),ue(),ce();var t=jt(),{AbortError:r,codes:o}=Ye(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:s}=o,{kEmptyObject:a,once:l}=Xe(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:f}=lr(),{Promise:g,PromisePrototypeThen:h,SymbolDispose:b}=Be(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:k,isReadableFinished:x,isReadableErrored:v,isWritable:S,isWritableNodeStream:E,isWritableStream:I,isWritableFinished:P,isWritableErrored:L,isNodeStream:$,willEmitClose:T,kIsClosedPromise:q}=bt(),F;function D(U){return U.setHeader&&typeof U.abort=="function"}var oe=()=>{};function j(U,Q,O){var J,pe;if(arguments.length===2?(O=Q,Q=a):Q==null?Q=a:d(Q,"options"),u(O,"callback"),c(Q.signal,"options.signal"),O=l(O),k(U)||I(U))return W(U,Q,O);if(!$(U))throw new n("stream",["ReadableStream","WritableStream","Stream"],U);let ee=(J=Q.readable)!==null&&J!==void 0?J:m(U),ve=(pe=Q.writable)!==null&&pe!==void 0?pe:E(U),G=U._writableState,R=U._readableState,ne=()=>{U.writable||X()},V=T(U)&&m(U)===ee&&E(U)===ve,Y=P(U,!1),X=()=>{Y=!0,U.destroyed&&(V=!1),!(V&&(!U.readable||ee))&&(!ee||be)&&O.call(U)},be=x(U,!1),se=()=>{be=!0,U.destroyed&&(V=!1),!(V&&(!U.writable||ve))&&(!ve||Y)&&O.call(U)},M=z=>{O.call(U,z)},H=y(U),te=()=>{H=!0;let z=L(U)||v(U);if(z&&typeof z!="boolean")return O.call(U,z);if(ee&&!be&&m(U,!0)&&!x(U,!1))return O.call(U,new s);if(ve&&!Y&&!P(U,!1))return O.call(U,new s);O.call(U)},he=()=>{H=!0;let z=L(U)||v(U);if(z&&typeof z!="boolean")return O.call(U,z);O.call(U)},fe=()=>{U.req.on("finish",X)};D(U)?(U.on("complete",X),V||U.on("abort",te),U.req?fe():U.on("request",fe)):ve&&!G&&(U.on("end",ne),U.on("close",ne)),!V&&typeof U.aborted=="boolean"&&U.on("aborted",te),U.on("end",se),U.on("finish",X),Q.error!==!1&&U.on("error",M),U.on("close",te),H?t.nextTick(te):G!=null&&G.errorEmitted||R!=null&&R.errorEmitted?V||t.nextTick(he):(!ee&&(!V||w(U))&&(Y||S(U)===!1)||!ve&&(!V||S(U))&&(be||w(U)===!1)||R&&U.req&&U.aborted)&&t.nextTick(he);let ye=()=>{O=oe,U.removeListener("aborted",te),U.removeListener("complete",X),U.removeListener("abort",te),U.removeListener("request",fe),U.req&&U.req.removeListener("finish",X),U.removeListener("end",ne),U.removeListener("close",ne),U.removeListener("finish",X),U.removeListener("end",se),U.removeListener("error",M),U.removeListener("close",te)};if(Q.signal&&!H){let z=()=>{let ge=O;ye(),ge.call(U,new r(void 0,{cause:Q.signal.reason}))};if(Q.signal.aborted)t.nextTick(z);else{F=F||Xe().addAbortListener;let ge=F(Q.signal,z),we=O;O=l((...ae)=>{ge[b](),we.apply(U,ae)})}}return ye}function W(U,Q,O){let J=!1,pe=oe;if(Q.signal)if(pe=()=>{J=!0,O.call(U,new r(void 0,{cause:Q.signal.reason}))},Q.signal.aborted)t.nextTick(pe);else{F=F||Xe().addAbortListener;let ve=F(Q.signal,pe),G=O;O=l((...R)=>{ve[b](),G.apply(U,R)})}let ee=(...ve)=>{J||t.nextTick(()=>O.apply(U,ve))};return h(U[q].promise,ee,ee),oe}function re(U,Q){var O;let J=!1;return Q===null&&(Q=a),(O=Q)!==null&&O!==void 0&&O.cleanup&&(f(Q.cleanup,"cleanup"),J=Q.cleanup),new g((pe,ee)=>{let ve=j(U,Q,G=>{J&&ve(),G?ee(G):pe()})})}e.exports=j,e.exports.finished=re}),Vt=me((i,e)=>{le(),ue(),ce();var t=jt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:n}=Ye(),{Symbol:s}=Be(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=bt(),d=s("kDestroy"),f=s("kConstruct");function g(T,q,F){T&&(T.stack,q&&!q.errored&&(q.errored=T),F&&!F.errored&&(F.errored=T))}function h(T,q){let F=this._readableState,D=this._writableState,oe=D||F;return D!=null&&D.destroyed||F!=null&&F.destroyed?(typeof q=="function"&&q(),this):(g(T,D,F),D&&(D.destroyed=!0),F&&(F.destroyed=!0),oe.constructed?b(this,T,q):this.once(d,function(j){b(this,r(j,T),q)}),this)}function b(T,q,F){let D=!1;function oe(j){if(D)return;D=!0;let W=T._readableState,re=T._writableState;g(j,re,W),re&&(re.closed=!0),W&&(W.closed=!0),typeof F=="function"&&F(j),j?t.nextTick(y,T,j):t.nextTick(w,T)}try{T._destroy(q||null,oe)}catch(j){oe(j)}}function y(T,q){m(T,q),w(T)}function w(T){let q=T._readableState,F=T._writableState;F&&(F.closeEmitted=!0),q&&(q.closeEmitted=!0),(F!=null&&F.emitClose||q!=null&&q.emitClose)&&T.emit("close")}function m(T,q){let F=T._readableState,D=T._writableState;D!=null&&D.errorEmitted||F!=null&&F.errorEmitted||(D&&(D.errorEmitted=!0),F&&(F.errorEmitted=!0),T.emit("error",q))}function k(){let T=this._readableState,q=this._writableState;T&&(T.constructed=!0,T.closed=!1,T.closeEmitted=!1,T.destroyed=!1,T.errored=null,T.errorEmitted=!1,T.reading=!1,T.ended=T.readable===!1,T.endEmitted=T.readable===!1),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function x(T,q,F){let D=T._readableState,oe=T._writableState;if(oe!=null&&oe.destroyed||D!=null&&D.destroyed)return this;D!=null&&D.autoDestroy||oe!=null&&oe.autoDestroy?T.destroy(q):q&&(q.stack,oe&&!oe.errored&&(oe.errored=q),D&&!D.errored&&(D.errored=q),F?t.nextTick(m,T,q):m(T,q))}function v(T,q){if(typeof T._construct!="function")return;let F=T._readableState,D=T._writableState;F&&(F.constructed=!1),D&&(D.constructed=!1),T.once(f,q),!(T.listenerCount(f)>1)&&t.nextTick(S,T)}function S(T){let q=!1;function F(D){if(q){x(T,D??new o);return}q=!0;let oe=T._readableState,j=T._writableState,W=j||oe;oe&&(oe.constructed=!0),j&&(j.constructed=!0),W.destroyed?T.emit(d,D):D?x(T,D,!0):t.nextTick(E,T)}try{T._construct(D=>{t.nextTick(F,D)})}catch(D){t.nextTick(F,D)}}function E(T){T.emit(f)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function P(T){T.emit("close")}function L(T,q){T.emit("error",q),t.nextTick(P,T)}function $(T,q){!T||l(T)||(!q&&!c(T)&&(q=new n),u(T)?(T.socket=null,T.destroy(q)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(q):typeof T.close=="function"?T.close():q?t.nextTick(L,T,q):t.nextTick(P,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:$,destroy:h,undestroy:k,errorOrDestroy:x}}),Ti=me((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Be(),{EventEmitter:o}=(Rt(),je(At));function n(a){o.call(this,a)}r(n.prototype,o.prototype),r(n,o),n.prototype.pipe=function(a,l){let c=this;function u(w){a.writable&&a.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function d(){c.readable&&c.resume&&c.resume()}a.on("drain",d),!a._isStdio&&(!l||l.end!==!1)&&(c.on("end",g),c.on("close",h));let f=!1;function g(){f||(f=!0,a.end())}function h(){f||(f=!0,typeof a.destroy=="function"&&a.destroy())}function b(w){y(),o.listenerCount(this,"error")===0&&this.emit("error",w)}s(c,"error",b),s(a,"error",b);function y(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",g),c.removeListener("close",h),c.removeListener("error",b),a.removeListener("error",b),c.removeListener("end",y),c.removeListener("close",y),a.removeListener("close",y)}return c.on("end",y),c.on("close",y),a.on("close",y),a.emit("pipe",c),a};function s(a,l,c){if(typeof a.prependListener=="function")return a.prependListener(l,c);!a._events||!a._events[l]?a.on(l,c):t(a._events[l])?a._events[l].unshift(c):a._events[l]=[c,a._events[l]]}e.exports={Stream:n,prependListener:s}}),Ir=me((i,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Be(),{AbortError:r,codes:o}=Ye(),{isNodeStream:n,isWebStream:s,kControllerErrorFunction:a}=bt(),l=It(),{ERR_INVALID_ARG_TYPE:c}=o,u,d=(f,g)=>{if(typeof f!="object"||!("aborted"in f))throw new c(g,"AbortSignal",f)};e.exports.addAbortSignal=function(f,g){if(d(f,"signal"),!n(g)&&!s(g))throw new c("stream",["ReadableStream","WritableStream","Stream"],g);return e.exports.addAbortSignalNoValidate(f,g)},e.exports.addAbortSignalNoValidate=function(f,g){if(typeof f!="object"||!("aborted"in f))return g;let h=n(g)?()=>{g.destroy(new r(void 0,{cause:f.reason}))}:()=>{g[a](new r(void 0,{cause:f.reason}))};if(f.aborted)h();else{u=u||Xe().addAbortListener;let b=u(f,h);l(g,b[t])}return g}}),uu=me((i,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:o,Uint8Array:n}=Be(),{Buffer:s}=(He(),je(qe)),{inspect:a}=Xe();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(l){let c={data:l,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(l){let c={data:l,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let l=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,l}clear(){this.head=this.tail=null,this.length=0}join(l){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=l+c.data;return u}concat(l){if(this.length===0)return s.alloc(0);let c=s.allocUnsafe(l>>>0),u=this.head,d=0;for(;u;)o(c,u.data,d),d+=u.data.length,u=u.next;return c}consume(l,c){let u=this.head.data;if(l<u.length){let d=u.slice(0,l);return this.head.data=u.slice(l),d}return l===u.length?this.shift():c?this._getString(l):this._getBuffer(l)}first(){return this.head.data}*[r](){for(let l=this.head;l;l=l.next)yield l.data}_getString(l){let c="",u=this.head,d=0;do{let f=u.data;if(l>f.length)c+=f,l-=f.length;else{l===f.length?(c+=f,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(f,0,l),this.head=u,u.data=t(f,l));break}++d}while((u=u.next)!==null);return this.length-=d,c}_getBuffer(l){let c=s.allocUnsafe(l),u=l,d=this.head,f=0;do{let g=d.data;if(l>g.length)o(c,g,u-l),l-=g.length;else{l===g.length?(o(c,g,u-l),++f,d.next?this.head=d.next:this.head=this.tail=null):(o(c,new n(g.buffer,g.byteOffset,l),u-l),this.head=d,d.data=g.slice(l));break}++f}while((d=d.next)!==null);return this.length-=f,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),Tr=me((i,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Be(),{validateInteger:o}=lr(),{ERR_INVALID_ARG_VALUE:n}=Ye().codes,s=16*1024,a=16;function l(f,g,h){return f.highWaterMark!=null?f.highWaterMark:g?f[h]:null}function c(f){return f?a:s}function u(f,g){o(g,"value",0),f?a=g:s=g}function d(f,g,h,b){let y=l(g,b,h);if(y!=null){if(!r(y)||y<0){let w=b?`options.${h}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(f.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),du=me((i,e)=>{le(),ue(),ce();var t=(He(),je(qe)),r=t.Buffer;function o(s,a){for(var l in s)a[l]=s[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(o(t,i),i.Buffer=n);function n(s,a,l){return r(s,a,l)}n.prototype=Object.create(r.prototype),o(r,n),n.from=function(s,a,l){if(typeof s=="number")throw new TypeError("Argument must not be a number");return r(s,a,l)},n.alloc=function(s,a,l){if(typeof s!="number")throw new TypeError("Argument must be a number");var c=r(s);return a!==void 0?typeof l=="string"?c.fill(a,l):c.fill(a):c.fill(0),c},n.allocUnsafe=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return r(s)},n.allocUnsafeSlow=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(s)}}),hu=me(i=>{le(),ue(),ce();var e=du().Buffer,t=e.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(m){if(!m)return"utf8";for(var k;;)switch(m){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return m;default:if(k)return;m=(""+m).toLowerCase(),k=!0}}function o(m){var k=r(m);if(typeof k!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return k||m}i.StringDecoder=n;function n(m){this.encoding=o(m);var k;switch(this.encoding){case"utf16le":this.text=f,this.end=g,k=4;break;case"utf8":this.fillLast=c,k=4;break;case"base64":this.text=h,this.end=b,k=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(k)}n.prototype.write=function(m){if(m.length===0)return"";var k,x;if(this.lastNeed){if(k=this.fillLast(m),k===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?k?k+this.text(m,x):this.text(m,x):k||""},n.prototype.end=d,n.prototype.text=u,n.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length};function s(m){return m<=127?0:m>>5===6?2:m>>4===14?3:m>>3===30?4:m>>6===2?-1:-2}function a(m,k,x){var v=k.length-1;if(v<x)return 0;var S=s(k[v]);return S>=0?(S>0&&(m.lastNeed=S-1),S):--v<x||S===-2?0:(S=s(k[v]),S>=0?(S>0&&(m.lastNeed=S-2),S):--v<x||S===-2?0:(S=s(k[v]),S>=0?(S>0&&(S===2?S=0:m.lastNeed=S-3),S):0))}function l(m,k,x){if((k[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&k.length>1){if((k[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&k.length>2&&(k[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var k=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,k,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,k,0,m.length),this.lastNeed-=m.length}function u(m,k){var x=a(this,m,k);if(!this.lastNeed)return m.toString("utf8",k);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",k,v)}function d(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+"�":k}function f(m,k){if((m.length-k)%2===0){var x=m.toString("utf16le",k);if(x){var v=x.charCodeAt(x.length-1);if(v>=55296&&v<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1],x.slice(0,-1)}return x}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",k,m.length-1)}function g(m){var k=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,x)}return k}function h(m,k){var x=(m.length-k)%3;return x===0?m.toString("base64",k):(this.lastNeed=3-x,this.lastTotal=3,x===1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",k,m.length-x))}function b(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+this.lastChar.toString("base64",0,3-this.lastNeed):k}function y(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),As=me((i,e)=>{le(),ue(),ce();var t=jt(),{PromisePrototypeThen:r,SymbolAsyncIterator:o,SymbolIterator:n}=Be(),{Buffer:s}=(He(),je(qe)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ye().codes;function c(u,d,f){let g;if(typeof d=="string"||d instanceof s)return new u({objectMode:!0,...f,read(){this.push(d),this.push(null)}});let h;if(d&&d[o])h=!0,g=d[o]();else if(d&&d[n])h=!1,g=d[n]();else throw new a("iterable",["Iterable"],d);let b=new u({objectMode:!0,highWaterMark:1,...f}),y=!1;b._read=function(){y||(y=!0,m())},b._destroy=function(k,x){r(w(k),()=>t.nextTick(x,k),v=>t.nextTick(x,v||k))};async function w(k){let x=k!=null,v=typeof g.throw=="function";if(x&&v){let{value:S,done:E}=await g.throw(k);if(await S,E)return}if(typeof g.return=="function"){let{value:S}=await g.return();await S}}async function m(){for(;;){try{let{value:k,done:x}=h?await g.next():g.next();if(x)b.push(null);else{let v=k&&typeof k.then=="function"?await k:k;if(v===null)throw y=!1,new l;if(b.push(v))continue;y=!1}}catch(k){b.destroy(k)}break}}return b}e.exports=c}),Cr=me((i,e)=>{le(),ue(),ce();var t=jt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:o,NumberIsNaN:n,NumberParseInt:s,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:f,SymbolAsyncIterator:g,Symbol:h}=Be();e.exports=ae,ae.ReadableState=we;var{EventEmitter:b}=(Rt(),je(At)),{Stream:y,prependListener:w}=Ti(),{Buffer:m}=(He(),je(qe)),{addAbortSignal:k}=Ir(),x=It(),v=Xe().debuglog("stream",C=>{v=C}),S=uu(),E=Vt(),{getHighWaterMark:I,getDefaultHighWaterMark:P}=Tr(),{aggregateTwoErrors:L,codes:{ERR_INVALID_ARG_TYPE:$,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:q,ERR_STREAM_PUSH_AFTER_EOF:F,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:D},AbortError:oe}=Ye(),{validateObject:j}=lr(),W=h("kPaused"),{StringDecoder:re}=hu(),U=As();c(ae.prototype,y.prototype),c(ae,y);var Q=()=>{},{errorOrDestroy:O}=E,J=1,pe=2,ee=4,ve=8,G=16,R=32,ne=64,V=128,Y=256,X=512,be=1024,se=2048,M=4096,H=8192,te=16384,he=32768,fe=65536,ye=1<<17,z=1<<18;function ge(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(N){N?this.state|=C:this.state&=~C}}}a(we.prototype,{objectMode:ge(J),ended:ge(pe),endEmitted:ge(ee),reading:ge(ve),constructed:ge(G),sync:ge(R),needReadable:ge(ne),emittedReadable:ge(V),readableListening:ge(Y),resumeScheduled:ge(X),errorEmitted:ge(be),emitClose:ge(se),autoDestroy:ge(M),destroyed:ge(H),closed:ge(te),closeEmitted:ge(he),multiAwaitDrain:ge(fe),readingMore:ge(ye),dataEmitted:ge(z)});function we(C,N,ke){typeof ke!="boolean"&&(ke=N instanceof yt()),this.state=se|M|G|R,C&&C.objectMode&&(this.state|=J),ke&&C&&C.readableObjectMode&&(this.state|=J),this.highWaterMark=C?I(this,C,"readableHighWaterMark",ke):P(!1),this.buffer=new S,this.length=0,this.pipes=[],this.flowing=null,this[W]=null,C&&C.emitClose===!1&&(this.state&=~se),C&&C.autoDestroy===!1&&(this.state&=~M),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 ae(C){if(!(this instanceof ae))return new ae(C);let N=this instanceof yt();this._readableState=new we(C,this,N),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&&!N&&k(C.signal,this)),y.call(this,C),E.construct(this,()=>{this._readableState.needReadable&&K(this,this._readableState)})}ae.prototype.destroy=E.destroy,ae.prototype._undestroy=E.undestroy,ae.prototype._destroy=function(C,N){N(C)},ae.prototype[b.captureRejectionSymbol]=function(C){this.destroy(C)},ae.prototype[f]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new oe,this.destroy(C)),new u((N,ke)=>x(this,Se=>Se&&Se!==C?ke(Se):N(null)))},ae.prototype.push=function(C,N){return Me(this,C,N,!1)},ae.prototype.unshift=function(C,N){return Me(this,C,N,!0)};function Me(C,N,ke,Se){v("readableAddChunk",N);let Ae=C._readableState,Fe;if((Ae.state&J)===0&&(typeof N=="string"?(ke=ke||Ae.defaultEncoding,Ae.encoding!==ke&&(Se&&Ae.encoding?N=m.from(N,ke).toString(Ae.encoding):(N=m.from(N,ke),ke=""))):N instanceof m?ke="":y._isUint8Array(N)?(N=y._uint8ArrayToBuffer(N),ke=""):N!=null&&(Fe=new $("chunk",["string","Buffer","Uint8Array"],N))),Fe)O(C,Fe);else if(N===null)Ae.state&=~ve,Z(C,Ae);else if((Ae.state&J)!==0||N&&N.length>0)if(Se)if((Ae.state&ee)!==0)O(C,new D);else{if(Ae.destroyed||Ae.errored)return!1;p(C,Ae,N,!0)}else if(Ae.ended)O(C,new F);else{if(Ae.destroyed||Ae.errored)return!1;Ae.state&=~ve,Ae.decoder&&!ke?(N=Ae.decoder.write(N),Ae.objectMode||N.length!==0?p(C,Ae,N,!1):K(C,Ae)):p(C,Ae,N,!1)}else Se||(Ae.state&=~ve,K(C,Ae));return!Ae.ended&&(Ae.length<Ae.highWaterMark||Ae.length===0)}function p(C,N,ke,Se){N.flowing&&N.length===0&&!N.sync&&C.listenerCount("data")>0?((N.state&fe)!==0?N.awaitDrainWriters.clear():N.awaitDrainWriters=null,N.dataEmitted=!0,C.emit("data",ke)):(N.length+=N.objectMode?1:ke.length,Se?N.buffer.unshift(ke):N.buffer.push(ke),(N.state&ne)!==0&&de(C)),K(C,N)}ae.prototype.isPaused=function(){let C=this._readableState;return C[W]===!0||C.flowing===!1},ae.prototype.setEncoding=function(C){let N=new re(C);this._readableState.decoder=N,this._readableState.encoding=this._readableState.decoder.encoding;let ke=this._readableState.buffer,Se="";for(let Ae of ke)Se+=N.write(Ae);return ke.clear(),Se!==""&&ke.push(Se),this._readableState.length=Se.length,this};var _=1073741824;function A(C){if(C>_)throw new q("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function B(C,N){return C<=0||N.length===0&&N.ended?0:(N.state&J)!==0?1:n(C)?N.flowing&&N.length?N.buffer.first().length:N.length:C<=N.length?C:N.ended?N.length:0}ae.prototype.read=function(C){v("read",C),C===void 0?C=NaN:o(C)||(C=s(C,10));let N=this._readableState,ke=C;if(C>N.highWaterMark&&(N.highWaterMark=A(C)),C!==0&&(N.state&=~V),C===0&&N.needReadable&&((N.highWaterMark!==0?N.length>=N.highWaterMark:N.length>0)||N.ended))return v("read: emitReadable",N.length,N.ended),N.length===0&&N.ended?dt(this):de(this),null;if(C=B(C,N),C===0&&N.ended)return N.length===0&&dt(this),null;let Se=(N.state&ne)!==0;if(v("need readable",Se),(N.length===0||N.length-C<N.highWaterMark)&&(Se=!0,v("length less than watermark",Se)),N.ended||N.reading||N.destroyed||N.errored||!N.constructed)Se=!1,v("reading, ended or constructing",Se);else if(Se){v("do read"),N.state|=ve|R,N.length===0&&(N.state|=ne);try{this._read(N.highWaterMark)}catch(Fe){O(this,Fe)}N.state&=~R,N.reading||(C=B(ke,N))}let Ae;return C>0?Ae=tr(C,N):Ae=null,Ae===null?(N.needReadable=N.length<=N.highWaterMark,C=0):(N.length-=C,N.multiAwaitDrain?N.awaitDrainWriters.clear():N.awaitDrainWriters=null),N.length===0&&(N.ended||(N.needReadable=!0),ke!==C&&N.ended&&dt(this)),Ae!==null&&!N.errorEmitted&&!N.closeEmitted&&(N.dataEmitted=!0,this.emit("data",Ae)),Ae};function Z(C,N){if(v("onEofChunk"),!N.ended){if(N.decoder){let ke=N.decoder.end();ke&&ke.length&&(N.buffer.push(ke),N.length+=N.objectMode?1:ke.length)}N.ended=!0,N.sync?de(C):(N.needReadable=!1,N.emittedReadable=!0,_e(C))}}function de(C){let N=C._readableState;v("emitReadable",N.needReadable,N.emittedReadable),N.needReadable=!1,N.emittedReadable||(v("emitReadable",N.flowing),N.emittedReadable=!0,t.nextTick(_e,C))}function _e(C){let N=C._readableState;v("emitReadable_",N.destroyed,N.length,N.ended),!N.destroyed&&!N.errored&&(N.length||N.ended)&&(C.emit("readable"),N.emittedReadable=!1),N.needReadable=!N.flowing&&!N.ended&&N.length<=N.highWaterMark,ct(C)}function K(C,N){!N.readingMore&&N.constructed&&(N.readingMore=!0,t.nextTick(ie,C,N))}function ie(C,N){for(;!N.reading&&!N.ended&&(N.length<N.highWaterMark||N.flowing&&N.length===0);){let ke=N.length;if(v("maybeReadMore read 0"),C.read(0),ke===N.length)break}N.readingMore=!1}ae.prototype._read=function(C){throw new T("_read()")},ae.prototype.pipe=function(C,N){let ke=this,Se=this._readableState;Se.pipes.length===1&&(Se.multiAwaitDrain||(Se.multiAwaitDrain=!0,Se.awaitDrainWriters=new d(Se.awaitDrainWriters?[Se.awaitDrainWriters]:[]))),Se.pipes.push(C),v("pipe count=%d opts=%j",Se.pipes.length,N);let Ae=(!N||N.end!==!1)&&C!==t.stdout&&C!==t.stderr?Je:qt;Se.endEmitted?t.nextTick(Ae):ke.once("end",Ae),C.on("unpipe",Fe);function Fe(pt,St){v("onunpipe"),pt===ke&&St&&St.hasUnpiped===!1&&(St.hasUnpiped=!0,vr())}function Je(){v("onend"),C.end()}let it,yr=!1;function vr(){v("cleanup"),C.removeListener("close",ht),C.removeListener("finish",Lt),it&&C.removeListener("drain",it),C.removeListener("error",Ft),C.removeListener("unpipe",Fe),ke.removeListener("end",Je),ke.removeListener("end",qt),ke.removeListener("data",pn),yr=!0,it&&Se.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&it()}function wr(){yr||(Se.pipes.length===1&&Se.pipes[0]===C?(v("false write response, pause",0),Se.awaitDrainWriters=C,Se.multiAwaitDrain=!1):Se.pipes.length>1&&Se.pipes.includes(C)&&(v("false write response, pause",Se.awaitDrainWriters.size),Se.awaitDrainWriters.add(C)),ke.pause()),it||(it=Te(ke,C),C.on("drain",it))}ke.on("data",pn);function pn(pt){v("ondata");let St=C.write(pt);v("dest.write",St),St===!1&&wr()}function Ft(pt){if(v("onerror",pt),qt(),C.removeListener("error",Ft),C.listenerCount("error")===0){let St=C._writableState||C._readableState;St&&!St.errorEmitted?O(C,pt):C.emit("error",pt)}}w(C,"error",Ft);function ht(){C.removeListener("finish",Lt),qt()}C.once("close",ht);function Lt(){v("onfinish"),C.removeListener("close",ht),qt()}C.once("finish",Lt);function qt(){v("unpipe"),ke.unpipe(C)}return C.emit("pipe",ke),C.writableNeedDrain===!0?wr():Se.flowing||(v("pipe resume"),ke.resume()),C};function Te(C,N){return function(){let ke=C._readableState;ke.awaitDrainWriters===N?(v("pipeOnDrain",1),ke.awaitDrainWriters=null):ke.multiAwaitDrain&&(v("pipeOnDrain",ke.awaitDrainWriters.size),ke.awaitDrainWriters.delete(N)),(!ke.awaitDrainWriters||ke.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}ae.prototype.unpipe=function(C){let N=this._readableState,ke={hasUnpiped:!1};if(N.pipes.length===0)return this;if(!C){let Ae=N.pipes;N.pipes=[],this.pause();for(let Fe=0;Fe<Ae.length;Fe++)Ae[Fe].emit("unpipe",this,{hasUnpiped:!1});return this}let Se=r(N.pipes,C);return Se===-1?this:(N.pipes.splice(Se,1),N.pipes.length===0&&this.pause(),C.emit("unpipe",this,ke),this)},ae.prototype.on=function(C,N){let ke=y.prototype.on.call(this,C,N),Se=this._readableState;return C==="data"?(Se.readableListening=this.listenerCount("readable")>0,Se.flowing!==!1&&this.resume()):C==="readable"&&!Se.endEmitted&&!Se.readableListening&&(Se.readableListening=Se.needReadable=!0,Se.flowing=!1,Se.emittedReadable=!1,v("on readable",Se.length,Se.reading),Se.length?de(this):Se.reading||t.nextTick(Le,this)),ke},ae.prototype.addListener=ae.prototype.on,ae.prototype.removeListener=function(C,N){let ke=y.prototype.removeListener.call(this,C,N);return C==="readable"&&t.nextTick(Ce,this),ke},ae.prototype.off=ae.prototype.removeListener,ae.prototype.removeAllListeners=function(C){let N=y.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Ce,this),N};function Ce(C){let N=C._readableState;N.readableListening=C.listenerCount("readable")>0,N.resumeScheduled&&N[W]===!1?N.flowing=!0:C.listenerCount("data")>0?C.resume():N.readableListening||(N.flowing=null)}function Le(C){v("readable nexttick read 0"),C.read(0)}ae.prototype.resume=function(){let C=this._readableState;return C.flowing||(v("resume"),C.flowing=!C.readableListening,Re(this,C)),C[W]=!1,this};function Re(C,N){N.resumeScheduled||(N.resumeScheduled=!0,t.nextTick(lt,C,N))}function lt(C,N){v("resume",N.reading),N.reading||C.read(0),N.resumeScheduled=!1,C.emit("resume"),ct(C),N.flowing&&!N.reading&&C.read(0)}ae.prototype.pause=function(){return v("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(v("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[W]=!0,this};function ct(C){let N=C._readableState;for(v("flow",N.flowing);N.flowing&&C.read()!==null;);}ae.prototype.wrap=function(C){let N=!1;C.on("data",Se=>{!this.push(Se)&&C.pause&&(N=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",Se=>{O(this,Se)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{N&&C.resume&&(N=!1,C.resume())};let ke=l(C);for(let Se=1;Se<ke.length;Se++){let Ae=ke[Se];this[Ae]===void 0&&typeof C[Ae]=="function"&&(this[Ae]=C[Ae].bind(C))}return this},ae.prototype[g]=function(){return Ge(this)},ae.prototype.iterator=function(C){return C!==void 0&&j(C,"options"),Ge(this,C)};function Ge(C,N){typeof C.read!="function"&&(C=ae.wrap(C,{objectMode:!0}));let ke=ut(C,N);return ke.stream=C,ke}async function*ut(C,N){let ke=Q;function Se(Je){this===C?(ke(),ke=Q):ke=Je}C.on("readable",Se);let Ae,Fe=x(C,{writable:!1},Je=>{Ae=Je?L(Ae,Je):null,ke(),ke=Q});try{for(;;){let Je=C.destroyed?null:C.read();if(Je!==null)yield Je;else{if(Ae)throw Ae;if(Ae===null)return;await new u(Se)}}}catch(Je){throw Ae=L(Ae,Je),Ae}finally{(Ae||N?.destroyOnReturn!==!1)&&(Ae===void 0||C._readableState.autoDestroy)?E.destroyer(C,null):(C.off("readable",Se),Fe())}}a(ae.prototype,{readable:{__proto__:null,get(){let C=this._readableState;return!!C&&C.readable!==!1&&!C.destroyed&&!C.errorEmitted&&!C.endEmitted},set(C){this._readableState&&(this._readableState.readable=!!C)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(C){this._readableState&&(this._readableState.flowing=C)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(C){this._readableState&&(this._readableState.destroyed=C)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),a(we.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[W]!==!1},set(C){this[W]=!!C}}}),ae._fromList=tr;function tr(C,N){if(N.length===0)return null;let ke;return N.objectMode?ke=N.buffer.shift():!C||C>=N.length?(N.decoder?ke=N.buffer.join(""):N.buffer.length===1?ke=N.buffer.first():ke=N.buffer.concat(N.length),N.buffer.clear()):ke=N.buffer.consume(C,N.decoder),ke}function dt(C){let N=C._readableState;v("endReadable",N.endEmitted),N.endEmitted||(N.ended=!0,t.nextTick(et,N,C))}function et(C,N){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,N.emit("end"),N.writable&&N.allowHalfOpen===!1)t.nextTick(hn,N);else if(C.autoDestroy){let ke=N._writableState;(!ke||ke.autoDestroy&&(ke.finished||ke.writable===!1))&&N.destroy()}}}function hn(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}ae.from=function(C,N){return U(ae,C,N)};var rr;function br(){return rr===void 0&&(rr={}),rr}ae.fromWeb=function(C,N){return br().newStreamReadableFromReadableStream(C,N)},ae.toWeb=function(C,N){return br().newReadableStreamFromStreamReadable(C,N)},ae.wrap=function(C,N){var ke,Se;return new ae({objectMode:(ke=(Se=C.readableObjectMode)!==null&&Se!==void 0?Se:C.objectMode)!==null&&ke!==void 0?ke:!0,...N,destroy(Ae,Fe){E.destroyer(C,Ae),Fe(Ae)}}).wrap(C)}}),Ci=me((i,e)=>{le(),ue(),ce();var t=jt(),{ArrayPrototypeSlice:r,Error:o,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:s,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=Be();e.exports=j,j.WritableState=D;var{EventEmitter:f}=(Rt(),je(At)),g=Ti().Stream,{Buffer:h}=(He(),je(qe)),b=Vt(),{addAbortSignal:y}=Ir(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=Tr(),{ERR_INVALID_ARG_TYPE:k,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:S,ERR_STREAM_DESTROYED:E,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:P,ERR_STREAM_WRITE_AFTER_END:L,ERR_UNKNOWN_ENCODING:$}=Ye().codes,{errorOrDestroy:T}=b;l(j.prototype,g.prototype),l(j,g);function q(){}var F=u("kOnFinished");function D(M,H,te){typeof te!="boolean"&&(te=H instanceof yt()),this.objectMode=!!(M&&M.objectMode),te&&(this.objectMode=this.objectMode||!!(M&&M.writableObjectMode)),this.highWaterMark=M?w(this,M,"writableHighWaterMark",te):m(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let he=!!(M&&M.decodeStrings===!1);this.decodeStrings=!he,this.defaultEncoding=M&&M.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=O.bind(void 0,H),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,oe(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!M||M.emitClose!==!1,this.autoDestroy=!M||M.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[F]=[]}function oe(M){M.buffered=[],M.bufferedIndex=0,M.allBuffers=!0,M.allNoop=!0}D.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},s(D.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function j(M){let H=this instanceof yt();if(!H&&!n(j,this))return new j(M);this._writableState=new D(M,this,H),M&&(typeof M.write=="function"&&(this._write=M.write),typeof M.writev=="function"&&(this._writev=M.writev),typeof M.destroy=="function"&&(this._destroy=M.destroy),typeof M.final=="function"&&(this._final=M.final),typeof M.construct=="function"&&(this._construct=M.construct),M.signal&&y(M.signal,this)),g.call(this,M),b.construct(this,()=>{let te=this._writableState;te.writing||ve(this,te),V(this,te)})}s(j,d,{__proto__:null,value:function(M){return n(this,M)?!0:this!==j?!1:M&&M._writableState instanceof D}}),j.prototype.pipe=function(){T(this,new S)};function W(M,H,te,he){let fe=M._writableState;if(typeof te=="function")he=te,te=fe.defaultEncoding;else{if(!te)te=fe.defaultEncoding;else if(te!=="buffer"&&!h.isEncoding(te))throw new $(te);typeof he!="function"&&(he=q)}if(H===null)throw new P;if(!fe.objectMode)if(typeof H=="string")fe.decodeStrings!==!1&&(H=h.from(H,te),te="buffer");else if(H instanceof h)te="buffer";else if(g._isUint8Array(H))H=g._uint8ArrayToBuffer(H),te="buffer";else throw new k("chunk",["string","Buffer","Uint8Array"],H);let ye;return fe.ending?ye=new L:fe.destroyed&&(ye=new E("write")),ye?(t.nextTick(he,ye),T(M,ye,!0),ye):(fe.pendingcb++,re(M,fe,H,te,he))}j.prototype.write=function(M,H,te){return W(this,M,H,te)===!0},j.prototype.cork=function(){this._writableState.corked++},j.prototype.uncork=function(){let M=this._writableState;M.corked&&(M.corked--,M.writing||ve(this,M))},j.prototype.setDefaultEncoding=function(M){if(typeof M=="string"&&(M=c(M)),!h.isEncoding(M))throw new $(M);return this._writableState.defaultEncoding=M,this};function re(M,H,te,he,fe){let ye=H.objectMode?1:te.length;H.length+=ye;let z=H.length<H.highWaterMark;return z||(H.needDrain=!0),H.writing||H.corked||H.errored||!H.constructed?(H.buffered.push({chunk:te,encoding:he,callback:fe}),H.allBuffers&&he!=="buffer"&&(H.allBuffers=!1),H.allNoop&&fe!==q&&(H.allNoop=!1)):(H.writelen=ye,H.writecb=fe,H.writing=!0,H.sync=!0,M._write(te,he,H.onwrite),H.sync=!1),z&&!H.errored&&!H.destroyed}function U(M,H,te,he,fe,ye,z){H.writelen=he,H.writecb=z,H.writing=!0,H.sync=!0,H.destroyed?H.onwrite(new E("write")):te?M._writev(fe,H.onwrite):M._write(fe,ye,H.onwrite),H.sync=!1}function Q(M,H,te,he){--H.pendingcb,he(te),ee(H),T(M,te)}function O(M,H){let te=M._writableState,he=te.sync,fe=te.writecb;if(typeof fe!="function"){T(M,new v);return}te.writing=!1,te.writecb=null,te.length-=te.writelen,te.writelen=0,H?(H.stack,te.errored||(te.errored=H),M._readableState&&!M._readableState.errored&&(M._readableState.errored=H),he?t.nextTick(Q,M,te,H,fe):Q(M,te,H,fe)):(te.buffered.length>te.bufferedIndex&&ve(M,te),he?te.afterWriteTickInfo!==null&&te.afterWriteTickInfo.cb===fe?te.afterWriteTickInfo.count++:(te.afterWriteTickInfo={count:1,cb:fe,stream:M,state:te},t.nextTick(J,te.afterWriteTickInfo)):pe(M,te,1,fe))}function J({stream:M,state:H,count:te,cb:he}){return H.afterWriteTickInfo=null,pe(M,H,te,he)}function pe(M,H,te,he){for(!H.ending&&!M.destroyed&&H.length===0&&H.needDrain&&(H.needDrain=!1,M.emit("drain"));te-- >0;)H.pendingcb--,he();H.destroyed&&ee(H),V(M,H)}function ee(M){if(M.writing)return;for(let fe=M.bufferedIndex;fe<M.buffered.length;++fe){var H;let{chunk:ye,callback:z}=M.buffered[fe],ge=M.objectMode?1:ye.length;M.length-=ge,z((H=M.errored)!==null&&H!==void 0?H:new E("write"))}let te=M[F].splice(0);for(let fe=0;fe<te.length;fe++){var he;te[fe]((he=M.errored)!==null&&he!==void 0?he:new E("end"))}oe(M)}function ve(M,H){if(H.corked||H.bufferProcessing||H.destroyed||!H.constructed)return;let{buffered:te,bufferedIndex:he,objectMode:fe}=H,ye=te.length-he;if(!ye)return;let z=he;if(H.bufferProcessing=!0,ye>1&&M._writev){H.pendingcb-=ye-1;let ge=H.allNoop?q:ae=>{for(let Me=z;Me<te.length;++Me)te[Me].callback(ae)},we=H.allNoop&&z===0?te:r(te,z);we.allBuffers=H.allBuffers,U(M,H,!0,H.length,we,"",ge),oe(H)}else{do{let{chunk:ge,encoding:we,callback:ae}=te[z];te[z++]=null;let Me=fe?1:ge.length;U(M,H,!1,Me,ge,we,ae)}while(z<te.length&&!H.writing);z===te.length?oe(H):z>256?(te.splice(0,z),H.bufferedIndex=0):H.bufferedIndex=z}H.bufferProcessing=!1}j.prototype._write=function(M,H,te){if(this._writev)this._writev([{chunk:M,encoding:H}],te);else throw new x("_write()")},j.prototype._writev=null,j.prototype.end=function(M,H,te){let he=this._writableState;typeof M=="function"?(te=M,M=null,H=null):typeof H=="function"&&(te=H,H=null);let fe;if(M!=null){let ye=W(this,M,H);ye instanceof o&&(fe=ye)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,V(this,he,!0),he.ended=!0):he.finished?fe=new I("end"):he.destroyed&&(fe=new E("end"))),typeof te=="function"&&(fe||he.finished?t.nextTick(te,fe):he[F].push(te)),this};function G(M){return M.ending&&!M.destroyed&&M.constructed&&M.length===0&&!M.errored&&M.buffered.length===0&&!M.finished&&!M.writing&&!M.errorEmitted&&!M.closeEmitted}function R(M,H){let te=!1;function he(fe){if(te){T(M,fe??v());return}if(te=!0,H.pendingcb--,fe){let ye=H[F].splice(0);for(let z=0;z<ye.length;z++)ye[z](fe);T(M,fe,H.sync)}else G(H)&&(H.prefinished=!0,M.emit("prefinish"),H.pendingcb++,t.nextTick(Y,M,H))}H.sync=!0,H.pendingcb++;try{M._final(he)}catch(fe){he(fe)}H.sync=!1}function ne(M,H){!H.prefinished&&!H.finalCalled&&(typeof M._final=="function"&&!H.destroyed?(H.finalCalled=!0,R(M,H)):(H.prefinished=!0,M.emit("prefinish")))}function V(M,H,te){G(H)&&(ne(M,H),H.pendingcb===0&&(te?(H.pendingcb++,t.nextTick((he,fe)=>{G(fe)?Y(he,fe):fe.pendingcb--},M,H)):G(H)&&(H.pendingcb++,Y(M,H))))}function Y(M,H){H.pendingcb--,H.finished=!0;let te=H[F].splice(0);for(let he=0;he<te.length;he++)te[he]();if(M.emit("finish"),H.autoDestroy){let he=M._readableState;(!he||he.autoDestroy&&(he.endEmitted||he.readable===!1))&&M.destroy()}}a(j.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(M){this._writableState&&(this._writableState.destroyed=M)}},writable:{__proto__:null,get(){let M=this._writableState;return!!M&&M.writable!==!1&&!M.destroyed&&!M.errored&&!M.ending&&!M.ended},set(M){this._writableState&&(this._writableState.writable=!!M)}},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 M=this._writableState;return M?!M.destroyed&&!M.ending&&M.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 X=b.destroy;j.prototype.destroy=function(M,H){let te=this._writableState;return!te.destroyed&&(te.bufferedIndex<te.buffered.length||te[F].length)&&t.nextTick(ee,te),X.call(this,M,H),this},j.prototype._undestroy=b.undestroy,j.prototype._destroy=function(M,H){H(M)},j.prototype[f.captureRejectionSymbol]=function(M){this.destroy(M)};var be;function se(){return be===void 0&&(be={}),be}j.fromWeb=function(M,H){return se().newStreamWritableFromWritableStream(M,H)},j.toWeb=function(M){return se().newWritableStreamFromStreamWritable(M)}}),pu=me((i,e)=>{le(),ue(),ce();var t=jt(),r=(He(),je(qe)),{isReadable:o,isWritable:n,isIterable:s,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:f}=bt(),g=It(),{AbortError:h,codes:{ERR_INVALID_ARG_TYPE:b,ERR_INVALID_RETURN_VALUE:y}}=Ye(),{destroyer:w}=Vt(),m=yt(),k=Cr(),x=Ci(),{createDeferredPromise:v}=Xe(),S=As(),E=globalThis.Blob||r.Blob,I=typeof E<"u"?function(F){return F instanceof E}:function(F){return!1},P=globalThis.AbortController||sr().AbortController,{FunctionPrototypeCall:L}=Be(),$=class extends m{constructor(F){super(F),F?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),F?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function F(D,oe){if(u(D))return D;if(l(D))return q({readable:D});if(c(D))return q({writable:D});if(a(D))return q({writable:!1,readable:!1});if(d(D))return q({readable:k.fromWeb(D)});if(f(D))return q({writable:x.fromWeb(D)});if(typeof D=="function"){let{value:W,write:re,final:U,destroy:Q}=T(D);if(s(W))return S($,W,{objectMode:!0,write:re,final:U,destroy:Q});let O=W?.then;if(typeof O=="function"){let J,pe=L(O,W,ee=>{if(ee!=null)throw new y("nully","body",ee)},ee=>{w(J,ee)});return J=new $({objectMode:!0,readable:!1,write:re,final(ee){U(async()=>{try{await pe,t.nextTick(ee,null)}catch(ve){t.nextTick(ee,ve)}})},destroy:Q})}throw new y("Iterable, AsyncIterable or AsyncFunction",oe,W)}if(I(D))return F(D.arrayBuffer());if(s(D))return S($,D,{objectMode:!0,writable:!1});if(d(D?.readable)&&f(D?.writable))return $.fromWeb(D);if(typeof D?.writable=="object"||typeof D?.readable=="object"){let W=D!=null&&D.readable?l(D?.readable)?D?.readable:F(D.readable):void 0,re=D!=null&&D.writable?c(D?.writable)?D?.writable:F(D.writable):void 0;return q({readable:W,writable:re})}let j=D?.then;if(typeof j=="function"){let W;return L(j,D,re=>{re!=null&&W.push(re),W.push(null)},re=>{w(W,re)}),W=new $({objectMode:!0,writable:!1,read(){}})}throw new b(oe,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],D)};function T(F){let{promise:D,resolve:oe}=v(),j=new P,W=j.signal;return{value:F((async function*(){for(;;){let re=D;D=null;let{chunk:U,done:Q,cb:O}=await re;if(t.nextTick(O),Q)return;if(W.aborted)throw new h(void 0,{cause:W.reason});({promise:D,resolve:oe}=v()),yield U}})(),{signal:W}),write(re,U,Q){let O=oe;oe=null,O({chunk:re,done:!1,cb:Q})},final(re){let U=oe;oe=null,U({done:!0,cb:re})},destroy(re,U){j.abort(),U(re)}}}function q(F){let D=F.readable&&typeof F.readable.read!="function"?k.wrap(F.readable):F.readable,oe=F.writable,j=!!o(D),W=!!n(oe),re,U,Q,O,J;function pe(ee){let ve=O;O=null,ve?ve(ee):ee&&J.destroy(ee)}return J=new $({readableObjectMode:!!(D!=null&&D.readableObjectMode),writableObjectMode:!!(oe!=null&&oe.writableObjectMode),readable:j,writable:W}),W&&(g(oe,ee=>{W=!1,ee&&w(D,ee),pe(ee)}),J._write=function(ee,ve,G){oe.write(ee,ve)?G():re=G},J._final=function(ee){oe.end(),U=ee},oe.on("drain",function(){if(re){let ee=re;re=null,ee()}}),oe.on("finish",function(){if(U){let ee=U;U=null,ee()}})),j&&(g(D,ee=>{j=!1,ee&&w(D,ee),pe(ee)}),D.on("readable",function(){if(Q){let ee=Q;Q=null,ee()}}),D.on("end",function(){J.push(null)}),J._read=function(){for(;;){let ee=D.read();if(ee===null){Q=J._read;return}if(!J.push(ee))return}}),J._destroy=function(ee,ve){!ee&&O!==null&&(ee=new h),Q=null,re=null,U=null,O===null?ve(ee):(O=ve,w(oe,ee),w(D,ee))},J}}),yt=me((i,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:o,ObjectSetPrototypeOf:n}=Be();e.exports=l;var s=Cr(),a=Ci();n(l.prototype,s.prototype),n(l,s);{let f=o(a.prototype);for(let g=0;g<f.length;g++){let h=f[g];l.prototype[h]||(l.prototype[h]=a.prototype[h])}}function l(f){if(!(this instanceof l))return new l(f);s.call(this,f),a.call(this,f),f?(this.allowHalfOpen=f.allowHalfOpen!==!1,f.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),f.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}t(l.prototype,{writable:{__proto__:null,...r(a.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(a.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(a.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(a.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(a.prototype,"writableLength")},writableFinished:{__proto__:null,...r(a.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(a.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(a.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(a.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(f){this._readableState&&this._writableState&&(this._readableState.destroyed=f,this._writableState.destroyed=f)}}});var c;function u(){return c===void 0&&(c={}),c}l.fromWeb=function(f,g){return u().newStreamDuplexFromReadableWritablePair(f,g)},l.toWeb=function(f){return u().newReadableWritablePairFromDuplex(f)};var d;l.from=function(f){return d||(d=pu()),d(f,"body")}}),Is=me((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Be();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:o}=Ye().codes,n=yt(),{getHighWaterMark:s}=Tr();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(d){if(!(this instanceof l))return new l(d);let f=d?s(this,d,"readableHighWaterMark",!0):null;f===0&&(d={...d,highWaterMark:null,readableHighWaterMark:f,writableHighWaterMark:d.writableHighWaterMark||0}),n.call(this,d),this._readableState.sync=!1,this[a]=null,d&&(typeof d.transform=="function"&&(this._transform=d.transform),typeof d.flush=="function"&&(this._flush=d.flush)),this.on("prefinish",u)}function c(d){typeof this._flush=="function"&&!this.destroyed?this._flush((f,g)=>{if(f){d?d(f):this.destroy(f);return}g!=null&&this.push(g),this.push(null),d&&d()}):(this.push(null),d&&d())}function u(){this._final!==c&&c.call(this)}l.prototype._final=c,l.prototype._transform=function(d,f,g){throw new o("_transform()")},l.prototype._write=function(d,f,g){let h=this._readableState,b=this._writableState,y=h.length;this._transform(d,f,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),b.ended||y===h.length||h.length<h.highWaterMark?g():this[a]=g})},l.prototype._read=function(){if(this[a]){let d=this[a];this[a]=null,d()}}}),Ts=me((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Be();e.exports=o;var r=Is();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,s,a){a(null,n)}}),Pi=me((i,e)=>{le(),ue(),ce();var t=jt(),{ArrayIsArray:r,Promise:o,SymbolAsyncIterator:n,SymbolDispose:s}=Be(),a=It(),{once:l}=Xe(),c=Vt(),u=yt(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:h,ERR_STREAM_DESTROYED:b,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ye(),{validateFunction:m,validateAbortSignal:k}=lr(),{isIterable:x,isReadable:v,isReadableNodeStream:S,isNodeStream:E,isTransformStream:I,isWebStream:P,isReadableStream:L,isReadableFinished:$}=bt(),T=globalThis.AbortController||sr().AbortController,q,F,D;function oe(ee,ve,G){let R=!1;ee.on("close",()=>{R=!0});let ne=a(ee,{readable:ve,writable:G},V=>{R=!V});return{destroy:V=>{R||(R=!0,c.destroyer(ee,V||new b("pipe")))},cleanup:ne}}function j(ee){return m(ee[ee.length-1],"streams[stream.length - 1]"),ee.pop()}function W(ee){if(x(ee))return ee;if(S(ee))return re(ee);throw new f("val",["Readable","Iterable","AsyncIterable"],ee)}async function*re(ee){F||(F=Cr()),yield*F.prototype[n].call(ee)}async function U(ee,ve,G,{end:R}){let ne,V=null,Y=se=>{if(se&&(ne=se),V){let M=V;V=null,M()}},X=()=>new o((se,M)=>{ne?M(ne):V=()=>{ne?M(ne):se()}});ve.on("drain",Y);let be=a(ve,{readable:!1},Y);try{ve.writableNeedDrain&&await X();for await(let se of ee)ve.write(se)||await X();R&&(ve.end(),await X()),G()}catch(se){G(ne!==se?d(ne,se):se)}finally{be(),ve.off("drain",Y)}}async function Q(ee,ve,G,{end:R}){I(ve)&&(ve=ve.writable);let ne=ve.getWriter();try{for await(let V of ee)await ne.ready,ne.write(V).catch(()=>{});await ne.ready,R&&await ne.close(),G()}catch(V){try{await ne.abort(V),G(V)}catch(Y){G(Y)}}}function O(...ee){return J(ee,l(j(ee)))}function J(ee,ve,G){if(ee.length===1&&r(ee[0])&&(ee=ee[0]),ee.length<2)throw new h("streams");let R=new T,ne=R.signal,V=G?.signal,Y=[];k(V,"options.signal");function X(){fe(new w)}D=D||Xe().addAbortListener;let be;V&&(be=D(V,X));let se,M,H=[],te=0;function he(we){fe(we,--te===0)}function fe(we,ae){var Me;if(we&&(!se||se.code==="ERR_STREAM_PREMATURE_CLOSE")&&(se=we),!(!se&&!ae)){for(;H.length;)H.shift()(se);(Me=be)===null||Me===void 0||Me[s](),R.abort(),ae&&(se||Y.forEach(p=>p()),t.nextTick(ve,se,M))}}let ye;for(let we=0;we<ee.length;we++){let ae=ee[we],Me=we<ee.length-1,p=we>0,_=Me||G?.end!==!1,A=we===ee.length-1;if(E(ae)){let B=function(Z){Z&&Z.name!=="AbortError"&&Z.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(Z)};if(_){let{destroy:Z,cleanup:de}=oe(ae,Me,p);H.push(Z),v(ae)&&A&&Y.push(de)}ae.on("error",B),v(ae)&&A&&Y.push(()=>{ae.removeListener("error",B)})}if(we===0)if(typeof ae=="function"){if(ye=ae({signal:ne}),!x(ye))throw new g("Iterable, AsyncIterable or Stream","source",ye)}else x(ae)||S(ae)||I(ae)?ye=ae:ye=u.from(ae);else if(typeof ae=="function"){if(I(ye)){var z;ye=W((z=ye)===null||z===void 0?void 0:z.readable)}else ye=W(ye);if(ye=ae(ye,{signal:ne}),Me){if(!x(ye,!0))throw new g("AsyncIterable",`transform[${we-1}]`,ye)}else{var ge;q||(q=Ts());let B=new q({objectMode:!0}),Z=(ge=ye)===null||ge===void 0?void 0:ge.then;if(typeof Z=="function")te++,Z.call(ye,K=>{M=K,K!=null&&B.write(K),_&&B.end(),t.nextTick(he)},K=>{B.destroy(K),t.nextTick(he,K)});else if(x(ye,!0))te++,U(ye,B,he,{end:_});else if(L(ye)||I(ye)){let K=ye.readable||ye;te++,U(K,B,he,{end:_})}else throw new g("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:de,cleanup:_e}=oe(ye,!1,!0);H.push(de),A&&Y.push(_e)}}else if(E(ae)){if(S(ye)){te+=2;let B=pe(ye,ae,he,{end:_});v(ae)&&A&&Y.push(B)}else if(I(ye)||L(ye)){let B=ye.readable||ye;te++,U(B,ae,he,{end:_})}else if(x(ye))te++,U(ye,ae,he,{end:_});else throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else if(P(ae)){if(S(ye))te++,Q(W(ye),ae,he,{end:_});else if(L(ye)||x(ye))te++,Q(ye,ae,he,{end:_});else if(I(ye))te++,Q(ye.readable,ae,he,{end:_});else throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else ye=u.from(ae)}return(ne!=null&&ne.aborted||V!=null&&V.aborted)&&t.nextTick(X),ye}function pe(ee,ve,G,{end:R}){let ne=!1;if(ve.on("close",()=>{ne||G(new y)}),ee.pipe(ve,{end:!1}),R){let V=function(){ne=!0,ve.end()};$(ee)?t.nextTick(V):ee.once("end",V)}else G();return a(ee,{readable:!0,writable:!1},V=>{let Y=ee._readableState;V&&V.code==="ERR_STREAM_PREMATURE_CLOSE"&&Y&&Y.ended&&!Y.errored&&!Y.errorEmitted?ee.once("end",G).once("error",G):G(V)}),a(ve,{readable:!1,writable:!0},G)}e.exports={pipelineImpl:J,pipeline:O}}),Cs=me((i,e)=>{le(),ue(),ce();var{pipeline:t}=Pi(),r=yt(),{destroyer:o}=Vt(),{isNodeStream:n,isReadable:s,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=bt(),{AbortError:f,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:h}}=Ye(),b=It();e.exports=function(...y){if(y.length===0)throw new h("streams");if(y.length===1)return r.from(y[0]);let w=[...y];if(typeof y[0]=="function"&&(y[0]=r.from(y[0])),typeof y[y.length-1]=="function"){let T=y.length-1;y[T]=r.from(y[T])}for(let T=0;T<y.length;++T)if(!(!n(y[T])&&!l(y[T]))){if(T<y.length-1&&!(s(y[T])||d(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(y[T])||u(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be writable")}let m,k,x,v,S;function E(T){let q=v;v=null,q?q(T):T?S.destroy(T):!$&&!L&&S.destroy()}let I=y[0],P=t(y,E),L=!!(a(I)||u(I)||c(I)),$=!!(s(P)||d(P)||c(P));if(S=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(P!=null&&P.readableObjectMode),writable:L,readable:$}),L){if(n(I))S._write=function(q,F,D){I.write(q,F)?D():m=D},S._final=function(q){I.end(),k=q},I.on("drain",function(){if(m){let q=m;m=null,q()}});else if(l(I)){let q=(c(I)?I.writable:I).getWriter();S._write=async function(F,D,oe){try{await q.ready,q.write(F).catch(()=>{}),oe()}catch(j){oe(j)}},S._final=async function(F){try{await q.ready,q.close().catch(()=>{}),k=F}catch(D){F(D)}}}let T=c(P)?P.readable:P;b(T,()=>{if(k){let q=k;k=null,q()}})}if($){if(n(P))P.on("readable",function(){if(x){let T=x;x=null,T()}}),P.on("end",function(){S.push(null)}),S._read=function(){for(;;){let T=P.read();if(T===null){x=S._read;return}if(!S.push(T))return}};else if(l(P)){let T=(c(P)?P.readable:P).getReader();S._read=async function(){for(;;)try{let{value:q,done:F}=await T.read();if(!S.push(q))return;if(F){S.push(null);return}}catch{return}}}}return S._destroy=function(T,q){!T&&v!==null&&(T=new f),x=null,m=null,k=null,v===null?q(T):(v=q,n(P)&&o(P,T))},S}}),fu=me((i,e)=>{le(),ue(),ce();var t=globalThis.AbortController||sr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:s},AbortError:a}=Ye(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=lr(),d=Be().Symbol("kWeak"),f=Be().Symbol("kResistStopPropagation"),{finished:g}=It(),h=Cs(),{addAbortSignalNoValidate:b}=Ir(),{isWritable:y,isNodeStream:w}=bt(),{deprecate:m}=Xe(),{ArrayPrototypePush:k,Boolean:x,MathFloor:v,Number:S,NumberIsNaN:E,Promise:I,PromiseReject:P,PromiseResolve:L,PromisePrototypeThen:$,Symbol:T}=Be(),q=T("kEmpty"),F=T("kEof");function D(V,Y){if(Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),w(V)&&!y(V))throw new r("stream",V,"must be writable");let X=h(this,V);return Y!=null&&Y.signal&&b(Y.signal,X),X}function oe(V,Y){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal");let X=1;Y?.concurrency!=null&&(X=v(Y.concurrency));let be=X-1;return Y?.highWaterMark!=null&&(be=v(Y.highWaterMark)),c(X,"options.concurrency",1),c(be,"options.highWaterMark",0),be+=X,(async function*(){let se=Xe().AbortSignalAny([Y?.signal].filter(x)),M=this,H=[],te={signal:se},he,fe,ye=!1,z=0;function ge(){ye=!0,we()}function we(){z-=1,ae()}function ae(){fe&&!ye&&z<X&&H.length<be&&(fe(),fe=null)}async function Me(){try{for await(let p of M){if(ye)return;if(se.aborted)throw new a;try{if(p=V(p,te),p===q)continue;p=L(p)}catch(_){p=P(_)}z+=1,$(p,we,ge),H.push(p),he&&(he(),he=null),!ye&&(H.length>=be||z>=X)&&await new I(_=>{fe=_})}H.push(F)}catch(p){let _=P(p);$(_,we,ge),H.push(_)}finally{ye=!0,he&&(he(),he=null)}}Me();try{for(;;){for(;H.length>0;){let p=await H[0];if(p===F)return;if(se.aborted)throw new a;p!==q&&(yield p),H.shift(),ae()}await new I(p=>{he=p})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function j(V=void 0){return V!=null&&u(V,"options"),V?.signal!=null&&l(V.signal,"options.signal"),(async function*(){let Y=0;for await(let be of this){var X;if(V!=null&&(X=V.signal)!==null&&X!==void 0&&X.aborted)throw new a({cause:V.signal.reason});yield[Y++,be]}}).call(this)}async function W(V,Y=void 0){for await(let X of O.call(this,V,Y))return!0;return!1}async function re(V,Y=void 0){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);return!await W.call(this,async(...X)=>!await V(...X),Y)}async function U(V,Y){for await(let X of O.call(this,V,Y))return X}async function Q(V,Y){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);async function X(be,se){return await V(be,se),q}for await(let be of oe.call(this,X,Y));}function O(V,Y){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);async function X(be,se){return await V(be,se)?be:q}return oe.call(this,X,Y)}var J=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function pe(V,Y,X){var be;if(typeof V!="function")throw new o("reducer",["Function","AsyncFunction"],V);X!=null&&u(X,"options"),X?.signal!=null&&l(X.signal,"options.signal");let se=arguments.length>1;if(X!=null&&(be=X.signal)!==null&&be!==void 0&&be.aborted){let fe=new a(void 0,{cause:X.signal.reason});throw this.once("error",()=>{}),await g(this.destroy(fe)),fe}let M=new t,H=M.signal;if(X!=null&&X.signal){let fe={once:!0,[d]:this,[f]:!0};X.signal.addEventListener("abort",()=>M.abort(),fe)}let te=!1;try{for await(let fe of this){var he;if(te=!0,X!=null&&(he=X.signal)!==null&&he!==void 0&&he.aborted)throw new a;se?Y=await V(Y,fe,{signal:H}):(Y=fe,se=!0)}if(!te&&!se)throw new J}finally{M.abort()}return Y}async function ee(V){V!=null&&u(V,"options"),V?.signal!=null&&l(V.signal,"options.signal");let Y=[];for await(let be of this){var X;if(V!=null&&(X=V.signal)!==null&&X!==void 0&&X.aborted)throw new a(void 0,{cause:V.signal.reason});k(Y,be)}return Y}function ve(V,Y){let X=oe.call(this,V,Y);return(async function*(){for await(let be of X)yield*be}).call(this)}function G(V){if(V=S(V),E(V))return 0;if(V<0)throw new s("number",">= 0",V);return V}function R(V,Y=void 0){return Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),V=G(V),(async function*(){var X;if(Y!=null&&(X=Y.signal)!==null&&X!==void 0&&X.aborted)throw new a;for await(let se of this){var be;if(Y!=null&&(be=Y.signal)!==null&&be!==void 0&&be.aborted)throw new a;V--<=0&&(yield se)}}).call(this)}function ne(V,Y=void 0){return Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),V=G(V),(async function*(){var X;if(Y!=null&&(X=Y.signal)!==null&&X!==void 0&&X.aborted)throw new a;for await(let se of this){var be;if(Y!=null&&(be=Y.signal)!==null&&be!==void 0&&be.aborted)throw new a;if(V-- >0&&(yield se),V<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(j,"readable.asIndexedPairs will be removed in a future version."),drop:R,filter:O,flatMap:ve,map:oe,take:ne,compose:D},e.exports.promiseReturningOperators={every:re,forEach:Q,reduce:pe,toArray:ee,some:W,find:U}}),Ps=me((i,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Be(),{isIterable:o,isNodeStream:n,isWebStream:s}=bt(),{pipelineImpl:a}=Pi(),{finished:l}=It();Os();function c(...u){return new r((d,f)=>{let g,h,b=u[u.length-1];if(b&&typeof b=="object"&&!n(b)&&!o(b)&&!s(b)){let y=t(u);g=y.signal,h=y.end}a(u,(y,w)=>{y?f(y):d(w)},{signal:g,end:h})})}e.exports={finished:l,pipeline:c}}),Os=me((i,e)=>{le(),ue(),ce();var{Buffer:t}=(He(),je(qe)),{ObjectDefineProperty:r,ObjectKeys:o,ReflectApply:n}=Be(),{promisify:{custom:s}}=Xe(),{streamReturningOperators:a,promiseReturningOperators:l}=fu(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ye(),u=Cs(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:f}=Tr(),{pipeline:g}=Pi(),{destroyer:h}=Vt(),b=It(),y=Ps(),w=bt(),m=e.exports=Ti().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=Cr();for(let x of o(a)){let v=function(...E){if(new.target)throw c();return m.Readable.from(n(S,this,E))},S=a[x];r(v,"name",{__proto__:null,value:S.name}),r(v,"length",{__proto__:null,value:S.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let x of o(l)){let v=function(...E){if(new.target)throw c();return n(S,this,E)},S=l[x];r(v,"name",{__proto__:null,value:S.name}),r(v,"length",{__proto__:null,value:S.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=Ci(),m.Duplex=yt(),m.Transform=Is(),m.PassThrough=Ts(),m.pipeline=g;var{addAbortSignal:k}=Ir();m.addAbortSignal=k,m.finished=b,m.destroy=h,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=f,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(g,s,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(b,s,{__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)}}),$t=me((i,e)=>{le(),ue(),ce();var t=Os(),r=Ps(),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}),mu=me((i,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}}}),gu=me((i,e)=>{le(),ue(),ce();var{Buffer:t}=(He(),je(qe)),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 s=0;for(let a=0;a<this._bufs.length;a++){let l=s+this._bufs[a].length;if(n<l||a===this._bufs.length-1)return[a,n-s];s=l}},o.prototype._reverseOffset=function(n){let s=n[0],a=n[1];for(let l=0;l<s;l++)a+=this._bufs[l].length;return a},o.prototype.getBuffers=function(){return this._bufs},o.prototype.get=function(n){if(n>this.length||n<0)return;let s=this._offset(n);return this._bufs[s[0]][s[1]]},o.prototype.slice=function(n,s){return typeof n=="number"&&n<0&&(n+=this.length),typeof s=="number"&&s<0&&(s+=this.length),this.copy(null,0,n,s)},o.prototype.copy=function(n,s,a,l){if((typeof a!="number"||a<0)&&(a=0),(typeof l!="number"||l>this.length)&&(l=this.length),a>=this.length||l<=0)return n||t.alloc(0);let c=!!n,u=this._offset(a),d=l-a,f=d,g=c&&s||0,h=u[1];if(a===0&&l===this.length){if(!c)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let b=0;b<this._bufs.length;b++)this._bufs[b].copy(n,g),g+=this._bufs[b].length;return n}if(f<=this._bufs[u[0]].length-h)return c?this._bufs[u[0]].copy(n,s,h,h+f):this._bufs[u[0]].slice(h,h+f);c||(n=t.allocUnsafe(d));for(let b=u[0];b<this._bufs.length;b++){let y=this._bufs[b].length-h;if(f>y)this._bufs[b].copy(n,g,h),g+=y;else{this._bufs[b].copy(n,g,h,h+f),g+=y;break}f-=y,h&&(h=0)}return n.length>g?n.slice(0,g):n},o.prototype.shallowSlice=function(n,s){if(n=n||0,s=typeof s!="number"?this.length:s,n<0&&(n+=this.length),s<0&&(s+=this.length),n===s)return this._new();let a=this._offset(n),l=this._offset(s),c=this._bufs.slice(a[0],l[0]+1);return l[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,l[1]),a[1]!==0&&(c[0]=c[0].slice(a[1])),this._new(c)},o.prototype.toString=function(n,s,a){return this.slice(s,a).toString(n)},o.prototype.consume=function(n){if(n=Math.trunc(n),Number.isNaN(n)||n<=0)return this;for(;this._bufs.length;)if(n>=this._bufs[0].length)n-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(n),this.length-=n;break}return this},o.prototype.duplicate=function(){let n=this._new();for(let s=0;s<this._bufs.length;s++)n.append(this._bufs[s]);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,s,a){if(n==null)return this;if(n.buffer)s.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[l,c]=a?[n.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n.length;u+=c)this._attach(n[u],s,a)}else if(this._isBufferList(n)){let[l,c]=a?[n._bufs.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],s,a)}else typeof n=="number"&&(n=n.toString()),s.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,s,a){if(a===void 0&&typeof s=="string"&&(a=s,s=void 0),typeof n=="function"||Array.isArray(n))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof n=="number"?n=t.from([n]):typeof n=="string"?n=t.from(n,a):this._isBufferList(n)?n=n.slice():Array.isArray(n.buffer)?n=t.from(n.buffer,n.byteOffset,n.byteLength):t.isBuffer(n)||(n=t.from(n)),s=Number(s||0),isNaN(s)&&(s=0),s<0&&(s=this.length+s),s<0&&(s=0),n.length===0)return s>this.length?this.length:s;let l=this._offset(s),c=l[0],u=l[1];for(;c<this._bufs.length;c++){let d=this._bufs[c];for(;u<d.length;)if(d.length-u>=n.length){let f=d.indexOf(n,u);if(f!==-1)return this._reverseOffset([c,f]);u=d.length-n.length+1}else{let f=this._reverseOffset([c,u]);if(this._match(f,n))return f;u++}u=0}return-1},o.prototype._match=function(n,s){if(this.length-n<s.length)return!1;for(let a=0;a<s.length;a++)if(this.get(n+a)!==s[a])return!1;return!0},(function(){let n={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let s in n)(function(a){n[a]===null?o.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:o.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(s)})(),o.prototype._isBufferList=function(n){return n instanceof o||o.isBufferList(n)},o.isBufferList=function(n){return n!=null&&n[r]},e.exports=o}),bu=me((i,e)=>{le(),ue(),ce();var t=$t().Duplex,r=mu(),o=gu();function n(s){if(!(this instanceof n))return new n(s);if(typeof s=="function"){this._callback=s;let a=(function(l){this._callback&&(this._callback(l),this._callback=null)}).bind(this);this.on("pipe",function(l){l.on("error",a)}),this.on("unpipe",function(l){l.removeListener("error",a)}),s=null}o._init.call(this,s),t.call(this)}r(n,t),Object.assign(n.prototype,o.prototype),n.prototype._new=function(s){return new n(s)},n.prototype._write=function(s,a,l){this._appendBuffer(s),typeof l=="function"&&l()},n.prototype._read=function(s){if(!this.length)return this.push(null);s=Math.min(s,this.length),this.push(this.slice(0,s)),this.consume(s)},n.prototype.end=function(s){t.prototype.end.call(this,s),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(s,a){this._bufs.length=0,this.length=0,a(s)},n.prototype._isBufferList=function(s){return s instanceof n||s instanceof o||n.isBufferList(s)},n.isBufferList=o.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=o}),yu=me((i,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}),Ls=me((i,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(He(),je(qe));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 s=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+s.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let s=t.types[n];t.codes[s]=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 s=t.properties[n];t.propertiesCodes[s]=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(s=>[0,1].map(a=>[0,1].map(l=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(a?t.DUP_MASK:0)|s<<t.QOS_SHIFT|l,0,!0),c})))}t.PUBLISH_HEADER=o("publish"),t.SUBSCRIBE_HEADER=o("subscribe"),t.SUBSCRIBE_OPTIONS_QOS_MASK=3,t.SUBSCRIBE_OPTIONS_NL_MASK=1,t.SUBSCRIBE_OPTIONS_NL_SHIFT=2,t.SUBSCRIBE_OPTIONS_RAP_MASK=1,t.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,t.SUBSCRIBE_OPTIONS_RH_MASK=3,t.SUBSCRIBE_OPTIONS_RH_SHIFT=4,t.SUBSCRIBE_OPTIONS_RH=[0,16,32],t.SUBSCRIBE_OPTIONS_NL=4,t.SUBSCRIBE_OPTIONS_RAP=8,t.SUBSCRIBE_OPTIONS_QOS=[0,1,2],t.UNSUBSCRIBE_HEADER=o("unsubscribe"),t.ACKS={unsuback:o("unsuback"),puback:o("puback"),pubcomp:o("pubcomp"),pubrel:o("pubrel"),pubrec:o("pubrec")},t.SUBACK_HEADER=r.from([t.codes.suback<<t.CMD_SHIFT]),t.VERSION3=r.from([3]),t.VERSION4=r.from([4]),t.VERSION5=r.from([5]),t.VERSION131=r.from([131]),t.VERSION132=r.from([132]),t.QOS=[0,1,2].map(n=>r.from([n])),t.EMPTY={pingreq:r.from([t.codes.pingreq<<4,0]),pingresp:r.from([t.codes.pingresp<<4,0]),disconnect:r.from([t.codes.disconnect<<4,0])},t.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},t.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},t.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},t.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}}),vu=me((i,e)=>{le(),ue(),ce();var t=1e3,r=t*60,o=r*60,n=o*24,s=n*7,a=n*365.25;e.exports=function(f,g){g=g||{};var h=typeof f;if(h==="string"&&f.length>0)return l(f);if(h==="number"&&isFinite(f))return g.long?u(f):c(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function l(f){if(f=String(f),!(f.length>100)){var g=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(g){var h=parseFloat(g[1]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return h*a;case"weeks":case"week":case"w":return h*s;case"days":case"day":case"d":return h*n;case"hours":case"hour":case"hrs":case"hr":case"h":return h*o;case"minutes":case"minute":case"mins":case"min":case"m":return h*r;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}}}function c(f){var g=Math.abs(f);return g>=n?Math.round(f/n)+"d":g>=o?Math.round(f/o)+"h":g>=r?Math.round(f/r)+"m":g>=t?Math.round(f/t)+"s":f+"ms"}function u(f){var g=Math.abs(f);return g>=n?d(f,g,n,"day"):g>=o?d(f,g,o,"hour"):g>=r?d(f,g,r,"minute"):g>=t?d(f,g,t,"second"):f+" ms"}function d(f,g,h,b){var y=g>=h*1.5;return Math.round(f/h)+" "+b+(y?"s":"")}}),wu=me((i,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=d,n.disable=c,n.enable=a,n.enabled=u,n.humanize=vu(),n.destroy=f,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function o(g){let h=0;for(let b=0;b<g.length;b++)h=(h<<5)-h+g.charCodeAt(b),h|=0;return n.colors[Math.abs(h)%n.colors.length]}n.selectColor=o;function n(g){let h,b=null,y,w;function m(...k){if(!m.enabled)return;let x=m,v=Number(new Date),S=v-(h||v);x.diff=S,x.prev=h,x.curr=v,h=v,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let E=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(I,P)=>{if(I==="%%")return"%";E++;let L=n.formatters[P];if(typeof L=="function"){let $=k[E];I=L.call(x,$),k.splice(E,1),E--}return I}),n.formatArgs.call(x,k),(x.log||n.log).apply(x,k)}return m.namespace=g,m.useColors=n.useColors(),m.color=n.selectColor(g),m.extend=s,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(y!==n.namespaces&&(y=n.namespaces,w=n.enabled(g)),w),set:k=>{b=k}}),typeof n.init=="function"&&n.init(m),m}function s(g,h){let b=n(this.namespace+(typeof h>"u"?":":h)+g);return b.log=this.log,b}function a(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let h=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let b of h)b[0]==="-"?n.skips.push(b.slice(1)):n.names.push(b)}function l(g,h){let b=0,y=0,w=-1,m=0;for(;b<g.length;)if(y<h.length&&(h[y]===g[b]||h[y]==="*"))h[y]==="*"?(w=y,m=b,y++):(b++,y++);else if(w!==-1)y=w+1,m++,b=m;else return!1;for(;y<h.length&&h[y]==="*";)y++;return y===h.length}function c(){let g=[...n.names,...n.skips.map(h=>"-"+h)].join(",");return n.enable(""),g}function u(g){for(let h of n.skips)if(l(g,h))return!1;for(let h of n.names)if(l(g,h))return!0;return!1}function d(g){return g instanceof Error?g.stack||g.message:g}function f(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}e.exports=t}),vt=me((i,e)=>{le(),ue(),ce(),i.formatArgs=r,i.save=o,i.load=n,i.useColors=t,i.storage=s(),i.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),i.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;l.splice(1,0,c,"color: inherit");let u=0,d=0;l[0].replace(/%[a-zA-Z%]/g,f=>{f!=="%%"&&(u++,f==="%c"&&(d=u))}),l.splice(d,0,c)}i.log=console.debug||console.log||(()=>{});function o(l){try{l?i.storage.setItem("debug",l):i.storage.removeItem("debug")}catch{}}function n(){let l;try{l=i.storage.getItem("debug")||i.storage.getItem("DEBUG")}catch{}return!l&&typeof De<"u"&&"env"in De&&(l=De.env.DEBUG),l}function s(){try{return localStorage}catch{}}e.exports=wu()(i);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),ku=me((i,e)=>{le(),ue(),ce();var t=bu(),{EventEmitter:r}=(Rt(),je(At)),o=yu(),n=Ls(),s=vt()("mqtt-packet:parser"),a=class Ko extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof Ko?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new Ko().parser(c)}_resetState(){s("_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),s("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++,s("parse: state complete. _stateCounter is now: %d",this._stateCounter),s("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return s("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let c=this._list.readUInt8(0),u=c>>n.CMD_SHIFT;this.packet.cmd=n.types[u];let d=c&15,f=n.requiredHeaderFlags[u];return f!=null&&d!==f?this._emitError(new Error(n.requiredHeaderFlagsErrors[u])):(this.packet.retain=(c&n.RETAIN_MASK)!==0,this.packet.qos=c>>n.QOS_SHIFT&n.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=(c&n.DUP_MASK)!==0,s("_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)),s("_parseLength %d",c.value),!!c}_parsePayload(){s("_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 s("_parsePayload complete result: %s",c),c}_parseConnect(){s("_parseConnect");let c,u,d,f,g={},h=this.packet,b=this._parseString();if(b===null)return this._emitError(new Error("Cannot parse protocolId"));if(b!=="MQTT"&&b!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(h.protocolId=b,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(h.protocolVersion=this._list.readUInt8(this._pos),h.protocolVersion>=128&&(h.bridgeMode=!0,h.protocolVersion=h.protocolVersion-128),h.protocolVersion!==3&&h.protocolVersion!==4&&h.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));g.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,g.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,g.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let y=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),w=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(g.will)h.will={},h.will.retain=y,h.will.qos=w;else{if(y)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(w)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(h.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,h.keepalive=this._parseNum(),h.keepalive===-1)return this._emitError(new Error("Packet too short"));if(h.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(h.properties=k)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(h.clientId=m,s("_parseConnect: packet.clientId: %s",h.clientId),g.will){if(h.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(h.will.properties=k)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(h.will.topic=c,s("_parseConnect: packet.will.topic: %s",h.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));h.will.payload=u,s("_parseConnect: packet.will.paylaod: %s",h.will.payload)}if(g.username){if(f=this._parseString(),f===null)return this._emitError(new Error("Cannot parse username"));h.username=f,s("_parseConnect: packet.username: %s",h.username)}if(g.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));h.password=d}return this.settings=h,s("_parseConnect: complete"),h}_parseConnack(){s("_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)}s("_parseConnack: complete")}_parsePublish(){s("_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),s("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){s("_parseSubscribe");let c=this.packet,u,d,f,g,h,b,y;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(c.properties=w)}if(c.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<c.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=c.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(d=this._parseByte(),this.settings.protocolVersion===5){if(d&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(d&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(f=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,f>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(b=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,h=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,g=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,g>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));y={topic:u,qos:f},this.settings.protocolVersion===5?(y.nl=b,y.rap=h,y.rh=g):this.settings.bridgeMode&&(y.rh=0,y.rap=!0,y.nl=!0),s("_parseSubscribe: push subscription `%s` to subscription",y),c.subscriptions.push(y)}}}_parseSuback(){s("_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(){s("_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"));s("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){s("_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(){s("_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}s("_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(s("_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 s("_parseDisconnect result: true"),!0}_parseAuth(){s("_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),s("_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):(s("_parseMessageId: packet.messageId %d",c.messageId),!0)}_parseString(c){let u=this._parseNum(),d=u+this._pos;if(u===-1||d>this._list.length||d>this.packet.length)return null;let f=this._list.toString("utf8",this._pos,d);return this._pos+=u,s("_parseString: result: %s",f),f}_parseStringPair(){return s("_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,s("_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,s("_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,s("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){s("_parseVarByteNum");let u=4,d=0,f=1,g=0,h=!1,b,y=this._pos?this._pos:0;for(;d<u&&y+d<this._list.length;){if(b=this._list.readUInt8(y+d++),g+=f*(b&n.VARBYTEINT_MASK),f*=128,(b&n.VARBYTEINT_FIN_MASK)===0){h=!0;break}if(this._list.length<=d)break}return!h&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=d),h?c?h={bytes:d,value:g}:h=g:h=!1,s("_parseVarByteNum: result: %o",h),h}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),s("_parseByte: result: %o",c),c}_parseByType(c){switch(s("_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(){s("_parseProperties");let c=this._parseVarByteNum(),u=this._pos+c,d={};for(;this._pos<u;){let f=this._parseByte();if(!f)return this._emitError(new Error("Cannot parse property code type")),!1;let g=n.propertiesCodes[f];if(!g)return this._emitError(new Error("Unknown property")),!1;if(g==="userProperties"){d[g]||(d[g]=Object.create(null));let h=this._parseByType(n.propertiesTypes[g]);if(d[g][h.name])if(Array.isArray(d[g][h.name]))d[g][h.name].push(h.value);else{let b=d[g][h.name];d[g][h.name]=[b],d[g][h.name].push(h.value)}else d[g][h.name]=h.value;continue}d[g]?Array.isArray(d[g])?d[g].push(this._parseByType(n.propertiesTypes[g])):(d[g]=[d[g]],d[g].push(this._parseByType(n.propertiesTypes[g]))):d[g]=this._parseByType(n.propertiesTypes[g])}return d}_newPacket(){return s("_newPacket"),this.packet&&(this._list.consume(this.packet.length),s("_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)),s("_newPacket: new packet"),this.packet=new o,this._pos=0,!0}_emitError(c){s("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),_u=me((i,e)=>{le(),ue(),ce();var{Buffer:t}=(He(),je(qe)),r=65536,o={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function s(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function a(){for(let u=0;u<r;u++)o[u]=s(u)}function l(u){let d=0,f=0,g=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),g.writeUInt8(d,f++);while(u>0&&f<4);return u>0&&(f=0),n?g.subarray(0,f):g.slice(0,f)}function c(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:o,generateCache:a,generateNumber:s,genBufVariableByteInt:l,generate4ByteBuffer:c}}),xu=me((i,e)=>{le(),ue(),ce(),typeof De>"u"||!De.version||De.version.indexOf("v0.")===0||De.version.indexOf("v1.")===0&&De.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=De;function t(r,o,n,s){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var a=arguments.length,l,c;switch(a){case 0:case 1:return De.nextTick(r);case 2:return De.nextTick(function(){r.call(null,o)});case 3:return De.nextTick(function(){r.call(null,o,n)});case 4:return De.nextTick(function(){r.call(null,o,n,s)});default:for(l=new Array(a-1),c=0;c<l.length;)l[c++]=arguments[c];return De.nextTick(function(){r.apply(null,l)})}}}),Ms=me((i,e)=>{le(),ue(),ce();var t=Ls(),{Buffer:r}=(He(),je(qe)),o=r.allocUnsafe(0),n=r.from([0]),s=_u(),a=xu().nextTick,l=vt()("mqtt-packet:writeToStream"),c=s.cache,u=s.generateNumber,d=s.generateCache,f=s.genBufVariableByteInt,g=s.generate4ByteBuffer,h=j,b=!0;function y(G,R,ne){switch(l("generate called"),R.cork&&(R.cork(),a(w,R)),b&&(b=!1,d()),l("generate: packet.cmd: %s",G.cmd),G.cmd){case"connect":return m(G,R);case"connack":return k(G,R,ne);case"publish":return x(G,R,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(G,R,ne);case"subscribe":return S(G,R,ne);case"suback":return E(G,R,ne);case"unsubscribe":return I(G,R,ne);case"unsuback":return P(G,R,ne);case"pingreq":case"pingresp":return L(G,R);case"disconnect":return $(G,R,ne);case"auth":return T(G,R,ne);default:return R.destroy(new Error("Unknown command")),!1}}Object.defineProperty(y,"cacheNumbers",{get(){return h===j},set(G){G?((!c||Object.keys(c).length===0)&&(b=!0),h=j):(b=!1,h=W)}});function w(G){G.uncork()}function m(G,R,ne){let V=G||{},Y=V.protocolId||"MQTT",X=V.protocolVersion||4,be=V.will,se=V.clean,M=V.keepalive||0,H=V.clientId||"",te=V.username,he=V.password,fe=V.properties;se===void 0&&(se=!0);let ye=0;if(typeof Y!="string"&&!r.isBuffer(Y))return R.destroy(new Error("Invalid protocolId")),!1;if(ye+=Y.length+2,X!==3&&X!==4&&X!==5)return R.destroy(new Error("Invalid protocol version")),!1;if(ye+=1,(typeof H=="string"||r.isBuffer(H))&&(H||X>=4)&&(H||se))ye+=r.byteLength(H)+2;else{if(X<4)return R.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(se*1===0)return R.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof M!="number"||M<0||M>65535||M%1!==0)return R.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let z,ge;if(X===5){if(z=Q(R,fe),!z)return!1;ye+=z.length}if(be){if(typeof be!="object")return R.destroy(new Error("Invalid will")),!1;if(!be.topic||typeof be.topic!="string")return R.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(be.topic)+2,ye+=2,be.payload)if(be.payload.length>=0)typeof be.payload=="string"?ye+=r.byteLength(be.payload):ye+=be.payload.length;else return R.destroy(new Error("Invalid will payload")),!1;if(ge={},X===5){if(ge=Q(R,be.properties),!ge)return!1;ye+=ge.length}}let we=!1;if(te!=null)if(ve(te))we=!0,ye+=r.byteLength(te)+2;else return R.destroy(new Error("Invalid username")),!1;if(he!=null){if(!we)return R.destroy(new Error("Username is required to use password")),!1;if(ve(he))ye+=ee(he)+2;else return R.destroy(new Error("Invalid password")),!1}R.write(t.CONNECT_HEADER),F(R,ye),U(R,Y),V.bridgeMode&&(X+=128),R.write(X===131?t.VERSION131:X===132?t.VERSION132:X===4?t.VERSION4:X===5?t.VERSION5:t.VERSION3);let ae=0;return ae|=te!=null?t.USERNAME_MASK:0,ae|=he!=null?t.PASSWORD_MASK:0,ae|=be&&be.retain?t.WILL_RETAIN_MASK:0,ae|=be&&be.qos?be.qos<<t.WILL_QOS_SHIFT:0,ae|=be?t.WILL_FLAG_MASK:0,ae|=se?t.CLEAN_SESSION_MASK:0,R.write(r.from([ae])),h(R,M),X===5&&z.write(),U(R,H),be&&(X===5&&ge.write(),D(R,be.topic),U(R,be.payload)),te!=null&&U(R,te),he!=null&&U(R,he),!0}function k(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=V===5?Y.reasonCode:Y.returnCode,be=Y.properties,se=2;if(typeof X!="number")return R.destroy(new Error("Invalid return code")),!1;let M=null;if(V===5){if(M=Q(R,be),!M)return!1;se+=M.length}return R.write(t.CONNACK_HEADER),F(R,se),R.write(Y.sessionPresent?t.SESSIONPRESENT_HEADER:n),R.write(r.from([X])),M?.write(),!0}function x(G,R,ne){l("publish: packet: %o",G);let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.qos||0,be=Y.retain?t.RETAIN_MASK:0,se=Y.topic,M=Y.payload||o,H=Y.messageId,te=Y.properties,he=0;if(typeof se=="string")he+=r.byteLength(se)+2;else if(r.isBuffer(se))he+=se.length+2;else return R.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(M)?he+=M.length:he+=r.byteLength(M),X&&typeof H!="number")return R.destroy(new Error("Invalid messageId")),!1;X&&(he+=2);let fe=null;if(V===5){if(fe=Q(R,te),!fe)return!1;he+=fe.length}return R.write(t.PUBLISH_HEADER[X][Y.dup?1:0][be?1:0]),F(R,he),h(R,ee(se)),R.write(se),X>0&&h(R,H),fe?.write(),l("publish: payload: %o",M),R.write(M)}function v(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.cmd||"puback",be=Y.messageId,se=Y.dup&&X==="pubrel"?t.DUP_MASK:0,M=0,H=Y.reasonCode,te=Y.properties,he=V===5?3:2;if(X==="pubrel"&&(M=1),typeof be!="number")return R.destroy(new Error("Invalid messageId")),!1;let fe=null;if(V===5&&typeof te=="object"){if(fe=O(R,te,ne,he),!fe)return!1;he+=fe.length}return R.write(t.ACKS[X][M][se][0]),he===3&&(he+=H!==0?1:-1),F(R,he),h(R,be),V===5&&he!==2&&R.write(r.from([H])),fe!==null?fe.write():he===4&&R.write(r.from([0])),!0}function S(G,R,ne){l("subscribe: packet: ");let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.dup?t.DUP_MASK:0,be=Y.messageId,se=Y.subscriptions,M=Y.properties,H=0;if(typeof be!="number")return R.destroy(new Error("Invalid messageId")),!1;H+=2;let te=null;if(V===5){if(te=Q(R,M),!te)return!1;H+=te.length}if(typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){let ye=se[fe].topic,z=se[fe].qos;if(typeof ye!="string")return R.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof z!="number")return R.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(V===5){if(typeof(se[fe].nl||!1)!="boolean")return R.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(se[fe].rap||!1)!="boolean")return R.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let ge=se[fe].rh||0;if(typeof ge!="number"||ge>2)return R.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}H+=r.byteLength(ye)+2+1}else return R.destroy(new Error("Invalid subscriptions")),!1;l("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),R.write(t.SUBSCRIBE_HEADER[1][X?1:0][0]),F(R,H),h(R,be),te!==null&&te.write();let he=!0;for(let fe of se){let ye=fe.topic,z=fe.qos,ge=+fe.nl,we=+fe.rap,ae=fe.rh,Me;D(R,ye),Me=t.SUBSCRIBE_OPTIONS_QOS[z],V===5&&(Me|=ge?t.SUBSCRIBE_OPTIONS_NL:0,Me|=we?t.SUBSCRIBE_OPTIONS_RAP:0,Me|=ae?t.SUBSCRIBE_OPTIONS_RH[ae]:0),he=R.write(r.from([Me]))}return he}function E(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.messageId,be=Y.granted,se=Y.properties,M=0;if(typeof X!="number")return R.destroy(new Error("Invalid messageId")),!1;if(M+=2,typeof be=="object"&&be.length)for(let te=0;te<be.length;te+=1){if(typeof be[te]!="number")return R.destroy(new Error("Invalid qos vector")),!1;M+=1}else return R.destroy(new Error("Invalid qos vector")),!1;let H=null;if(V===5){if(H=O(R,se,ne,M),!H)return!1;M+=H.length}return R.write(t.SUBACK_HEADER),F(R,M),h(R,X),H!==null&&H.write(),R.write(r.from(be))}function I(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.messageId,be=Y.dup?t.DUP_MASK:0,se=Y.unsubscriptions,M=Y.properties,H=0;if(typeof X!="number")return R.destroy(new Error("Invalid messageId")),!1;if(H+=2,typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){if(typeof se[fe]!="string")return R.destroy(new Error("Invalid unsubscriptions")),!1;H+=r.byteLength(se[fe])+2}else return R.destroy(new Error("Invalid unsubscriptions")),!1;let te=null;if(V===5){if(te=Q(R,M),!te)return!1;H+=te.length}R.write(t.UNSUBSCRIBE_HEADER[1][be?1:0][0]),F(R,H),h(R,X),te!==null&&te.write();let he=!0;for(let fe=0;fe<se.length;fe++)he=D(R,se[fe]);return he}function P(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.messageId,be=Y.dup?t.DUP_MASK:0,se=Y.granted,M=Y.properties,H=Y.cmd,te=0,he=2;if(typeof X!="number")return R.destroy(new Error("Invalid messageId")),!1;if(V===5)if(typeof se=="object"&&se.length)for(let ye=0;ye<se.length;ye+=1){if(typeof se[ye]!="number")return R.destroy(new Error("Invalid qos vector")),!1;he+=1}else return R.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(V===5){if(fe=O(R,M,ne,he),!fe)return!1;he+=fe.length}return R.write(t.ACKS[H][te][be][0]),F(R,he),h(R,X),fe!==null&&fe.write(),V===5&&R.write(r.from(se)),!0}function L(G,R,ne){return R.write(t.EMPTY[G.cmd])}function $(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.reasonCode,be=Y.properties,se=V===5?1:0,M=null;if(V===5){if(M=O(R,be,ne,se),!M)return!1;se+=M.length}return R.write(r.from([t.codes.disconnect<<4])),F(R,se),V===5&&R.write(r.from([X])),M!==null&&M.write(),!0}function T(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.reasonCode,be=Y.properties,se=V===5?1:0;V!==5&&R.destroy(new Error("Invalid mqtt version for auth packet"));let M=O(R,be,ne,se);return M?(se+=M.length,R.write(r.from([t.codes.auth<<4])),F(R,se),R.write(r.from([X])),M!==null&&M.write(),!0):!1}var q={};function F(G,R){if(R>t.VARBYTEINT_MAX)return G.destroy(new Error(`Invalid variable byte integer: ${R}`)),!1;let ne=q[R];return ne||(ne=f(R),R<16384&&(q[R]=ne)),l("writeVarByteInt: writing to stream: %o",ne),G.write(ne)}function D(G,R){let ne=r.byteLength(R);return h(G,ne),l("writeString: %s",R),G.write(R,"utf8")}function oe(G,R,ne){D(G,R),D(G,ne)}function j(G,R){return l("writeNumberCached: number: %d",R),l("writeNumberCached: %o",c[R]),G.write(c[R])}function W(G,R){let ne=u(R);return l("writeNumberGenerated: %o",ne),G.write(ne)}function re(G,R){let ne=g(R);return l("write4ByteNumber: %o",ne),G.write(ne)}function U(G,R){typeof R=="string"?D(G,R):R?(h(G,R.length),G.write(R)):h(G,0)}function Q(G,R){if(typeof R!="object"||R.length!=null)return{length:1,write(){pe(G,{},0)}};let ne=0;function V(Y,X){let be=t.propertiesTypes[Y],se=0;switch(be){case"byte":{if(typeof X!="boolean")return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=2;break}case"int8":{if(typeof X!="number"||X<0||X>255)return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=2;break}case"binary":{if(X&&X===null)return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=1+r.byteLength(X)+2;break}case"int16":{if(typeof X!="number"||X<0||X>65535)return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=3;break}case"int32":{if(typeof X!="number"||X<0||X>4294967295)return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=5;break}case"var":{if(typeof X!="number"||X<0||X>268435455)return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=1+r.byteLength(f(X));break}case"string":{if(typeof X!="string")return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=3+r.byteLength(X.toString());break}case"pair":{if(typeof X!="object")return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=Object.getOwnPropertyNames(X).reduce((M,H)=>{let te=X[H];return Array.isArray(te)?M+=te.reduce((he,fe)=>(he+=3+r.byteLength(H.toString())+2+r.byteLength(fe.toString()),he),0):M+=3+r.byteLength(H.toString())+2+r.byteLength(X[H].toString()),M},0);break}default:return G.destroy(new Error(`Invalid property ${Y}: ${X}`)),!1}return se}if(R)for(let Y in R){let X=0,be=0,se=R[Y];if(se!==void 0){if(Array.isArray(se))for(let M=0;M<se.length;M++){if(be=V(Y,se[M]),!be)return!1;X+=be}else{if(be=V(Y,se),!be)return!1;X=be}if(!X)return!1;ne+=X}}return{length:r.byteLength(f(ne))+ne,write(){pe(G,R,ne)}}}function O(G,R,ne,V){let Y=["reasonString","userProperties"],X=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,be=Q(G,R);if(X)for(;V+be.length>X;){let se=Y.shift();if(se&&R[se])delete R[se],be=Q(G,R);else return!1}return be}function J(G,R,ne){switch(t.propertiesTypes[R]){case"byte":{G.write(r.from([t.properties[R]])),G.write(r.from([+ne]));break}case"int8":{G.write(r.from([t.properties[R]])),G.write(r.from([ne]));break}case"binary":{G.write(r.from([t.properties[R]])),U(G,ne);break}case"int16":{G.write(r.from([t.properties[R]])),h(G,ne);break}case"int32":{G.write(r.from([t.properties[R]])),re(G,ne);break}case"var":{G.write(r.from([t.properties[R]])),F(G,ne);break}case"string":{G.write(r.from([t.properties[R]])),D(G,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(V=>{let Y=ne[V];Array.isArray(Y)?Y.forEach(X=>{G.write(r.from([t.properties[R]])),oe(G,V.toString(),X.toString())}):(G.write(r.from([t.properties[R]])),oe(G,V.toString(),Y.toString()))});break}default:return G.destroy(new Error(`Invalid property ${R} value: ${ne}`)),!1}}function pe(G,R,ne){F(G,ne);for(let V in R)if(Object.prototype.hasOwnProperty.call(R,V)&&R[V]!=null){let Y=R[V];if(Array.isArray(Y))for(let X=0;X<Y.length;X++)J(G,V,Y[X]);else J(G,V,Y)}}function ee(G){return G?G instanceof r?G.length:r.byteLength(G):0}function ve(G){return typeof G=="string"||G instanceof r}e.exports=y}),Su=me((i,e)=>{le(),ue(),ce();var t=Ms(),{EventEmitter:r}=(Rt(),je(At)),{Buffer:o}=(He(),je(qe));function n(a,l){let c=new s;return t(a,c,l),c.concat()}var s=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(a){return this._array[this._i++]=a,!0}concat(){let a=0,l=new Array(this._array.length),c=this._array,u=0,d;for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?l[d]=c[d].length:l[d]=o.byteLength(c[d]),a+=l[d];let f=o.allocUnsafe(a);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(f,u),u+=l[d]):(f.write(c[d],u),u+=l[d]);return f}destroy(a){a&&this.emit("error",a)}};e.exports=n}),Eu=me(i=>{le(),ue(),ce(),i.parser=ku().parser,i.generate=Su(),i.writeToStream=Ms()}),Au=me((i,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof Ar?Ar.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return o(n);let s=new Map;if(s.set(Date,d=>new Date(d)),s.set(Map,(d,f)=>new Map(l(Array.from(d),f))),s.set(Set,(d,f)=>new Set(l(Array.from(d),f))),n.constructorHandlers)for(let d of n.constructorHandlers)s.set(d[0],d[1]);let a=null;return n.proto?u:c;function l(d,f){let g=Object.keys(d),h=new Array(g.length);for(let b=0;b<g.length;b++){let y=g[b],w=d[y];typeof w!="object"||w===null?h[y]=w:w.constructor!==Object&&(a=s.get(w.constructor))?h[y]=a(w,f):ArrayBuffer.isView(w)?h[y]=t(w):h[y]=f(w)}return h}function c(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,c);if(d.constructor!==Object&&(a=s.get(d.constructor)))return a(d,c);let f={};for(let g in d){if(Object.hasOwnProperty.call(d,g)===!1)continue;let h=d[g];typeof h!="object"||h===null?f[g]=h:h.constructor!==Object&&(a=s.get(h.constructor))?f[g]=a(h,c):ArrayBuffer.isView(h)?f[g]=t(h):f[g]=c(h)}return f}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,u);if(d.constructor!==Object&&(a=s.get(d.constructor)))return a(d,u);let f={};for(let g in d){let h=d[g];typeof h!="object"||h===null?f[g]=h:h.constructor!==Object&&(a=s.get(h.constructor))?f[g]=a(h,u):ArrayBuffer.isView(h)?f[g]=t(h):f[g]=u(h)}return f}}function o(n){let s=[],a=[],l=new Map;if(l.set(Date,g=>new Date(g)),l.set(Map,(g,h)=>new Map(u(Array.from(g),h))),l.set(Set,(g,h)=>new Set(u(Array.from(g),h))),n.constructorHandlers)for(let g of n.constructorHandlers)l.set(g[0],g[1]);let c=null;return n.proto?f:d;function u(g,h){let b=Object.keys(g),y=new Array(b.length);for(let w=0;w<b.length;w++){let m=b[w],k=g[m];if(typeof k!="object"||k===null)y[m]=k;else if(k.constructor!==Object&&(c=l.get(k.constructor)))y[m]=c(k,h);else if(ArrayBuffer.isView(k))y[m]=t(k);else{let x=s.indexOf(k);x!==-1?y[m]=a[x]:y[m]=h(k)}}return y}function d(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,d);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,d);let h={};s.push(g),a.push(h);for(let b in g){if(Object.hasOwnProperty.call(g,b)===!1)continue;let y=g[b];if(typeof y!="object"||y===null)h[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))h[b]=c(y,d);else if(ArrayBuffer.isView(y))h[b]=t(y);else{let w=s.indexOf(y);w!==-1?h[b]=a[w]:h[b]=d(y)}}return s.pop(),a.pop(),h}function f(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,f);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,f);let h={};s.push(g),a.push(h);for(let b in g){let y=g[b];if(typeof y!="object"||y===null)h[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))h[b]=c(y,f);else if(ArrayBuffer.isView(y))h[b]=t(y);else{let w=s.indexOf(y);w!==-1?h[b]=a[w]:h[b]=f(y)}}return s.pop(),a.pop(),h}}}),Iu=me((i,e)=>{le(),ue(),ce(),e.exports=Au()()}),Ns=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.validateTopic=e,i.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}}),Rs=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=$t(),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,s){return this._inflights.set(n.messageId,n),s&&s(),this}createStream(){let n=new e.Readable(t),s=[],a=!1,l=0;return this._inflights.forEach((c,u)=>{s.push(c)}),n._read=()=>{!a&&l<s.length?n.push(s[l++]):n.push(null)},n.destroy=c=>{if(!a)return a=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,s){let a=this._inflights.get(n.messageId);return a?(this._inflights.delete(n.messageId),s(null,a)):s&&s(new Error("missing packet")),this}get(n,s){let a=this._inflights.get(n.messageId);return a?s(null,a):s&&s(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};i.default=o}),Tu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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 s=o.topic.toString(),a=o.payload,{qos:l}=o,{messageId:c}=o,{options:u}=r;if(r.options.protocolVersion===5){let d;if(o.properties&&(d=o.properties.topicAlias),typeof d<"u")if(s.length===0)if(d>0&&d<=65535){let f=r.topicAliasRecv.getTopicByAlias(d);if(f)s=f,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",s,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(s,d))r.log("handlePublish :: registered topic: %s - alias: %d",s,d);else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",l),l){case 2:{u.customHandleAcks(s,a,o,(d,f)=>{if(typeof d=="number"&&(f=d,d=null),d)return r.emit("error",d);if(e.indexOf(f)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));f?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:f},n):r.incomingStore.put(o,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(s,a,o,(d,f)=>{if(typeof d=="number"&&(f=d,d=null),d)return r.emit("error",d);if(e.indexOf(f)===-1)return r.emit("error",new Error("Wrong reason code for puback"));f||r.emit("message",s,a,o),r.handleMessage(o,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:f},n)})});break}case 0:r.emit("message",s,a,o),r.handleMessage(o,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};i.default=t}),Cu=me((i,e)=>{e.exports={version:"5.15.0"}}),Kt=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.MQTTJS_VERSION=i.nextTick=i.ErrorWithSubackPacket=i.ErrorWithReasonCode=void 0,i.applyMixin=r;var e=class Nc extends Error{code;constructor(n,s){super(n),this.code=s,Object.setPrototypeOf(this,Nc.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};i.ErrorWithReasonCode=e;var t=class Rc extends Error{packet;constructor(n,s){super(n),this.packet=s,Object.setPrototypeOf(this,Rc.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};i.ErrorWithSubackPacket=t;function r(o,n,s=!1){let a=[n];for(;;){let l=a[0],c=Object.getPrototypeOf(l);if(c?.prototype)a.unshift(c);else break}for(let l of a)for(let c of Object.getOwnPropertyNames(l.prototype))(s||c!=="constructor")&&Object.defineProperty(o.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}i.nextTick=typeof De?.nextTick=="function"?De.nextTick:o=>{setTimeout(o,0)},i.MQTTJS_VERSION=Cu().version}),Pr=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=void 0;var e=Kt();i.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,s=o.cmd,a=null,l=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!l){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",s),s){case"pubcomp":case"puback":{let u=o.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,o)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=o.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,o)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=o.granted;for(let d=0;d<u.length;d++){let f=u[d];if((f&128)!==0){c=new Error(`Subscribe error: ${i.ReasonCodes[f]}`),c.code=f;let g=r.messageIdToTopic[n];g&&g.forEach(h=>{delete r._resubscribeTopics[h]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),l(c,o);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,o);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};i.default=t}),Pu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Kt(),t=Pr(),r=(o,n)=>{let{options:s}=o,a=s.protocolVersion,l=a===5?n.reasonCode:n.returnCode;if(a!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${a}`,l);o.emit("error",c);return}o.handleAuth(n,(c,u)=>{if(c){o.emit("error",c);return}if(l===24)o.reconnecting=!1,o._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);o.emit("error",d)}})};i.default=r}),Ou=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof De=="object"&&De?De:{},o=(g,h,b,y)=>{typeof r.emitWarning=="function"?r.emitWarning(g,h,b,y):console.error(`[${b}] ${h}: ${g}`)},n=globalThis.AbortController,s=globalThis.AbortSignal;if(typeof n>"u"){s=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(b,y){this._onabort.push(y)}},n=class{constructor(){h()}signal=new s;abort(b){if(!this.signal.aborted){this.signal.reason=b,this.signal.aborted=!0;for(let y of this.signal._onabort)y(b);this.signal.onabort?.(b)}}};let g=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",h=()=>{g&&(g=!1,o("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",h))}}var a=g=>!t.has(g),l=g=>g&&g===Math.floor(g)&&g>0&&isFinite(g),c=g=>l(g)?g<=Math.pow(2,8)?Uint8Array:g<=Math.pow(2,16)?Uint16Array:g<=Math.pow(2,32)?Uint32Array:g<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(g){super(g),this.fill(0)}},d=class kr{heap;length;static#l=!1;static create(h){let b=c(h);if(!b)return[];kr.#l=!0;let y=new kr(h,b);return kr.#l=!1,y}constructor(h,b){if(!kr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new b(h),this.length=0}push(h){this.heap[this.length++]=h}pop(){return this.heap[--this.length]}},f=class jc{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#h;#a;#o;#y;#s;#v;#w;#p;#k;#A;#u;static unsafeExposeInternals(h){return{starts:h.#w,ttls:h.#p,sizes:h.#v,keyMap:h.#n,keyList:h.#r,valList:h.#e,next:h.#c,prev:h.#h,get head(){return h.#a},get tail(){return h.#o},free:h.#y,isBackgroundFetch:b=>h.#t(b),backgroundFetch:(b,y,w,m)=>h.#N(b,y,w,m),moveToTail:b=>h.#C(b),indexes:b=>h.#_(b),rindexes:b=>h.#x(b),isStale:b=>h.#f(b)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#b}get size(){return this.#i}get fetchMethod(){return this.#P}get memoMethod(){return this.#O}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(h){let{max:b=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:k,updateAgeOnHas:x,allowStale:v,dispose:S,disposeAfter:E,noDisposeOnSet:I,noUpdateTTL:P,maxSize:L=0,maxEntrySize:$=0,sizeCalculation:T,fetchMethod:q,memoMethod:F,noDeleteOnFetchRejection:D,noDeleteOnStaleGet:oe,allowStaleOnFetchRejection:j,allowStaleOnFetchAbort:W,ignoreFetchAbort:re}=h;if(b!==0&&!l(b))throw new TypeError("max option must be a nonnegative integer");let U=b?c(b):Array;if(!U)throw new Error("invalid max value: "+b);if(this.#l=b,this.#d=L,this.maxEntrySize=$||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(F!==void 0&&typeof F!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=F,q!==void 0&&typeof q!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=q,this.#A=!!q,this.#n=new Map,this.#r=new Array(b).fill(void 0),this.#e=new Array(b).fill(void 0),this.#c=new U(b),this.#h=new U(b),this.#a=0,this.#o=0,this.#y=d.create(b),this.#i=0,this.#b=0,typeof S=="function"&&(this.#m=S),typeof E=="function"?(this.#g=E,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#k=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!P,this.noDeleteOnFetchRejection=!!D,this.allowStaleOnFetchRejection=!!j,this.allowStaleOnFetchAbort=!!W,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#d!==0&&!l(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!l(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!oe,this.updateAgeOnGet=!!k,this.updateAgeOnHas=!!x,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=y||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R()}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 Q="LRU_CACHE_UNBOUNDED";a(Q)&&(t.add(Q),o("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Q,jc))}}getRemainingTTL(h){return this.#n.has(h)?1/0:0}#R(){let h=new u(this.#l),b=new u(this.#l);this.#p=h,this.#w=b,this.#j=(m,k,x=e.now())=>{if(b[m]=k!==0?x:0,h[m]=k,k!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#f(m)&&this.#S(this.#r[m],"expire")},k+1);v.unref&&v.unref()}},this.#I=m=>{b[m]=h[m]!==0?e.now():0},this.#E=(m,k)=>{if(h[k]){let x=h[k],v=b[k];if(!x||!v)return;m.ttl=x,m.start=v,m.now=y||w();let S=m.now-v;m.remainingTTL=x-S}};let y=0,w=()=>{let m=e.now();if(this.ttlResolution>0){y=m;let k=setTimeout(()=>y=0,this.ttlResolution);k.unref&&k.unref()}return m};this.getRemainingTTL=m=>{let k=this.#n.get(m);if(k===void 0)return 0;let x=h[k],v=b[k];if(!x||!v)return 1/0;let S=(y||w())-v;return x-S},this.#f=m=>{let k=b[m],x=h[m];return!!x&&!!k&&(y||w())-k>x}}#I=()=>{};#E=()=>{};#j=()=>{};#f=()=>!1;#F(){let h=new u(this.#l);this.#b=0,this.#v=h,this.#T=b=>{this.#b-=h[b],h[b]=0},this.#$=(b,y,w,m)=>{if(this.#t(y))return 0;if(!l(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(y,b),!l(w))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return w},this.#L=(b,y,w)=>{if(h[b]=y,this.#d){let m=this.#d-h[b];for(;this.#b>m;)this.#M(!0)}this.#b+=h[b],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=h=>{};#L=(h,b,y)=>{};#$=(h,b,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:h=this.allowStale}={}){if(this.#i)for(let b=this.#o;!(!this.#D(b)||((h||!this.#f(b))&&(yield b),b===this.#a));)b=this.#h[b]}*#x({allowStale:h=this.allowStale}={}){if(this.#i)for(let b=this.#a;!(!this.#D(b)||((h||!this.#f(b))&&(yield b),b===this.#o));)b=this.#c[b]}#D(h){return h!==void 0&&this.#n.get(this.#r[h])===h}*entries(){for(let h of this.#_())this.#e[h]!==void 0&&this.#r[h]!==void 0&&!this.#t(this.#e[h])&&(yield[this.#r[h],this.#e[h]])}*rentries(){for(let h of this.#x())this.#e[h]!==void 0&&this.#r[h]!==void 0&&!this.#t(this.#e[h])&&(yield[this.#r[h],this.#e[h]])}*keys(){for(let h of this.#_()){let b=this.#r[h];b!==void 0&&!this.#t(this.#e[h])&&(yield b)}}*rkeys(){for(let h of this.#x()){let b=this.#r[h];b!==void 0&&!this.#t(this.#e[h])&&(yield b)}}*values(){for(let h of this.#_())this.#e[h]!==void 0&&!this.#t(this.#e[h])&&(yield this.#e[h])}*rvalues(){for(let h of this.#x())this.#e[h]!==void 0&&!this.#t(this.#e[h])&&(yield this.#e[h])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(h,b={}){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&h(m,this.#r[y],this))return this.get(this.#r[y],b)}}forEach(h,b=this){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&h.call(b,m,this.#r[y],this)}}rforEach(h,b=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&h.call(b,m,this.#r[y],this)}}purgeStale(){let h=!1;for(let b of this.#x({allowStale:!0}))this.#f(b)&&(this.#S(this.#r[b],"expire"),h=!0);return h}info(h){let b=this.#n.get(h);if(b===void 0)return;let y=this.#e[b],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#p&&this.#w){let k=this.#p[b],x=this.#w[b];if(k&&x){let v=k-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[b]),m}dump(){let h=[];for(let b of this.#_({allowStale:!0})){let y=this.#r[b],w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||y===void 0)continue;let k={value:m};if(this.#p&&this.#w){k.ttl=this.#p[b];let x=e.now()-this.#w[b];k.start=Math.floor(Date.now()-x)}this.#v&&(k.size=this.#v[b]),h.unshift([y,k])}return h}load(h){this.clear();for(let[b,y]of h){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(b,y.value,y)}}set(h,b,y={}){if(b===void 0)return this.delete(h),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:k=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=y,{noUpdateTTL:S=this.noUpdateTTL}=y,E=this.#$(h,b,y.size||0,x);if(this.maxEntrySize&&E>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(h,"set"),this;let I=this.#i===0?void 0:this.#n.get(h);if(I===void 0)I=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#M(!1):this.#i,this.#r[I]=h,this.#e[I]=b,this.#n.set(h,I),this.#c[this.#o]=I,this.#h[I]=this.#o,this.#o=I,this.#i++,this.#L(I,E,v),v&&(v.set="add"),S=!1;else{this.#C(I);let P=this.#e[I];if(b!==P){if(this.#A&&this.#t(P)){P.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:L}=P;L!==void 0&&!k&&(this.#k&&this.#m?.(L,h,"set"),this.#u&&this.#s?.push([L,h,"set"]))}else k||(this.#k&&this.#m?.(P,h,"set"),this.#u&&this.#s?.push([P,h,"set"]));if(this.#T(I),this.#L(I,E,v),this.#e[I]=b,v){v.set="replace";let L=P&&this.#t(P)?P.__staleWhileFetching:P;L!==void 0&&(v.oldValue=L)}}else v&&(v.set="update")}if(w!==0&&!this.#p&&this.#R(),this.#p&&(S||this.#j(I,w,m),v&&this.#E(v,I)),!k&&this.#u&&this.#s){let P=this.#s,L;for(;L=P?.shift();)this.#g?.(...L)}return this}pop(){try{for(;this.#i;){let h=this.#e[this.#a];if(this.#M(!0),this.#t(h)){if(h.__staleWhileFetching)return h.__staleWhileFetching}else if(h!==void 0)return h}}finally{if(this.#u&&this.#s){let h=this.#s,b;for(;b=h?.shift();)this.#g?.(...b)}}}#M(h){let b=this.#a,y=this.#r[b],w=this.#e[b];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(b),h&&(this.#r[b]=void 0,this.#e[b]=void 0,this.#y.push(b)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[b],this.#n.delete(y),this.#i--,b}has(h,b={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=b,m=this.#n.get(h);if(m!==void 0){let k=this.#e[m];if(this.#t(k)&&k.__staleWhileFetching===void 0)return!1;if(this.#f(m))w&&(w.has="stale",this.#E(w,m));else return y&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(h,b={}){let{allowStale:y=this.allowStale}=b,w=this.#n.get(h);if(w===void 0||!y&&this.#f(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#N(h,b,y,w){let m=b===void 0?void 0:this.#e[b];if(this.#t(m))return m;let k=new n,{signal:x}=y;x?.addEventListener("abort",()=>k.abort(x.reason),{signal:k.signal});let v={signal:k.signal,options:y,context:w},S=(T,q=!1)=>{let{aborted:F}=k.signal,D=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(F&&!q?(y.status.fetchAborted=!0,y.status.fetchError=k.signal.reason,D&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),F&&!D&&!q)return I(k.signal.reason);let oe=L;return this.#e[b]===L&&(T===void 0?oe.__staleWhileFetching?this.#e[b]=oe.__staleWhileFetching:this.#S(h,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(h,T,v.options))),T},E=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:q}=k.signal,F=q&&y.allowStaleOnFetchAbort,D=F||y.allowStaleOnFetchRejection,oe=D||y.noDeleteOnFetchRejection,j=L;if(this.#e[b]===L&&(!oe||j.__staleWhileFetching===void 0?this.#S(h,"fetch"):F||(this.#e[b]=j.__staleWhileFetching)),D)return y.status&&j.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),j.__staleWhileFetching;if(j.__returned===j)throw T},P=(T,q)=>{let F=this.#P?.(h,m,v);F&&F instanceof Promise&&F.then(D=>T(D===void 0?void 0:D),q),k.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=D=>S(D,!0)))})};y.status&&(y.status.fetchDispatched=!0);let L=new Promise(P).then(S,E),$=Object.assign(L,{__abortController:k,__staleWhileFetching:m,__returned:void 0});return b===void 0?(this.set(h,$,{...v.options,status:void 0}),b=this.#n.get(h)):this.#e[b]=$,$}#t(h){if(!this.#A)return!1;let b=h;return!!b&&b instanceof Promise&&b.hasOwnProperty("__staleWhileFetching")&&b.__abortController instanceof n}async fetch(h,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:k=this.ttl,noDisposeOnSet:x=this.noDisposeOnSet,size:v=0,sizeCalculation:S=this.sizeCalculation,noUpdateTTL:E=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:L=this.ignoreFetchAbort,allowStaleOnFetchAbort:$=this.allowStaleOnFetchAbort,context:T,forceRefresh:q=!1,status:F,signal:D}=b;if(!this.#A)return F&&(F.fetch="get"),this.get(h,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:F});let oe={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:k,noDisposeOnSet:x,size:v,sizeCalculation:S,noUpdateTTL:E,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:$,ignoreFetchAbort:L,status:F,signal:D},j=this.#n.get(h);if(j===void 0){F&&(F.fetch="miss");let W=this.#N(h,j,oe,T);return W.__returned=W}else{let W=this.#e[j];if(this.#t(W)){let O=y&&W.__staleWhileFetching!==void 0;return F&&(F.fetch="inflight",O&&(F.returnedStale=!0)),O?W.__staleWhileFetching:W.__returned=W}let re=this.#f(j);if(!q&&!re)return F&&(F.fetch="hit"),this.#C(j),w&&this.#I(j),F&&this.#E(F,j),W;let U=this.#N(h,j,oe,T),Q=U.__staleWhileFetching!==void 0&&y;return F&&(F.fetch=re?"stale":"refresh",Q&&re&&(F.returnedStale=!0)),Q?U.__staleWhileFetching:U.__returned=U}}async forceFetch(h,b={}){let y=await this.fetch(h,b);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(h,b={}){let y=this.#O;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,...k}=b,x=this.get(h,k);if(!m&&x!==void 0)return x;let v=y(h,x,{options:k,context:w});return this.set(h,v,k),v}get(h,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:k}=b,x=this.#n.get(h);if(x!==void 0){let v=this.#e[x],S=this.#t(v);return k&&this.#E(k,x),this.#f(x)?(k&&(k.get="stale"),S?(k&&y&&v.__staleWhileFetching!==void 0&&(k.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(h,"expire"),k&&y&&(k.returnedStale=!0),y?v:void 0)):(k&&(k.get="hit"),S?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else k&&(k.get="miss")}#U(h,b){this.#h[b]=h,this.#c[h]=b}#C(h){h!==this.#o&&(h===this.#a?this.#a=this.#c[h]:this.#U(this.#h[h],this.#c[h]),this.#U(this.#o,h),this.#o=h)}delete(h){return this.#S(h,"delete")}#S(h,b){let y=!1;if(this.#i!==0){let w=this.#n.get(h);if(w!==void 0)if(y=!0,this.#i===1)this.#B(b);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(m,h,b),this.#u&&this.#s?.push([m,h,b])),this.#n.delete(h),this.#r[w]=void 0,this.#e[w]=void 0,w===this.#o)this.#o=this.#h[w];else if(w===this.#a)this.#a=this.#c[w];else{let k=this.#h[w];this.#c[k]=this.#c[w];let x=this.#c[w];this.#h[x]=this.#h[w]}this.#i--,this.#y.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.shift();)this.#g?.(...m)}return y}clear(){return this.#B("delete")}#B(h){for(let b of this.#x({allowStale:!0})){let y=this.#e[b];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let w=this.#r[b];this.#k&&this.#m?.(y,w,h),this.#u&&this.#s?.push([y,w,h])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#p&&this.#w&&(this.#p.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)}}};i.LRUCache=f}),wt=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.ContainerIterator=i.Container=i.Base=void 0;var e=class{constructor(o=0){this.iteratorType=o}equals(o){return this.o===o.o}};i.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};i.Base=t;var r=class extends t{};i.Container=r}),Lu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=wt(),t=class extends e.Base{constructor(o=[]){super(),this.S=[];let n=this;o.forEach(function(s){n.push(s)})}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;i.default=r}),Mu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=wt(),t=class extends e.Base{constructor(o=[]){super(),this.j=0,this.q=[];let n=this;o.forEach(function(s){n.push(s)})}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 s=this.i;for(let a=0;a<s;++a)this.q[a]=this.q[this.j+a];this.j=0,this.q[this.i]=o}else this.q[this.j+this.i]=o;return++this.i}pop(){if(this.i===0)return;let o=this.q[this.j++];return this.i-=1,o}front(){if(this.i!==0)return this.q[this.j]}},r=t;i.default=r}),Nu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=wt(),t=class extends e.Base{constructor(o=[],n=function(a,l){return a>l?-1:a<l?1:0},s=!0){if(super(),this.v=n,Array.isArray(o))this.C=s?[...o]:o;else{this.C=[];let l=this;o.forEach(function(c){l.C.push(c)})}this.i=this.C.length;let a=this.i>>1;for(let l=this.i-1>>1;l>=0;--l)this.k(l,a)}m(o){let n=this.C[o];for(;o>0;){let s=o-1>>1,a=this.C[s];if(this.v(a,n)<=0)break;this.C[o]=a,o=s}this.C[o]=n}k(o,n){let s=this.C[o];for(;o<n;){let a=o<<1|1,l=a+1,c=this.C[a];if(l<this.i&&this.v(c,this.C[l])>0&&(a=l,c=this.C[l]),this.v(c,s)>=0)break;this.C[o]=c,o=a}this.C[o]=s}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;i.default=r}),Oi=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=wt(),t=class extends e.Container{},r=t;i.default=r}),kt=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),js=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.RandomIterator=void 0;var e=wt(),t=kt(),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)}};i.RandomIterator=r}),Ru=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(Oi()),t=js();function r(a){return a&&a.t?a:{default:a}}var o=class $c extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new $c(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=!0){if(super(),Array.isArray(a))this.J=l?[...a]:a,this.i=a.length;else{this.J=[];let c=this;a.forEach(function(u){c.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new o(0,this)}end(){return new o(this.i,this)}rBegin(){return new o(this.i-1,this,1)}rEnd(){return new o(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J[a]}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J.splice(a,1),this.i-=1,this.i}eraseElementByValue(a){let l=0;for(let c=0;c<this.i;++c)this.J[c]!==a&&(this.J[l++]=this.J[c]);return this.i=this.J.length=l,this.i}eraseElementByIterator(a){let l=a.o;return a=a.next(),this.eraseElementByPos(l),a}pushBack(a){return this.J.push(a),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;this.J[a]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;return this.J.splice(a,0,...new Array(c).fill(l)),this.i+=c,this.i}find(a){for(let l=0;l<this.i;++l)if(this.J[l]===a)return new o(l,this);return this.end()}reverse(){this.J.reverse()}unique(){let a=1;for(let l=1;l<this.i;++l)this.J[l]!==this.J[l-1]&&(this.J[a++]=this.J[l]);return this.i=this.J.length=a,this.i}sort(a){this.J.sort(a)}forEach(a){for(let l=0;l<this.i;++l)a(this.J[l],l,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},s=n;i.default=s}),ju=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o(Oi()),t=wt(),r=kt();function o(l){return l&&l.t?l:{default:l}}var n=class Dc extends t.ContainerIterator{constructor(c,u,d,f){super(f),this.o=c,this.h=u,this.container=d,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l}set pointer(c){this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l=c}copy(){return new Dc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.default{constructor(l=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;l.forEach(function(u){c.pushBack(u)})}V(l){let{L:c,B:u}=l;c.B=u,u.L=c,l===this.p&&(this.p=u),l===this._&&(this._=c),this.i-=1}G(l,c){let u=c.B,d={l,L:c,B:u};c.B=d,u.L=d,c===this.h&&(this.p=d),u===this.h&&(this._=d),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return c.l}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return this.V(c),this.i}eraseElementByValue(l){let c=this.p;for(;c!==this.h;)c.l===l&&this.V(c),c=c.B;return this.i}eraseElementByIterator(l){let c=l.o;return c===this.h&&(0,r.throwIteratorAccessError)(),l=l.next(),this.V(c),l}pushBack(l){return this.G(l,this._),this.i}popBack(){if(this.i===0)return;let l=this._.l;return this.V(this._),l}pushFront(l){return this.G(l,this.h),this.i}popFront(){if(this.i===0)return;let l=this.p.l;return this.V(this.p),l}setElementByPos(l,c){if(l<0||l>this.i-1)throw new RangeError;let u=this.p;for(;l--;)u=u.B;u.l=c}insert(l,c,u=1){if(l<0||l>this.i)throw new RangeError;if(u<=0)return this.i;if(l===0)for(;u--;)this.pushFront(c);else if(l===this.i)for(;u--;)this.pushBack(c);else{let d=this.p;for(let g=1;g<l;++g)d=d.B;let f=d.B;for(this.i+=u;u--;)d.B={l:c,L:d},d.B.L=d,d=d.B;d.B=f,f.L=d}return this.i}find(l){let c=this.p;for(;c!==this.h;){if(c.l===l)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let l=this.p,c=this._,u=0;for(;u<<1<this.i;){let d=l.l;l.l=c.l,c.l=d,l=l.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let l=this.p;for(;l!==this.h;){let c=l;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;l.B=c.B,l.B.L=l,l=l.B}return this.i}sort(l){if(this.i<=1)return;let c=[];this.forEach(function(d){c.push(d)}),c.sort(l);let u=this.p;c.forEach(function(d){u.l=d,u=u.B})}merge(l){let c=this;if(this.i===0)l.forEach(function(u){c.pushBack(u)});else{let u=this.p;l.forEach(function(d){for(;u!==c.h&&u.l<=d;)u=u.B;c.G(d,u.L)})}return this.i}forEach(l){let c=this.p,u=0;for(;c!==this.h;)l(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let l=this.p;for(;l!==this.h;)yield l.l,l=l.B}).bind(this)()}},a=s;i.default=a}),$u=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(Oi()),t=js();function r(a){return a&&a.t?a:{default:a}}var o=class Uc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Uc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof a.length=="number")return a.length;if(typeof a.size=="number")return a.size;if(typeof a.size=="function")return a.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=l,this.P=Math.max(Math.ceil(c/this.F),1);for(let f=0;f<this.P;++f)this.A.push(new Array(this.F));let u=Math.ceil(c/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-c%this.F>>1;let d=this;a.forEach(function(f){d.pushBack(f)})}T(){let a=[],l=Math.max(this.P>>1,1);for(let c=0;c<l;++c)a[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)a[a.length]=this.A[c];for(let c=0;c<this.R;++c)a[a.length]=this.A[c];a[a.length]=[...this.A[this.R]],this.j=l,this.R=a.length-1;for(let c=0;c<l;++c)a[a.length]=new Array(this.F);this.A=a,this.P=a.length}O(a){let l=this.D+a+1,c=l%this.F,u=c-1,d=this.j+(l-c)/this.F;return c===0&&(d-=1),d%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:d,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new o(0,this)}end(){return new o(this.i,this)}rBegin(){return new o(this.i-1,this,1)}rEnd(){return new o(-1,this,1)}front(){if(this.i!==0)return this.A[this.j][this.D]}back(){if(this.i!==0)return this.A[this.R][this.N]}pushBack(a){return this.i&&(this.N<this.F-1?this.N+=1:this.R<this.P-1?(this.R+=1,this.N=0):(this.R=0,this.N=0),this.R===this.j&&this.N===this.D&&this.T()),this.i+=1,this.A[this.R][this.N]=a,this.i}popBack(){if(this.i===0)return;let a=this.A[this.R][this.N];return this.i!==1&&(this.N>0?this.N-=1:this.R>0?(this.R-=1,this.N=this.F-1):(this.R=this.P-1,this.N=this.F-1)),this.i-=1,a}pushFront(a){return this.i&&(this.D>0?this.D-=1:this.j>0?(this.j-=1,this.D=this.F-1):(this.j=this.P-1,this.D=this.F-1),this.j===this.R&&this.D===this.N&&this.T()),this.i+=1,this.A[this.j][this.D]=a,this.i}popFront(){if(this.i===0)return;let a=this.A[this.j][this.D];return this.i!==1&&(this.D<this.F-1?this.D+=1:this.j<this.P-1?(this.j+=1,this.D=0):(this.j=0,this.D=0)),this.i-=1,a}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.A[l][c]}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(a);this.A[c][u]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;if(a===0)for(;c--;)this.pushFront(l);else if(a===this.i)for(;c--;)this.pushBack(l);else{let u=[];for(let d=a;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(a-1);for(let d=0;d<c;++d)this.pushBack(l);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(a){if(a<0)return this.clear(),0;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.R=l,this.N=c,this.i=a+1,this.i}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;if(a===0)this.popFront();else if(a===this.i-1)this.popBack();else{let l=[];for(let u=a+1;u<this.i;++u)l.push(this.getElementByPos(u));this.cut(a),this.popBack();let c=this;l.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(a){if(this.i===0)return 0;let l=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==a&&l.push(d)}let c=l.length;for(let u=0;u<c;++u)this.setElementByPos(u,l[u]);return this.cut(c-1)}eraseElementByIterator(a){let l=a.o;return this.eraseElementByPos(l),a=a.next(),a}find(a){for(let l=0;l<this.i;++l)if(this.getElementByPos(l)===a)return new o(l,this);return this.end()}reverse(){let a=0,l=this.i-1;for(;a<l;){let c=this.getElementByPos(a);this.setElementByPos(a,this.getElementByPos(l)),this.setElementByPos(l,c),a+=1,l-=1}}unique(){if(this.i<=1)return this.i;let a=1,l=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==l&&(l=u,this.setElementByPos(a++,u))}for(;this.i>a;)this.popBack();return this.i}sort(a){let l=[];for(let c=0;c<this.i;++c)l.push(this.getElementByPos(c));l.sort(a);for(let c=0;c<this.i;++c)this.setElementByPos(c,l[c])}shrinkToFit(){if(this.i===0)return;let a=[];this.forEach(function(l){a.push(l)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let l=0;l<this.P;++l)this.A.push(new Array(this.F));for(let l=0;l<a.length;++l)this.pushBack(a[l])}forEach(a){for(let l=0;l<this.i;++l)a(this.getElementByPos(l),l,this)}[Symbol.iterator](){return(function*(){for(let a=0;a<this.i;++a)yield this.getElementByPos(a)}).bind(this)()}},s=n;i.default=s}),Du=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.TreeNodeEnableIndex=i.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}};i.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)}};i.TreeNodeEnableIndex=t}),$s=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Du(),t=wt(),r=kt(),o=class extends t.Container{constructor(s=function(l,c){return l<c?-1:l>c?1:0},a=!1){super(),this.Y=void 0,this.v=s,a?(this.re=e.TreeNodeEnableIndex,this.M=function(l,c,u){let d=this.ne(l,c,u);if(d){let f=d.tt;for(;f!==this.h;)f.rt+=1,f=f.tt;let g=this.he(d);if(g){let{parentNode:h,grandParent:b,curNode:y}=g;h.ie(),b.ie(),y.ie()}}return this.i},this.V=function(l){let c=this.fe(l);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(l,c,u){let d=this.ne(l,c,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(s,a){let l=this.h;for(;s;){let c=this.v(s.u,a);if(c<0)s=s.W;else if(c>0)l=s,s=s.U;else return s}return l}Z(s,a){let l=this.h;for(;s;)this.v(s.u,a)<=0?s=s.W:(l=s,s=s.U);return l}$(s,a){let l=this.h;for(;s;){let c=this.v(s.u,a);if(c<0)l=s,s=s.W;else if(c>0)s=s.U;else return s}return l}rr(s,a){let l=this.h;for(;s;)this.v(s.u,a)<0?(l=s,s=s.W):s=s.U;return l}ue(s){for(;;){let a=s.tt;if(a===this.h)return;if(s.ee===1){s.ee=0;return}if(s===a.U){let l=a.W;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.te():a.te();else if(l.W&&l.W.ee===1){l.ee=a.ee,a.ee=0,l.W.ee=0,a===this.Y?this.Y=a.te():a.te();return}else l.U&&l.U.ee===1?(l.ee=1,l.U.ee=0,l.se()):(l.ee=1,s=a)}else{let l=a.U;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.se():a.se();else if(l.U&&l.U.ee===1){l.ee=a.ee,a.ee=0,l.U.ee=0,a===this.Y?this.Y=a.se():a.se();return}else l.W&&l.W.ee===1?(l.ee=1,l.W.ee=0,l.te()):(l.ee=1,s=a)}}}fe(s){if(this.i===1)return this.clear(),this.h;let a=s;for(;a.U||a.W;){if(a.W)for(a=a.W;a.U;)a=a.U;else a=a.U;[s.u,a.u]=[a.u,s.u],[s.l,a.l]=[a.l,s.l],s=a}this.h.U===a?this.h.U=a.tt:this.h.W===a&&(this.h.W=a.tt),this.ue(a);let l=a.tt;return a===l.U?l.U=void 0:l.W=void 0,this.i-=1,this.Y.ee=0,l}oe(s,a){return s===void 0?!1:this.oe(s.U,a)||a(s)?!0:this.oe(s.W,a)}he(s){for(;;){let a=s.tt;if(a.ee===0)return;let l=a.tt;if(a===l.U){let c=l.W;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,s=l;continue}else if(s===a.W){if(s.ee=0,s.U&&(s.U.tt=a),s.W&&(s.W.tt=l),a.W=s.U,l.U=s.W,s.U=a,s.W=l,l===this.Y)this.Y=s,this.h.tt=s;else{let u=l.tt;u.U===l?u.U=s:u.W=s}return s.tt=l.tt,a.tt=s,l.tt=s,l.ee=1,{parentNode:a,grandParent:l,curNode:s}}else a.ee=0,l===this.Y?this.Y=l.se():l.se(),l.ee=1}else{let c=l.U;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,s=l;continue}else if(s===a.U){if(s.ee=0,s.U&&(s.U.tt=l),s.W&&(s.W.tt=a),l.W=s.U,a.U=s.W,s.U=l,s.W=a,l===this.Y)this.Y=s,this.h.tt=s;else{let u=l.tt;u.U===l?u.U=s:u.W=s}return s.tt=l.tt,a.tt=s,l.tt=s,l.ee=1,{parentNode:a,grandParent:l,curNode:s}}else a.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(s,a,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(s,a),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let c,u=this.h.U,d=this.v(u.u,s);if(d===0){u.l=a;return}else if(d>0)u.U=new this.re(s,a),u.U.tt=u,c=u.U,this.h.U=c;else{let f=this.h.W,g=this.v(f.u,s);if(g===0){f.l=a;return}else if(g<0)f.W=new this.re(s,a),f.W.tt=f,c=f.W,this.h.W=c;else{if(l!==void 0){let h=l.o;if(h!==this.h){let b=this.v(h.u,s);if(b===0){h.l=a;return}else if(b>0){let y=h.L(),w=this.v(y.u,s);if(w===0){y.l=a;return}else w<0&&(c=new this.re(s,a),y.W===void 0?(y.W=c,c.tt=y):(h.U=c,c.tt=h))}}}if(c===void 0)for(c=this.Y;;){let h=this.v(c.u,s);if(h>0){if(c.U===void 0){c.U=new this.re(s,a),c.U.tt=c,c=c.U;break}c=c.U}else if(h<0){if(c.W===void 0){c.W=new this.re(s,a),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=a;return}}}}return this.i+=1,c}I(s,a){for(;s;){let l=this.v(s.u,a);if(l<0)s=s.W;else if(l>0)s=s.U;else return s}return s||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(s,a){let l=s.o;if(l===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return l.u=a,!0;if(l===this.h.U)return this.v(l.B().u,a)>0?(l.u=a,!0):!1;if(l===this.h.W)return this.v(l.L().u,a)<0?(l.u=a,!0):!1;let c=l.L().u;if(this.v(c,a)>=0)return!1;let u=l.B().u;return this.v(u,a)<=0?!1:(l.u=a,!0)}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a=0,l=this;return this.oe(this.Y,function(c){return s===a?(l.V(c),!0):(a+=1,!1)}),this.i}eraseElementByKey(s){if(this.i===0)return!1;let a=this.I(this.Y,s);return a===this.h?!1:(this.V(a),!0)}eraseElementByIterator(s){let a=s.o;a===this.h&&(0,r.throwIteratorAccessError)();let l=a.W===void 0;return s.iteratorType===0?l&&s.next():(!l||a.U===void 0)&&s.next(),this.V(a),s}forEach(s){let a=0;for(let l of this)s(l,a++,this)}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a,l=0;for(let c of this){if(l===s){a=c;break}l+=1}return a}getHeight(){if(this.i===0)return 0;let s=function(a){return a?Math.max(s(a.U),s(a.W))+1:0};return s(this.Y)}},n=o;i.default=n}),Ds=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=wt(),t=kt(),r=class extends e.ContainerIterator{constructor(n,s,a){super(a),this.o=n,this.h=s,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,s=this.h.tt;if(n===this.h)return s?s.rt-1:0;let a=0;for(n.U&&(a+=n.U.rt);n!==s;){let l=n.tt;n===l.W&&(a+=1,l.U&&(a+=l.U.rt)),n=l}return a}},o=r;i.default=o}),Uu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o($s()),t=o(Ds()),r=kt();function o(l){return l&&l.t?l:{default:l}}var n=class Bc extends t.default{constructor(c,u,d,f){super(c,u,f),this.container=d}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new Bc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(f){d.insert(f)})}*K(l){l!==void 0&&(yield*this.K(l.U),yield l.u,yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(l,c){return this.M(l,void 0,c)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}union(l){let c=this;return l.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=s;i.default=a}),Bu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o($s()),t=o(Ds()),r=kt();function o(l){return l&&l.t?l:{default:l}}var n=class Fc extends t.default{constructor(c,u,d,f){super(c,u,f),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,d){if(d==="0")return c.o.u;if(d==="1")return c.o.l},set(u,d,f){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=f,!0}})}copy(){return new Fc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(f){d.setElement(f[0],f[1])})}*K(l){l!==void 0&&(yield*this.K(l.U),yield[l.u,l.l],yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i===0)return;let l=this.h.U;return[l.u,l.l]}back(){if(this.i===0)return;let l=this.h.W;return[l.u,l.l]}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}setElement(l,c,u){return this.M(l,c,u)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}getElementByKey(l){return this.I(this.Y,l).l}union(l){let c=this;return l.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=s;i.default=a}),Us=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),Bs=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.HashContainerIterator=i.HashContainer=void 0;var e=wt(),t=o(Us()),r=kt();function o(a){return a&&a.t?a:{default:a}}var n=class extends e.ContainerIterator{constructor(a,l,c){super(c),this.o=a,this.h=l,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}};i.HashContainerIterator=n;var s=class extends e.Container{constructor(){super(),this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(a){let{L:l,B:c}=a;l.B=c,c.L=l,a===this.p&&(this.p=c),a===this._&&(this._=l),this.i-=1}M(a,l,c){c===void 0&&(c=(0,t.default)(a));let u;if(c){let d=a[this.HASH_TAG];if(d!==void 0)return this.H[d].l=l,this.i;Object.defineProperty(a,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:a,l,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[a];if(d)return d.l=l,this.i;u={u:a,l,L:this._,B:this.h},this.g[a]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(a,l){if(l===void 0&&(l=(0,t.default)(a)),l){let c=a[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[a]||this.h}clear(){let a=this.HASH_TAG;this.H.forEach(function(l){delete l.u[a]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(a,l){let c;if(l===void 0&&(l=(0,t.default)(a)),l){let u=a[this.HASH_TAG];if(u===void 0)return!1;delete a[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[a],c===void 0)return!1;delete this.g[a]}return this.V(c),!0}eraseElementByIterator(a){let l=a.o;return l===this.h&&(0,r.throwIteratorAccessError)(),this.V(l),a.next()}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let l=this.p;for(;a--;)l=l.B;return this.V(l),this.i}};i.HashContainer=s}),Fu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Bs(),t=kt(),r=class qc extends e.HashContainerIterator{constructor(a,l,c,u){super(a,l,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new qc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.HashContainer{constructor(s=[]){super();let a=this;s.forEach(function(l){a.insert(l)})}begin(){return new r(this.p,this.h,this)}end(){return new r(this.h,this.h,this)}rBegin(){return new r(this._,this.h,this,1)}rEnd(){return new r(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(s,a){return this.M(s,void 0,a)}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a=this.p;for(;s--;)a=a.B;return a.u}find(s,a){let l=this.I(s,a);return new r(l,this.h,this)}forEach(s){let a=0,l=this.p;for(;l!==this.h;)s(l.u,a++,this),l=l.B}[Symbol.iterator](){return(function*(){let s=this.p;for(;s!==this.h;)yield s.u,s=s.B}).bind(this)()}},n=o;i.default=n}),qu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Bs(),t=o(Us()),r=kt();function o(l){return l&&l.t?l:{default:l}}var n=class Hc extends e.HashContainerIterator{constructor(c,u,d,f){super(c,u,f),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,d){if(d==="0")return c.o.u;if(d==="1")return c.o.l},set(u,d,f){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=f,!0}})}copy(){return new Hc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.HashContainer{constructor(l=[]){super();let c=this;l.forEach(function(u){c.setElement(u[0],u[1])})}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i!==0)return[this.p.u,this.p.l]}back(){if(this.i!==0)return[this._.u,this._.l]}setElement(l,c,u){return this.M(l,c,u)}getElementByKey(l,c){if(c===void 0&&(c=(0,t.default)(l)),c){let d=l[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[l];return u?u.l:void 0}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return[c.u,c.l]}find(l,c){let u=this.I(l,c);return new n(u,this.h,this)}forEach(l){let c=0,u=this.p;for(;u!==this.h;)l([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let l=this.p;for(;l!==this.h;)yield[l.u,l.l],l=l.B}).bind(this)()}},a=s;i.default=a}),Hu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),Object.defineProperty(i,"Deque",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(i,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(i,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(i,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(i,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(i,"OrderedSet",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(i,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(i,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(i,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(i,"Vector",{enumerable:!0,get:function(){return o.default}});var e=d(Lu()),t=d(Mu()),r=d(Nu()),o=d(Ru()),n=d(ju()),s=d($u()),a=d(Uu()),l=d(Bu()),c=d(Fu()),u=d(qu());function d(f){return f&&f.t?f:{default:f}}}),Wu=me((i,e)=>{le(),ue(),ce();var t=Hu().OrderedSet,r=vt()("number-allocator:trace"),o=vt()("number-allocator:error");function n(a,l){this.low=a,this.high=l}n.prototype.equals=function(a){return this.low===a.low&&this.high===a.high},n.prototype.compare=function(a){return this.low<a.low&&this.high<a.low?-1:a.low<this.low&&a.high<this.low?1:0};function s(a,l){if(!(this instanceof s))return new s(a,l);this.min=a,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}s.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},s.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let a=this.ss.begin(),l=a.pointer.low,c=a.pointer.high,u=l;return u+1<=c?this.ss.updateKeyByIterator(a,new n(l+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},s.prototype.use=function(a){let l=new n(a,a),c=this.ss.lowerBound(l);if(!c.equals(this.ss.end())){let u=c.pointer.low,d=c.pointer.high;return c.pointer.equals(l)?(this.ss.eraseElementByIterator(c),r("use():"+a),!0):u>a?!1:u===a?(this.ss.updateKeyByIterator(c,new n(u+1,d)),r("use():"+a),!0):d===a?(this.ss.updateKeyByIterator(c,new n(u,d-1)),r("use():"+a),!0):(this.ss.updateKeyByIterator(c,new n(a+1,d)),this.ss.insert(new n(u,a-1)),r("use():"+a),!0)}return r("use():failed"),!1},s.prototype.free=function(a){if(a<this.min||a>this.max){o("free():"+a+" is out of range");return}let l=new n(a,a),c=this.ss.upperBound(l);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(l);return}c.pre();let u=c.pointer.high;c.pointer.high+1===a?this.ss.updateKeyByIterator(c,new n(u,a)):this.ss.insert(l)}else if(c.equals(this.ss.begin()))if(a+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(a,u))}else this.ss.insert(l);else{let u=c.pointer.low,d=c.pointer.high;c.pre();let f=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(f,d))):this.ss.updateKeyByIterator(c,new n(f,a)):a+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(a,d))):this.ss.insert(l)}r("free():"+a)},s.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},s.prototype.intervalCount=function(){return this.ss.size()},s.prototype.dump=function(){console.log("length:"+this.ss.size());for(let a of this.ss)console.log(a)},e.exports=s}),Fs=me((i,e)=>{le(),ue(),ce();var t=Wu();e.exports.NumberAllocator=t}),zu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Ou(),t=Fs(),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 s=this.aliasToTopic.get(n);return s&&delete this.topicToAlias[s],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]}};i.default=r}),Vu=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(i,"__esModule",{value:!0});var t=Pr(),r=e(zu()),o=Kt(),n=(s,a)=>{s.log("_handleConnack");let{options:l}=s,c=l.protocolVersion===5?a.reasonCode:a.returnCode;if(clearTimeout(s.connackTimer),delete s.topicAliasSend,a.properties){if(a.properties.topicAliasMaximum){if(a.properties.topicAliasMaximum>65535){s.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}a.properties.topicAliasMaximum>0&&(s.topicAliasSend=new r.default(a.properties.topicAliasMaximum))}a.properties.serverKeepAlive&&l.keepalive&&(l.keepalive=a.properties.serverKeepAlive),a.properties.maximumPacketSize&&(l.properties||(l.properties={}),l.properties.maximumPacketSize=a.properties.maximumPacketSize)}if(c===0)s.reconnecting=!1,s._onConnect(a);else if(c>0){let u=new o.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);s.emit("error",u),s.options.reconnectOnConnackError&&s._cleanUp(!0)}};i.default=n}),Ku=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(t,r,o)=>{t.log("handling pubrel packet");let n=typeof o<"u"?o:t.noop,{messageId:s}=r,a={cmd:"pubcomp",messageId:s};t.incomingStore.get(r,(l,c)=>{l?t._sendPacket(a,n):(t.emit("message",c.topic,c.payload,c),t.handleMessage(c,u=>{if(u)return n(u);t.incomingStore.del(c,t.noop),t._sendPacket(a,n)}))})};i.default=e}),Gu=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(i,"__esModule",{value:!0});var t=e(Tu()),r=e(Pu()),o=e(Vu()),n=e(Pr()),s=e(Ku()),a=(l,c,u)=>{let{options:d}=l;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<c.length)return l.emit("error",new Error(`exceeding packets size ${c.cmd}`)),l.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),l;switch(l.log("_handlePacket :: emitting packetreceive"),l.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(l,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":l.reschedulePing(),(0,n.default)(l,c),u();break;case"pubrel":l.reschedulePing(),(0,s.default)(l,c,u);break;case"connack":(0,o.default)(l,c),u();break;case"auth":l.reschedulePing(),(0,r.default)(l,c),u();break;case"pingresp":l.log("_handlePacket :: received pingresp"),l.reschedulePing(!0),u();break;case"disconnect":l.emit("disconnect",c),u();break;default:l.log("_handlePacket :: unknown command"),u();break}};i.default=a}),qs=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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(){}};i.default=e}),Yu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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={}}};i.default=e}),Ju=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(i,"__esModule",{value:!0}),i.TypedEventEmitter=void 0;var t=e((Rt(),je(At))),r=Kt(),o=class{};i.TypedEventEmitter=o,(0,r.applyMixin)(o,t.default)}),Or=me((i,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}),Qu=me((i,e)=>{le(),ue(),ce();var t=Or().default;function r(o,n){if(t(o)!="object"||!o)return o;var s=o[Symbol.toPrimitive];if(s!==void 0){var a=s.call(o,n||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(o)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Xu=me((i,e)=>{le(),ue(),ce();var t=Or().default,r=Qu();function o(n){var s=r(n,"string");return t(s)=="symbol"?s:s+""}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Zu=me((i,e)=>{le(),ue(),ce();var t=Xu();function r(o,n,s){return(n=t(n))in o?Object.defineProperty(o,n,{value:s,enumerable:!0,configurable:!0,writable:!0}):o[n]=s,o}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ed=me((i,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}),td=me((i,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 s,a,l,c,u=[],d=!0,f=!1;try{if(l=(n=n.call(r)).next,o===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(s=l.call(n)).done)&&(u.push(s.value),u.length!==o);d=!0);}catch(g){f=!0,a=g}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(f)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),rd=me((i,e)=>{le(),ue(),ce();function t(r,o){(o==null||o>r.length)&&(o=r.length);for(var n=0,s=Array(o);n<o;n++)s[n]=r[n];return s}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),nd=me((i,e)=>{le(),ue(),ce();var t=rd();function r(o,n){if(o){if(typeof o=="string")return t(o,n);var s={}.toString.call(o).slice(8,-1);return s==="Object"&&o.constructor&&(s=o.constructor.name),s==="Map"||s==="Set"?Array.from(o):s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(o,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),id=me((i,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}),od=me((i,e)=>{le(),ue(),ce();var t=ed(),r=td(),o=nd(),n=id();function s(a,l){return t(a)||r(a,l)||o(a,l)||n()}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Hs=me((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(i,function(t){var r=function(g){return function(h){var b=g(h);return h.add(b),b}},o=function(g){return function(h,b){return g.set(h,b),b}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,s=536870912,a=s*2,l=function(g,h){return function(b){var y=h.get(b),w=y===void 0?b.size:y<a?y+1:0;if(!b.has(w))return g(b,w);if(b.size<s){for(;b.has(w);)w=Math.floor(Math.random()*a);return g(b,w)}if(b.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;b.has(w);)w=Math.floor(Math.random()*n);return g(b,w)}},c=new WeakMap,u=o(c),d=l(u,c),f=r(d);t.addUniqueNumber=f,t.generateUniqueNumber=d})}),sd=me((i,e)=>{le(),ue(),ce();function t(o,n,s,a,l,c,u){try{var d=o[c](u),f=d.value}catch(g){return void s(g)}d.done?n(f):Promise.resolve(f).then(a,l)}function r(o){return function(){var n=this,s=arguments;return new Promise(function(a,l){var c=o.apply(n,s);function u(f){t(c,a,l,u,d,"next",f)}function d(f){t(c,a,l,u,d,"throw",f)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ws=me((i,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}),zs=me((i,e)=>{le(),ue(),ce();function t(r,o,n,s){var a=Object.defineProperty;try{a({},"",{})}catch{a=0}e.exports=t=function(l,c,u,d){function f(g,h){t(l,g,function(b){return this._invoke(g,h,b)})}c?a?a(l,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):l[c]=u:(f("next",0),f("throw",1),f("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,o,n,s)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Vs=me((i,e)=>{le(),ue(),ce();var t=zs();function r(){var o,n,s=typeof Symbol=="function"?Symbol:{},a=s.iterator||"@@iterator",l=s.toStringTag||"@@toStringTag";function c(w,m,k,x){var v=m&&m.prototype instanceof d?m:d,S=Object.create(v.prototype);return t(S,"_invoke",(function(E,I,P){var L,$,T,q=0,F=P||[],D=!1,oe={p:0,n:0,v:o,a:j,f:j.bind(o,4),d:function(W,re){return L=W,$=0,T=o,oe.n=re,u}};function j(W,re){for($=W,T=re,n=0;!D&&q&&!U&&n<F.length;n++){var U,Q=F[n],O=oe.p,J=Q[2];W>3?(U=J===re)&&(T=Q[($=Q[4])?5:($=3,3)],Q[4]=Q[5]=o):Q[0]<=O&&((U=W<2&&O<Q[1])?($=0,oe.v=re,oe.n=Q[1]):O<J&&(U=W<3||Q[0]>re||re>J)&&(Q[4]=W,Q[5]=re,oe.n=J,$=0))}if(U||W>1)return u;throw D=!0,re}return function(W,re,U){if(q>1)throw TypeError("Generator is already running");for(D&&re===1&&j(re,U),$=re,T=U;(n=$<2?o:T)||!D;){L||($?$<3?($>1&&(oe.n=-1),j($,T)):oe.n=T:oe.v=T);try{if(q=2,L){if($||(W="next"),n=L[W]){if(!(n=n.call(L,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,$<2&&($=0)}else $===1&&(n=L.return)&&n.call(L),$<2&&(T=TypeError("The iterator does not provide a '"+W+"' method"),$=1);L=o}else if((n=(D=oe.n<0)?T:E.call(I,oe))!==u)break}catch(Q){L=o,$=1,T=Q}finally{q=1}}return{value:n,done:D}}})(w,k,x),!0),S}var u={};function d(){}function f(){}function g(){}n=Object.getPrototypeOf;var h=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),b=g.prototype=d.prototype=Object.create(h);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,l,"GeneratorFunction")),w.prototype=Object.create(b),w}return f.prototype=g,t(b,"constructor",g),t(g,"constructor",f),f.displayName="GeneratorFunction",t(g,l,"GeneratorFunction"),t(b),t(b,l,"Generator"),t(b,a,function(){return this}),t(b,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ks=me((i,e)=>{le(),ue(),ce();var t=Ws(),r=zs();function o(n,s){function a(c,u,d,f){try{var g=n[c](u),h=g.value;return h instanceof t?s.resolve(h.v).then(function(b){a("next",b,d,f)},function(b){a("throw",b,d,f)}):s.resolve(h).then(function(b){g.value=b,d(g)},function(b){return a("throw",b,d,f)})}catch(b){f(b)}}var l;this.next||(r(o.prototype),r(o.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function f(){return new s(function(g,h){a(c,d,g,h)})}return l=l?l.then(f,f):f()},!0)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Gs=me((i,e)=>{le(),ue(),ce();var t=Vs(),r=Ks();function o(n,s,a,l,c){return new r(t().w(n,s,a,l),c||Promise)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),ad=me((i,e)=>{le(),ue(),ce();var t=Gs();function r(o,n,s,a,l){var c=t(o,n,s,a,l);return c.next().then(function(u){return u.done?u.value:c.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ld=me((i,e)=>{le(),ue(),ce();function t(r){var o=Object(r),n=[];for(var s in o)n.unshift(s);return function a(){for(;n.length;)if((s=n.pop())in o)return a.value=s,a.done=!1,a;return a.done=!0,a}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),cd=me((i,e)=>{le(),ue(),ce();var t=Or().default;function r(o){if(o!=null){var n=o[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],s=0;if(n)return n.call(o);if(typeof o.next=="function")return o;if(!isNaN(o.length))return{next:function(){return o&&s>=o.length&&(o=void 0),{value:o&&o[s++],done:!o}}}}throw new TypeError(t(o)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ud=me((i,e)=>{le(),ue(),ce();var t=Ws(),r=Vs(),o=ad(),n=Gs(),s=Ks(),a=ld(),l=cd();function c(){var u=r(),d=u.m(c),f=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===f||(w.displayName||w.name)==="GeneratorFunction")}var h={throw:1,return:2,break:3,continue:3};function b(y){var w,m;return function(k){w||(w={stop:function(){return m(k.a,2)},catch:function(){return k.v},abrupt:function(x,v){return m(k.a,h[x],v)},delegateYield:function(x,v,S){return w.resultName=v,m(k.d,l(x),S)},finish:function(x){return m(k.f,x)}},m=function(x,v,S){k.p=w.prev,k.n=w.next;try{return x(v,S)}finally{w.next=k.n}}),w.resultName&&(w[w.resultName]=k.v,w.resultName=void 0),w.sent=k.v,w.next=k.n;try{return y.call(this,w)}finally{k.p=w.prev,k.n=w.next}}}return(e.exports=c=function(){return{wrap:function(y,w,m,k){return u.w(b(y),w,m,k&&k.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:s,async:function(y,w,m,k,x){return(g(w)?n:o)(b(y),w,m,k,x)},keys:a,values:l}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),dd=me((i,e)=>{le(),ue(),ce();var t=ud()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),hd=me((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Zu(),od(),Hs(),sd(),dd()):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))})(i,function(t,r,o,n,s,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),x.push.apply(x,v)}return x}function d(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%2?u(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):u(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var f=function(m){return d(d({},m),{},{connect:function(k){var x=k.call;return s(a.mark(function v(){var S,E,I,P;return a.wrap(function(L){for(;;)switch(L.prev=L.next){case 0:return S=new MessageChannel,E=S.port1,I=S.port2,L.next=1,x("connect",{port:E},[E]);case 1:return P=L.sent,c.set(I,P),L.abrupt("return",I);case 2:case"end":return L.stop()}},v)}))},disconnect:function(k){var x=k.call;return(function(){var v=s(a.mark(function S(E){var I;return a.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:if(I=c.get(E),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()}},S)}));return function(S){return v.apply(this,arguments)}})()},isSupported:function(k){var x=k.call;return function(){return x("isSupported")}}})};function g(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),x.push.apply(x,v)}return x}function h(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%2?g(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):g(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var b=new WeakMap,y=function(m){if(b.has(m))return b.get(m);var k=new Map;return b.set(m,k),k},w=function(m){var k=f(m);return function(x){var v=y(x);x.addEventListener("message",function(F){var D=F.data,oe=D.id;if(oe!==null&&v.has(oe)){var j=v.get(oe),W=j.reject,re=j.resolve;v.delete(oe),D.error===void 0?re(D.result):W(new Error(D.error.message))}}),l(x)&&x.start();for(var S=function(F){var D=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(j,W){var re=n.generateUniqueNumber(v);v.set(re,{reject:W,resolve:j}),D===null?x.postMessage({id:re,method:F},oe):x.postMessage({id:re,method:F,params:D},oe)})},E=function(F,D){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:F,params:D},oe)},I={},P=0,L=Object.entries(k);P<L.length;P++){var $=o(L[P],2),T=$[0],q=$[1];I=h(h({},I),{},r({},T,q({call:S,notify:E})))}return h({},I)}};t.createBroker=w})}),pd=me((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Or(),hd(),Hs()):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))})(i,function(t,r,o,n){var s=new Map([[0,null]]),a=new Map([[0,null]]),l=o.createBroker({clearInterval:function(u){var d=u.call;return function(f){r(s.get(f))==="symbol"&&(s.set(f,null),d("clear",{timerId:f,timerType:"interval"}).then(function(){s.delete(f)}))}},clearTimeout:function(u){var d=u.call;return function(f){r(a.get(f))==="symbol"&&(a.set(f,null),d("clear",{timerId:f,timerType:"timeout"}).then(function(){a.delete(f)}))}},setInterval:function(u){var d=u.call;return function(f){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length,b=new Array(h>2?h-2:0),y=2;y<h;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(s);s.set(m,w);var k=function(){return d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=s.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===w&&(f.apply(void 0,b),s.get(m)===w&&k())})};return k(),m}},setTimeout:function(u){var d=u.call;return function(f){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length,b=new Array(h>2?h-2:0),y=2;y<h;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(a);return a.set(m,w),d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var k=a.get(m);if(k===void 0)throw new Error("The timer is in an undefined state.");k===w&&(a.delete(m),f.apply(void 0,b))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),fd=me((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,pd()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(i,function(t,r){var o=function(d,f){var g=null;return function(){if(g!==null)return g;var h=new Blob([f],{type:"application/javascript; charset=utf-8"}),b=URL.createObjectURL(h);return g=d(b),setTimeout(function(){return URL.revokeObjectURL(b)}),g}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,s=o(r.load,n),a=function(d){return s().clearInterval(d)},l=function(d){return s().clearTimeout(d)},c=function(){var d;return(d=s()).setInterval.apply(d,arguments)},u=function(){var d;return(d=s()).setTimeout.apply(d,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Lr=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.isReactNativeBrowser=i.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&De?.versions?!Object.prototype.hasOwnProperty.call(De.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();i.isWebWorker=t(),i.isReactNativeBrowser=r(),i.default=o}),md=me(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(c,u,d,f){f===void 0&&(f=d);var g=Object.getOwnPropertyDescriptor(u,d);(!g||("get"in g?!u.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,f,g)}:function(c,u,d,f){f===void 0&&(f=d),c[f]=u[d]}),t=i&&i.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=i&&i.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(d){var f=[];for(var g in d)Object.prototype.hasOwnProperty.call(d,g)&&(f[f.length]=g);return f},c(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var f=c(u),g=0;g<f.length;g++)f[g]!=="default"&&e(d,u,f[g]);return t(d,u),d}})();Object.defineProperty(i,"__esModule",{value:!0});var o=fd(),n=r(Lr()),s={set:o.setInterval,clear:o.clearInterval},a={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return a;case"worker":return s;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?s:a}};i.default=l}),Ys=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(i,"__esModule",{value:!0});var t=e(md()),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)}};i.default=r}),Li=me(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(v,S,E,I){I===void 0&&(I=E);var P=Object.getOwnPropertyDescriptor(S,E);(!P||("get"in P?!S.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return S[E]}}),Object.defineProperty(v,I,P)}:function(v,S,E,I){I===void 0&&(I=E),v[I]=S[E]}),t=i&&i.__setModuleDefault||(Object.create?function(v,S){Object.defineProperty(v,"default",{enumerable:!0,value:S})}:function(v,S){v.default=S}),r=i&&i.__importStar||(function(){var v=function(S){return v=Object.getOwnPropertyNames||function(E){var I=[];for(var P in E)Object.prototype.hasOwnProperty.call(E,P)&&(I[I.length]=P);return I},v(S)};return function(S){if(S&&S.__esModule)return S;var E={};if(S!=null)for(var I=v(S),P=0;P<I.length;P++)I[P]!=="default"&&e(E,S,I[P]);return t(E,S),E}})(),o=i&&i.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(i,"__esModule",{value:!0});var n=o(Eu()),s=$t(),a=o(Iu()),l=o(vt()),c=r(Ns()),u=o(Rs()),d=o(Gu()),f=o(qs()),g=o(Yu()),h=Kt(),b=Ju(),y=o(Ys()),w=r(Lr()),m=globalThis.setImmediate||((...v)=>{let S=v.shift();(0,h.nextTick)(()=>{S(...v)})}),k={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},x=class Go extends b.TypedEventEmitter{static VERSION=h.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(S,E){super(),this.options=E||{};for(let I in k)typeof this.options[I]>"u"?this.options[I]=k[I]:this.options[I]=E[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",Go.VERSION),w.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",w.default?"browser":"node"),this.log("MqttClient :: options.protocol",E.protocol),this.log("MqttClient :: options.protocolVersion",E.protocolVersion),this.log("MqttClient :: options.username",E.username),this.log("MqttClient :: options.keepalive",E.keepalive),this.log("MqttClient :: options.reconnectPeriod",E.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",E.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",E.properties?E.properties.topicAliasMaximum:void 0),this.options.clientId=typeof E.clientId=="string"?E.clientId:Go.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=E.protocolVersion===5&&E.customHandleAcks?E.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=S,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new f.default:this.options.messageIdProvider,this.outgoingStore=E.outgoingStore||new u.default,this.incomingStore=E.incomingStore||new u.default,this.queueQoSZero=E.queueQoSZero===void 0?!0:E.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,E.properties&&E.properties.topicAliasMaximum>0&&(E.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new g.default(E.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,P=()=>{let L=I.shift();this.log("deliver :: entry %o",L);let $=null;if(!L){this._resubscribe();return}$=L.packet,this.log("deliver :: call _sendPacket for %o",$);let T=!0;$.messageId&&$.messageId!==0&&(this.messageIdProvider.register($.messageId)||(T=!1)),T?this._sendPacket($,q=>{L.cb&&L.cb(q),P()}):(this.log("messageId: %d has already used. The message is skipped and removed.",$.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(S,E){E()}handleMessage(S,E){E()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let S=new s.Writable,E=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),E.on("packet",F=>{this.log("parser :: on packet push to packets array."),P.push(F)});let L=()=>{this.log("work :: getting next packet in queue");let F=P.shift();if(F)this.log("work :: packet pulled from queue"),(0,d.default)(this,F,$);else{this.log("work :: no packets in queue");let D=I;I=null,this.log("work :: done flag is %s",!!D),D&&D()}},$=()=>{if(P.length)(0,h.nextTick)(L);else{let F=I;I=null,F()}};S._write=(F,D,oe)=>{I=oe,this.log("writable stream :: parsing buffer"),E.parse(F),L()};let T=F=>{this.log("streamErrorHandler :: error",F.message),F.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",F)):this.noop(F)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(S),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),E.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 F={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(F)}}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(S,E,I,P){this.log("publish :: message `%s` to topic `%s`",E,S);let{options:L}=this;typeof I=="function"&&(P=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:$,retain:T,dup:q,properties:F,cbStorePut:D}=I;if(this._checkDisconnecting(P))return this;let oe=()=>{let j=0;if(($===1||$===2)&&(j=this._nextId(),j===null))return this.log("No messageId left"),!1;let W={cmd:"publish",topic:S,payload:E,qos:$,retain:T,messageId:j,dup:q};switch(L.protocolVersion===5&&(W.properties=F),this.log("publish :: qos",$),$){case 1:case 2:this.outgoing[W.messageId]={volatile:!1,cb:P||this.noop},this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,void 0,D);break;default:this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,P,D);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!oe())&&this._storeProcessingQueue.push({invoke:oe,cbStorePut:I.cbStorePut,callback:P}),this}publishAsync(S,E,I){return new Promise((P,L)=>{this.publish(S,E,I,($,T)=>{$?L($):P(T)})})}subscribe(S,E,I){let P=this.options.protocolVersion;typeof E=="function"&&(I=E),I=I||this.noop;let L=!1,$=[];typeof S=="string"?(S=[S],$=S):Array.isArray(S)?$=S:typeof S=="object"&&(L=S.resubscribe,delete S.resubscribe,$=Object.keys(S));let T=c.validateTopics($);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),E={...q,...E};let{properties:F}=E,D=[],oe=(re,U)=>{if(U=U||E,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<U.qos||L){let Q={topic:re,qos:U.qos};P===5&&(Q.nl=U.nl,Q.rap=U.rap,Q.rh=U.rh,Q.properties=F),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",Q.topic,Q.qos),D.push(Q)}};if(Array.isArray(S)?S.forEach(re=>{this.log("subscribe: array topic %s",re),oe(re)}):Object.keys(S).forEach(re=>{this.log("subscribe: object topic %s, %o",re,S[re]),oe(re,S[re])}),!D.length)return I(null,[]),this;let j=(re,U)=>{let Q={cmd:"subscribe",subscriptions:re,messageId:U};if(F&&(Q.properties=F),this.options.resubscribe){this.log("subscribe :: resubscribe true");let J=[];re.forEach(pe=>{if(this.options.reconnectPeriod>0){let ee={qos:pe.qos};P===5&&(ee.nl=pe.nl||!1,ee.rap=pe.rap||!1,ee.rh=pe.rh||0,ee.properties=pe.properties),this._resubscribeTopics[pe.topic]=ee,J.push(pe.topic)}}),this.messageIdToTopic[Q.messageId]=J}let O=new Promise((J,pe)=>{this.outgoing[Q.messageId]={volatile:!0,cb(ee,ve){if(!ee){let{granted:G}=ve;for(let R=0;R<G.length;R+=1)re[R].qos=G[R]}ee?pe(new h.ErrorWithSubackPacket(ee.message,ve)):J(ve)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Q),O},W=()=>{let re=this.options.subscribeBatchSize??D.length,U=[];for(let Q=0;Q<D.length;Q+=re){let O=D.slice(Q,Q+re),J=this._nextId();if(J===null)return this.log("No messageId left"),!1;U.push(j(O,J))}return Promise.all(U).then(Q=>{I(null,D,Q.at(-1))}).catch(Q=>{I(Q,D,Q.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!W())&&this._storeProcessingQueue.push({invoke:W,callback:I}),this}subscribeAsync(S,E){return new Promise((I,P)=>{this.subscribe(S,E,(L,$)=>{L?P(L):I($)})})}unsubscribe(S,E,I){typeof S=="string"&&(S=[S]),typeof E=="function"&&(I=E),I=I||this.noop;let P=c.validateTopics(S);if(P!==null)return m(I,new Error(`Invalid topic ${P}`)),this;if(this._checkDisconnecting(I))return this;let L=()=>{let $=this._nextId();if($===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:$,unsubscriptions:[]};return typeof S=="string"?T.unsubscriptions=[S]:Array.isArray(S)&&(T.unsubscriptions=S),this.options.resubscribe&&T.unsubscriptions.forEach(q=>{delete this._resubscribeTopics[q]}),typeof E=="object"&&E.properties&&(T.properties=E.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||!L())&&this._storeProcessingQueue.push({invoke:L,callback:I}),this}unsubscribeAsync(S,E){return new Promise((I,P)=>{this.unsubscribe(S,E,(L,$)=>{L?P(L):I($)})})}end(S,E,I){this.log("end :: (%s)",this.options.clientId),(S==null||typeof S!="boolean")&&(I=I||E,E=S,S=!1),typeof E!="object"&&(I=I||E,E=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($=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let q=$||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)},L=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,S),this._cleanUp(S,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,h.nextTick)(P)},E)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!S&&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,L,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),L()),this)}endAsync(S,E){return new Promise((I,P)=>{this.end(S,E,L=>{L?P(L):I()})})}removeOutgoingMessage(S){if(this.outgoing[S]){let{cb:E}=this.outgoing[S];this._removeOutgoingAndStoreMessage(S,()=>{E(new Error("Message removed"))})}return this}reconnect(S){this.log("client reconnect");let E=()=>{S?(this.options.incomingStore=S.incomingStore,this.options.outgoingStore=S.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=E:E(),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(S=>{this.outgoing[S].volatile&&typeof this.outgoing[S].cb=="function"&&(this.outgoing[S].cb(new Error("Connection closed")),delete this.outgoing[S])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(S=>{typeof this.outgoing[S].cb=="function"&&(this.outgoing[S].cb(new Error("Connection closed")),delete this.outgoing[S])}))}_removeTopicAliasAndRecoverTopicName(S){let E;S.properties&&(E=S.properties.topicAlias);let I=S.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",E,I),I.length===0){if(typeof E>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(E),typeof I>"u")return new Error("Unregistered Topic Alias");S.topic=I}E&&delete S.properties.topicAlias}_checkDisconnecting(S){return this.disconnecting&&(S&&S!==this.noop?S(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(S,E,I={}){if(E&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",E)),this.log("_cleanUp :: forced? %s",S),S)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(),E&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",E),E())}_storeAndSend(S,E,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",S.cmd);let P=S,L;if(P.cmd==="publish"&&(P=(0,a.default)(S),L=this._removeTopicAliasAndRecoverTopicName(P),L))return E&&E(L);this.outgoingStore.put(P,$=>{if($)return E&&E($);I(),this._writePacket(S,E)})}_applyTopicAlias(S){if(this.options.protocolVersion===5&&S.cmd==="publish"){let E;S.properties&&(E=S.properties.topicAlias);let I=S.topic.toString();if(this.topicAliasSend)if(E){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,E),!this.topicAliasSend.put(I,E)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,E),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(E=this.topicAliasSend.getAliasByTopic(I),E?(S.topic="",S.properties={...S.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,E)):(E=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,E),S.properties={...S.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,E))):this.options.autoUseTopicAlias&&(E=this.topicAliasSend.getAliasByTopic(I),E&&(S.topic="",S.properties={...S.properties,topicAlias:E},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,E))));else if(E)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,E),new Error("Sending Topic Alias out of range")}}_noop(S){this.log("noop ::",S)}_writePacket(S,E){this.log("_writePacket :: packet: %O",S),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",S),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(S,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&E&&E!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",E)):E&&(this.log("_writePacket :: invoking cb"),E())}_sendPacket(S,E,I,P){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,E=E||this.noop;let L=this._applyTopicAlias(S);if(L){E(L);return}if(!this.connected){if(S.cmd==="auth"){this._writePacket(S,E);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(S,E,I);return}if(P){this._writePacket(S,E);return}switch(S.cmd){case"publish":break;case"pubrel":this._storeAndSend(S,E,I);return;default:this._writePacket(S,E);return}switch(S.qos){case 2:case 1:this._storeAndSend(S,E,I);break;default:this._writePacket(S,E);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(S,E,I){this.log("_storePacket :: packet: %o",S),this.log("_storePacket :: cb? %s",!!E),I=I||this.noop;let P=S;if(P.cmd==="publish"){P=(0,a.default)(S);let $=this._removeTopicAliasAndRecoverTopicName(P);if($)return E&&E($)}let L=P.qos||0;L===0&&this.queueQoSZero||P.cmd!=="publish"?this.queue.push({packet:P,cb:E}):L>0?(E=this.outgoing[P.messageId]?this.outgoing[P.messageId].cb:null,this.outgoingStore.put(P,$=>{if($)return E&&E($);I()})):E&&E(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(S=!1){this.keepaliveManager&&this.options.keepalive&&(S||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 S=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&S.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let E=0;E<S.length;E++){let I={};I[S[E]]=this._resubscribeTopics[S[E]],I.resubscribe=!0,this.subscribe(I,{properties:I[S[E]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(S){if(this.disconnected){this.emit("connect",S);return}this.connackPacket=S,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let E=()=>{let I=this.outgoingStore.createStream(),P=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),L()},L=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",P),I.on("error",T=>{L(),this._flushStoreProcessingQueue(),this.removeListener("close",P),this.emit("error",T)});let $=()=>{if(!I)return;let T=I.read(1),q;if(!T){I.once("readable",$);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){$();return}!this.disconnecting&&!this.reconnectTimer?(q=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(F,D){q&&q(F,D),$()}},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?(L(),this._invokeAllStoreProcessingQueue(),this.emit("connect",S)):E()}),$()};E()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let S=this._storeProcessingQueue[0];if(S&&S.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let S of this._storeProcessingQueue)S.cbStorePut&&S.cbStorePut(new Error("Connection closed")),S.callback&&S.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(S,E){delete this.outgoing[S],this.outgoingStore.del({messageId:S},(I,P)=>{E(I,P),this.messageIdProvider.deallocate(S),this._invokeStoreProcessingQueue()})}};i.default=x}),gd=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Fs(),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()}};i.default=t});function bd(){if(Mi)return Mr;Mi=!0;let i=2147483647,e=36,t=1,r=26,o=38,n=700,s=72,a=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,f={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},g=e-t,h=Math.floor,b=String.fromCharCode;function y(L){throw new RangeError(f[L])}function w(L,$){let T=[],q=L.length;for(;q--;)T[q]=$(L[q]);return T}function m(L,$){let T=L.split("@"),q="";T.length>1&&(q=T[0]+"@",L=T[1]),L=L.replace(d,".");let F=L.split("."),D=w(F,$).join(".");return q+D}function k(L){let $=[],T=0,q=L.length;for(;T<q;){let F=L.charCodeAt(T++);if(F>=55296&&F<=56319&&T<q){let D=L.charCodeAt(T++);(D&64512)==56320?$.push(((F&1023)<<10)+(D&1023)+65536):($.push(F),T--)}else $.push(F)}return $}let x=L=>String.fromCodePoint(...L),v=function(L){return L>=48&&L<58?26+(L-48):L>=65&&L<91?L-65:L>=97&&L<123?L-97:e},S=function(L,$){return L+22+75*(L<26)-(($!=0)<<5)},E=function(L,$,T){let q=0;for(L=T?h(L/n):L>>1,L+=h(L/$);L>g*r>>1;q+=e)L=h(L/g);return h(q+(g+1)*L/(L+o))},I=function(L){let $=[],T=L.length,q=0,F=a,D=s,oe=L.lastIndexOf(l);oe<0&&(oe=0);for(let j=0;j<oe;++j)L.charCodeAt(j)>=128&&y("not-basic"),$.push(L.charCodeAt(j));for(let j=oe>0?oe+1:0;j<T;){let W=q;for(let U=1,Q=e;;Q+=e){j>=T&&y("invalid-input");let O=v(L.charCodeAt(j++));O>=e&&y("invalid-input"),O>h((i-q)/U)&&y("overflow"),q+=O*U;let J=Q<=D?t:Q>=D+r?r:Q-D;if(O<J)break;let pe=e-J;U>h(i/pe)&&y("overflow"),U*=pe}let re=$.length+1;D=E(q-W,re,W==0),h(q/re)>i-F&&y("overflow"),F+=h(q/re),q%=re,$.splice(q++,0,F)}return String.fromCodePoint(...$)},P=function(L){let $=[];L=k(L);let T=L.length,q=a,F=0,D=s;for(let W of L)W<128&&$.push(b(W));let oe=$.length,j=oe;for(oe&&$.push(l);j<T;){let W=i;for(let U of L)U>=q&&U<W&&(W=U);let re=j+1;W-q>h((i-F)/re)&&y("overflow"),F+=(W-q)*re,q=W;for(let U of L)if(U<q&&++F>i&&y("overflow"),U===q){let Q=F;for(let O=e;;O+=e){let J=O<=D?t:O>=D+r?r:O-D;if(Q<J)break;let pe=Q-J,ee=e-J;$.push(b(S(J+pe%ee,0))),Q=h(pe/ee)}$.push(b(S(Q,0))),D=E(F,re,j===oe),F=0,++j}++F,++q}return $.join("")};return Mr={version:"2.3.1",ucs2:{decode:k,encode:x},decode:I,encode:P,toASCII:function(L){return m(L,function($){return u.test($)?"xn--"+P($):$})},toUnicode:function(L){return m(L,function($){return c.test($)?I($.slice(4).toLowerCase()):$})}},Mr}var Mr,Mi,Tt,yd=Qe(()=>{le(),ue(),ce(),Mr={},Mi=!1,Tt=bd(),Tt.decode,Tt.encode,Tt.toASCII,Tt.toUnicode,Tt.ucs2,Tt.version});function vd(){return $i||($i=!0,ji=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var i={},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;i[e]=r;for(e in i)return!1;if(typeof Object.keys=="function"&&Object.keys(i).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(i).length!==0)return!1;var o=Object.getOwnPropertySymbols(i);if(o.length!==1||o[0]!==e||!Object.prototype.propertyIsEnumerable.call(i,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(i,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),ji}function wd(){return Ui||(Ui=!0,Di=Error),Di}function kd(){return Fi||(Fi=!0,Bi=EvalError),Bi}function _d(){return Hi||(Hi=!0,qi=RangeError),qi}function xd(){return zi||(zi=!0,Wi=ReferenceError),Wi}function Js(){return Ki||(Ki=!0,Vi=SyntaxError),Vi}function cr(){return Yi||(Yi=!0,Gi=TypeError),Gi}function Sd(){return Qi||(Qi=!0,Ji=URIError),Ji}function Ed(){if(Xi)return Nr;Xi=!0;var i=typeof Symbol<"u"&&Symbol,e=vd();return Nr=function(){return typeof i!="function"||typeof Symbol!="function"||typeof i("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Nr}function Ad(){if(Zi)return Rr;Zi=!0;var i={__proto__:null,foo:{}},e=Object;return Rr=function(){return{__proto__:i}.foo===i.foo&&!(i instanceof e)},Rr}function Id(){if(eo)return jr;eo=!0;var i="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",o=function(a,l){for(var c=[],u=0;u<a.length;u+=1)c[u]=a[u];for(var d=0;d<l.length;d+=1)c[d+a.length]=l[d];return c},n=function(a,l){for(var c=[],u=l,d=0;u<a.length;u+=1,d+=1)c[d]=a[u];return c},s=function(a,l){for(var c="",u=0;u<a.length;u+=1)c+=a[u],u+1<a.length&&(c+=l);return c};return jr=function(a){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(i+l);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var y=l.apply(this,o(c,arguments));return Object(y)===y?y:this}return l.apply(a,o(c,arguments))},f=t(0,l.length-c.length),g=[],h=0;h<f;h++)g[h]="$"+h;if(u=Function("binder","return function ("+s(g,",")+"){ return binder.apply(this,arguments); }")(d),l.prototype){var b=function(){};b.prototype=l.prototype,u.prototype=new b,b.prototype=null}return u},jr}function Ni(){if(to)return $r;to=!0;var i=Id();return $r=Function.prototype.bind||i,$r}function Td(){if(ro)return Dr;ro=!0;var i=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=Ni();return Dr=t.call(i,e),Dr}function Gt(){if(no)return Ur;no=!0;var i,e=wd(),t=kd(),r=_d(),o=xd(),n=Js(),s=cr(),a=Sd(),l=Function,c=function(j){try{return l('"use strict"; return ('+j+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new s},f=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=Ed()(),h=Ad()(),b=Object.getPrototypeOf||(h?function(j){return j.__proto__}:null),y={},w=typeof Uint8Array>"u"||!b?i:b(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?i:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?i:ArrayBuffer,"%ArrayIteratorPrototype%":g&&b?b([][Symbol.iterator]()):i,"%AsyncFromSyncIteratorPrototype%":i,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":typeof Atomics>"u"?i:Atomics,"%BigInt%":typeof BigInt>"u"?i:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?i:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?i:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?i:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?i:Float32Array,"%Float64Array%":typeof Float64Array>"u"?i:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?i:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":y,"%Int8Array%":typeof Int8Array>"u"?i:Int8Array,"%Int16Array%":typeof Int16Array>"u"?i:Int16Array,"%Int32Array%":typeof Int32Array>"u"?i:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&b?b(b([][Symbol.iterator]())):i,"%JSON%":typeof JSON=="object"?JSON:i,"%Map%":typeof Map>"u"?i:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!b?i:b(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?i:Promise,"%Proxy%":typeof Proxy>"u"?i:Proxy,"%RangeError%":r,"%ReferenceError%":o,"%Reflect%":typeof Reflect>"u"?i:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?i:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!b?i:b(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?i:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&b?b(""[Symbol.iterator]()):i,"%Symbol%":g?Symbol:i,"%SyntaxError%":n,"%ThrowTypeError%":f,"%TypedArray%":w,"%TypeError%":s,"%Uint8Array%":typeof Uint8Array>"u"?i:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?i:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?i:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?i:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?i:WeakMap,"%WeakRef%":typeof WeakRef>"u"?i:WeakRef,"%WeakSet%":typeof WeakSet>"u"?i:WeakSet};if(b)try{null.error}catch(j){var k=b(b(j));m["%Error.prototype%"]=k}var x=function j(W){var re;if(W==="%AsyncFunction%")re=c("async function () {}");else if(W==="%GeneratorFunction%")re=c("function* () {}");else if(W==="%AsyncGeneratorFunction%")re=c("async function* () {}");else if(W==="%AsyncGenerator%"){var U=j("%AsyncGeneratorFunction%");U&&(re=U.prototype)}else if(W==="%AsyncIteratorPrototype%"){var Q=j("%AsyncGenerator%");Q&&b&&(re=b(Q.prototype))}return m[W]=re,re},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},S=Ni(),E=Td(),I=S.call(Function.call,Array.prototype.concat),P=S.call(Function.apply,Array.prototype.splice),L=S.call(Function.call,String.prototype.replace),$=S.call(Function.call,String.prototype.slice),T=S.call(Function.call,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,F=/\\(\\)?/g,D=function(j){var W=$(j,0,1),re=$(j,-1);if(W==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&W!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var U=[];return L(j,q,function(Q,O,J,pe){U[U.length]=J?L(pe,F,"$1"):O||Q}),U},oe=function(j,W){var re=j,U;if(E(v,re)&&(U=v[re],re="%"+U[0]+"%"),E(m,re)){var Q=m[re];if(Q===y&&(Q=x(re)),typeof Q>"u"&&!W)throw new s("intrinsic "+j+" exists, but is not available. Please file an issue!");return{alias:U,name:re,value:Q}}throw new n("intrinsic "+j+" does not exist!")};return Ur=function(j,W){if(typeof j!="string"||j.length===0)throw new s("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof W!="boolean")throw new s('"allowMissing" argument must be a boolean');if(T(/^%?[^%]*%?$/,j)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var re=D(j),U=re.length>0?re[0]:"",Q=oe("%"+U+"%",W),O=Q.name,J=Q.value,pe=!1,ee=Q.alias;ee&&(U=ee[0],P(re,I([0,1],ee)));for(var ve=1,G=!0;ve<re.length;ve+=1){var R=re[ve],ne=$(R,0,1),V=$(R,-1);if((ne==='"'||ne==="'"||ne==="`"||V==='"'||V==="'"||V==="`")&&ne!==V)throw new n("property names with quotes must have matching quotes");if((R==="constructor"||!G)&&(pe=!0),U+="."+R,O="%"+U+"%",E(m,O))J=m[O];else if(J!=null){if(!(R in J)){if(!W)throw new s("base intrinsic for "+j+" exists, but the property is not available.");return}if(u&&ve+1>=re.length){var Y=u(J,R);G=!!Y,G&&"get"in Y&&!("originalValue"in Y.get)?J=Y.get:J=J[R]}else G=E(J,R),J=J[R];G&&!pe&&(m[O]=J)}}return J},Ur}function Ri(){if(io)return Br;io=!0;var i=Gt(),e=i("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Br=e,Br}function Qs(){if(oo)return Fr;oo=!0;var i=Gt(),e=i("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Fr=e,Fr}function Cd(){if(so)return qr;so=!0;var i=Ri(),e=Js(),t=cr(),r=Qs();return qr=function(o,n,s){if(!o||typeof o!="object"&&typeof o!="function")throw new t("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new t("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new t("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new t("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new t("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new t("`loose`, if provided, must be a boolean");var a=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(o,n);if(i)i(o,n,{configurable:c===null&&d?d.configurable:!c,enumerable:a===null&&d?d.enumerable:!a,value:s,writable:l===null&&d?d.writable:!l});else if(u||!a&&!l&&!c)o[n]=s;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},qr}function Pd(){if(ao)return Hr;ao=!0;var i=Ri(),e=function(){return!!i};return e.hasArrayLengthDefineBug=function(){if(!i)return null;try{return i([],"length",{value:1}).length!==1}catch{return!0}},Hr=e,Hr}function Od(){if(lo)return Wr;lo=!0;var i=Gt(),e=Cd(),t=Pd()(),r=Qs(),o=cr(),n=i("%Math.floor%");return Wr=function(s,a){if(typeof s!="function")throw new o("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new o("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in s&&r){var d=r(s,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!l)&&(t?e(s,"length",a,!0,!0):e(s,"length",a)),s},Wr}function Ld(){if(co)return Yt;co=!0;var i=Ni(),e=Gt(),t=Od(),r=cr(),o=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),s=e("%Reflect.apply%",!0)||i.call(n,o),a=Ri(),l=e("%Math.max%");Yt=function(u){if(typeof u!="function")throw new r("a function is required");var d=s(i,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return s(i,o,arguments)};return a?a(Yt,"apply",{value:c}):Yt.apply=c,Yt}function Md(){if(uo)return zr;uo=!0;var i=Gt(),e=Ld(),t=e(i("String.prototype.indexOf"));return zr=function(r,o){var n=i(r,!!o);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},zr}var ji,$i,Di,Ui,Bi,Fi,qi,Hi,Wi,zi,Vi,Ki,Gi,Yi,Ji,Qi,Nr,Xi,Rr,Zi,jr,eo,$r,to,Dr,ro,Ur,no,Br,io,Fr,oo,qr,so,Hr,ao,Wr,lo,Yt,co,zr,uo,Nd=Qe(()=>{le(),ue(),ce(),ji={},$i=!1,Di={},Ui=!1,Bi={},Fi=!1,qi={},Hi=!1,Wi={},zi=!1,Vi={},Ki=!1,Gi={},Yi=!1,Ji={},Qi=!1,Nr={},Xi=!1,Rr={},Zi=!1,jr={},eo=!1,$r={},to=!1,Dr={},ro=!1,Ur={},no=!1,Br={},io=!1,Fr={},oo=!1,qr={},so=!1,Hr={},ao=!1,Wr={},lo=!1,Yt={},co=!1,zr={},uo=!1});function ho(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function Rd(){!Dt||!Ut||(Dt=!1,Ut.length?st=Ut.concat(st):ur=-1,st.length&&Xs())}function Xs(){if(!Dt){var i=setTimeout(Rd,0);Dt=!0;for(var e=st.length;e;){for(Ut=st,st=[];++ur<e;)Ut&&Ut[ur].run();ur=-1,e=st.length}Ut=null,Dt=!1,clearTimeout(i)}}function jd(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];st.push(new Zs(i,e)),st.length===1&&!Dt&&setTimeout(Xs,0)}function Zs(i,e){this.fun=i,this.array=e}function ze(){}function $d(i){ho("_linkedBinding")}function Dd(i){ho("dlopen")}function Ud(){return[]}function Bd(){return[]}function Fd(i,e){if(!i)throw new Error(e||"assertion error")}function qd(){return!1}function Hd(){return _t.now()/1e3}function po(i){var e=Math.floor((Date.now()-_t.now())*.001),t=_t.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return i&&(r=r-i[0],o=o-i[1],o<0&&(r--,o+=Kr)),[r,o]}function Ct(){return mo}function Wd(i){return[]}var st,Dt,Ut,ur,ea,ta,ra,na,ia,oa,sa,aa,la,ca,ua,da,ha,pa,fa,ma,ga,ba,ya,va,wa,Vr,ka,_a,xa,Sa,Ea,Aa,Ia,Ta,Ca,Pa,Oa,La,Ma,Na,Ra,ja,$a,Da,Ua,Ba,Fa,qa,Ha,Wa,za,_t,fo,Kr,Va,Ka,Ga,Ya,Ja,Qa,Xa,Za,el,tl,rl,mo,nl=Qe(()=>{le(),ue(),ce(),st=[],Dt=!1,ur=-1,Zs.prototype.run=function(){this.fun.apply(null,this.array)},ea="browser",ta="x64",ra="browser",na={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},ia=["/usr/bin/node"],oa=[],sa="v16.8.0",aa={},la=function(i,e){console.warn((e?e+": ":"")+i)},ca=function(i){ho("binding")},ua=function(i){return 0},da=function(){return"/"},ha=function(i){},pa={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},fa=ze,ma=[],ga={},ba=!1,ya={},va=ze,wa=ze,Vr=function(){return{}},ka=Vr,_a=Vr,xa=ze,Sa=ze,Ea=ze,Aa={},Ia={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Ta=ze,Ca=ze,Pa=ze,Oa=ze,La=ze,Ma=ze,Na=ze,Ra=void 0,ja=void 0,$a=void 0,Da=ze,Ua=2,Ba=1,Fa="/bin/usr/node",qa=9229,Ha="node",Wa=[],za=ze,_t={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},_t.now===void 0&&(fo=Date.now(),_t.timing&&_t.timing.navigationStart&&(fo=_t.timing.navigationStart),_t.now=()=>Date.now()-fo),Kr=1e9,po.bigint=function(i){var e=po(i);return typeof BigInt>"u"?e[0]*Kr+e[1]:BigInt(e[0]*Kr)+BigInt(e[1])},Va=10,Ka={},Ga=0,Ya=Ct,Ja=Ct,Qa=Ct,Xa=Ct,Za=Ct,el=ze,tl=Ct,rl=Ct,mo={version:sa,versions:aa,arch:ta,platform:ra,release:pa,_rawDebug:fa,moduleLoadList:ma,binding:ca,_linkedBinding:$d,_events:Ka,_eventsCount:Ga,_maxListeners:Va,on:Ct,addListener:Ya,once:Ja,off:Qa,removeListener:Xa,removeAllListeners:Za,emit:el,prependListener:tl,prependOnceListener:rl,listeners:Wd,domain:ga,_exiting:ba,config:ya,dlopen:Dd,uptime:Hd,_getActiveRequests:Ud,_getActiveHandles:Bd,reallyExit:va,_kill:wa,cpuUsage:Vr,resourceUsage:ka,memoryUsage:_a,kill:xa,exit:Sa,openStdin:Ea,allowedNodeEnvironmentFlags:Aa,assert:Fd,features:Ia,_fatalExceptions:Ta,setUncaughtExceptionCaptureCallback:Ca,hasUncaughtExceptionCaptureCallback:qd,emitWarning:la,nextTick:jd,_tickCallback:Pa,_debugProcess:Oa,_debugEnd:La,_startProfilerIdleNotifier:Ma,_stopProfilerIdleNotifier:Na,stdout:Ra,stdin:$a,stderr:ja,abort:Da,umask:ua,chdir:ha,cwd:da,env:na,title:ea,argv:ia,execArgv:oa,pid:Ua,ppid:Ba,execPath:Fa,debugPort:qa,hrtime:po,argv0:Ha,_preload_modules:Wa,setSourceMapsEnabled:za}});function zd(){if(go)return Gr;go=!0;var i=mo;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,s){for(var a="",l=0,c=-1,u=0,d,f=0;f<=n.length;++f){if(f<n.length)d=n.charCodeAt(f);else{if(d===47)break;d=47}if(d===47){if(!(c===f-1||u===1))if(c!==f-1&&u===2){if(a.length<2||l!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var g=a.lastIndexOf("/");if(g!==a.length-1){g===-1?(a="",l=0):(a=a.slice(0,g),l=a.length-1-a.lastIndexOf("/")),c=f,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=f,u=0;continue}}s&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,f):a=n.slice(c+1,f),l=f-c-1;c=f,u=0}else d===46&&u!==-1?++u:u=-1}return a}function r(n,s){var a=s.dir||s.root,l=s.base||(s.name||"")+(s.ext||"");return a?a===s.root?a+l:a+n+l:l}var o={resolve:function(){for(var n="",s=!1,a,l=arguments.length-1;l>=-1&&!s;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=i.cwd()),c=a),e(c),c.length!==0&&(n=c+"/"+n,s=c.charCodeAt(0)===47)}return n=t(n,!s),s?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var s=n.charCodeAt(0)===47,a=n.charCodeAt(n.length-1)===47;return n=t(n,!s),n.length===0&&!s&&(n="."),n.length>0&&a&&(n+="/"),s?"/"+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,s=0;s<arguments.length;++s){var a=arguments[s];e(a),a.length>0&&(n===void 0?n=a:n+="/"+a)}return n===void 0?".":o.normalize(n)},relative:function(n,s){if(e(n),e(s),n===s||(n=o.resolve(n),s=o.resolve(s),n===s))return"";for(var a=1;a<n.length&&n.charCodeAt(a)===47;++a);for(var l=n.length,c=l-a,u=1;u<s.length&&s.charCodeAt(u)===47;++u);for(var d=s.length,f=d-u,g=c<f?c:f,h=-1,b=0;b<=g;++b){if(b===g){if(f>g){if(s.charCodeAt(u+b)===47)return s.slice(u+b+1);if(b===0)return s.slice(u+b)}else c>g&&(n.charCodeAt(a+b)===47?h=b:b===0&&(h=0));break}var y=n.charCodeAt(a+b),w=s.charCodeAt(u+b);if(y!==w)break;y===47&&(h=b)}var m="";for(b=a+h+1;b<=l;++b)(b===l||n.charCodeAt(b)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+s.slice(u+h):(u+=h,s.charCodeAt(u)===47&&++u,s.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var s=n.charCodeAt(0),a=s===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(s=n.charCodeAt(u),s===47){if(!c){l=u;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":n.slice(0,l)},basename:function(n,s){if(s!==void 0&&typeof s!="string")throw new TypeError('"ext" argument must be a string');e(n);var a=0,l=-1,c=!0,u;if(s!==void 0&&s.length>0&&s.length<=n.length){if(s.length===n.length&&s===n)return"";var d=s.length-1,f=-1;for(u=n.length-1;u>=0;--u){var g=n.charCodeAt(u);if(g===47){if(!c){a=u+1;break}}else f===-1&&(c=!1,f=u+1),d>=0&&(g===s.charCodeAt(d)?--d===-1&&(l=u):(d=-1,l=f))}return a===l?l=f:l===-1&&(l=n.length),n.slice(a,l)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){a=u+1;break}}else l===-1&&(c=!1,l=u+1);return l===-1?"":n.slice(a,l)}},extname:function(n){e(n);for(var s=-1,a=0,l=-1,c=!0,u=0,d=n.length-1;d>=0;--d){var f=n.charCodeAt(d);if(f===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),f===46?s===-1?s=d:u!==1&&(u=1):s!==-1&&(u=-1)}return s===-1||l===-1||u===0||u===1&&s===l-1&&s===a+1?"":n.slice(s,l)},format:function(n){if(n===null||typeof n!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof n);return r("/",n)},parse:function(n){e(n);var s={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return s;var a=n.charCodeAt(0),l=a===47,c;l?(s.root="/",c=1):c=0;for(var u=-1,d=0,f=-1,g=!0,h=n.length-1,b=0;h>=c;--h){if(a=n.charCodeAt(h),a===47){if(!g){d=h+1;break}continue}f===-1&&(g=!1,f=h+1),a===46?u===-1?u=h:b!==1&&(b=1):u!==-1&&(b=-1)}return u===-1||f===-1||b===0||b===1&&u===f-1&&u===d+1?f!==-1&&(d===0&&l?s.base=s.name=n.slice(1,f):s.base=s.name=n.slice(d,f)):(d===0&&l?(s.name=n.slice(1,u),s.base=n.slice(1,f)):(s.name=n.slice(d,u),s.base=n.slice(d,f)),s.ext=n.slice(u,f)),d>0?s.dir=n.slice(0,d-1):l&&(s.dir="/"),s},sep:"/",delimiter:":",win32:null,posix:null};return o.posix=o,Gr=o,Gr}var Gr,go,bo,Vd=Qe(()=>{le(),ue(),ce(),nl(),Gr={},go=!1,bo=zd()}),il={};Ht(il,{URL:()=>ml,Url:()=>ul,default:()=>Ve,fileURLToPath:()=>sl,format:()=>dl,parse:()=>fl,pathToFileURL:()=>al,resolve:()=>hl,resolveObject:()=>pl});function Kd(){if(vo)return Yr;vo=!0;var i=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=i&&e&&typeof e.get=="function"?e.get:null,r=i&&Map.prototype.forEach,o=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&o?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,s=o&&n&&typeof n.get=="function"?n.get:null,a=o&&Set.prototype.forEach,l=typeof WeakMap=="function"&&WeakMap.prototype,c=l?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,f=typeof WeakRef=="function"&&WeakRef.prototype,g=f?WeakRef.prototype.deref:null,h=Boolean.prototype.valueOf,b=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,k=String.prototype.replace,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,S=RegExp.prototype.test,E=Array.prototype.concat,I=Array.prototype.join,P=Array.prototype.slice,L=Math.floor,$=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,q=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,F=typeof Symbol=="function"&&typeof Symbol.iterator=="object",D=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===F||!0)?Symbol.toStringTag:null,oe=Object.prototype.propertyIsEnumerable,j=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(K){return K.__proto__}:null);function W(K,ie){if(K===1/0||K===-1/0||K!==K||K&&K>-1e3&&K<1e3||S.call(/e/,ie))return ie;var Te=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof K=="number"){var Ce=K<0?-L(-K):L(K);if(Ce!==K){var Le=String(Ce),Re=m.call(ie,Le.length+1);return k.call(Le,Te,"$&_")+"."+k.call(k.call(Re,/([0-9]{3})/g,"$&_"),/_$/,"")}}return k.call(ie,Te,"$&_")}var re=ll,U=re.custom,Q=Y(U)?U:null;Yr=function K(ie,Te,Ce,Le){var Re=Te||{};if(se(Re,"quoteStyle")&&Re.quoteStyle!=="single"&&Re.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(se(Re,"maxStringLength")&&(typeof Re.maxStringLength=="number"?Re.maxStringLength<0&&Re.maxStringLength!==1/0:Re.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var lt=se(Re,"customInspect")?Re.customInspect:!0;if(typeof lt!="boolean"&<!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(se(Re,"indent")&&Re.indent!==null&&Re.indent!==" "&&!(parseInt(Re.indent,10)===Re.indent&&Re.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(se(Re,"numericSeparator")&&typeof Re.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var ct=Re.numericSeparator;if(typeof ie>"u")return"undefined";if(ie===null)return"null";if(typeof ie=="boolean")return ie?"true":"false";if(typeof ie=="string")return ae(ie,Re);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var Ge=String(ie);return ct?W(ie,Ge):Ge}if(typeof ie=="bigint"){var ut=String(ie)+"n";return ct?W(ie,ut):ut}var tr=typeof Re.depth>"u"?5:Re.depth;if(typeof Ce>"u"&&(Ce=0),Ce>=tr&&tr>0&&typeof ie=="object")return pe(ie)?"[Array]":"[Object]";var dt=Z(Re,Ce);if(typeof Le>"u")Le=[];else if(te(Le,ie)>=0)return"[Circular]";function et(ht,Lt,qt){if(Lt&&(Le=P.call(Le),Le.push(Lt)),qt){var pt={depth:Re.depth};return se(Re,"quoteStyle")&&(pt.quoteStyle=Re.quoteStyle),K(ht,pt,Ce+1,Le)}return K(ht,Re,Ce+1,Le)}if(typeof ie=="function"&&!ve(ie)){var hn=H(ie),rr=_e(ie,et);return"[Function"+(hn?": "+hn:" (anonymous)")+"]"+(rr.length>0?" { "+I.call(rr,", ")+" }":"")}if(Y(ie)){var br=F?k.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):q.call(ie);return typeof ie=="object"&&!F?p(br):br}if(we(ie)){for(var C="<"+v.call(String(ie.nodeName)),N=ie.attributes||[],ke=0;ke<N.length;ke++)C+=" "+N[ke].name+"="+O(J(N[ke].value),"double",Re);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(pe(ie)){if(ie.length===0)return"[]";var Se=_e(ie,et);return dt&&!B(Se)?"["+de(Se,dt)+"]":"[ "+I.call(Se,", ")+" ]"}if(G(ie)){var Ae=_e(ie,et);return!("cause"in Error.prototype)&&"cause"in ie&&!oe.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(E.call("[cause]: "+et(ie.cause),Ae),", ")+" }":Ae.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ae,", ")+" }"}if(typeof ie=="object"&<){if(Q&&typeof ie[Q]=="function"&&re)return re(ie,{depth:tr-Ce});if(lt!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var Fe=[];return r&&r.call(ie,function(ht,Lt){Fe.push(et(Lt,ie,!0)+" => "+et(ht,ie))}),A("Map",t.call(ie),Fe,dt)}if(z(ie)){var Je=[];return a&&a.call(ie,function(ht){Je.push(et(ht,ie))}),A("Set",s.call(ie),Je,dt)}if(fe(ie))return _("WeakMap");if(ge(ie))return _("WeakSet");if(ye(ie))return _("WeakRef");if(ne(ie))return p(et(Number(ie)));if(X(ie))return p(et($.call(ie)));if(V(ie))return p(h.call(ie));if(R(ie))return p(et(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Jr<"u"&&ie===Jr)return"{ [object globalThis] }";if(!ee(ie)&&!ve(ie)){var it=_e(ie,et),yr=j?j(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,vr=ie instanceof Object?"":"null prototype",wr=!yr&&D&&Object(ie)===ie&&D in ie?m.call(M(ie),8,-1):vr?"Object":"",pn=yr||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Ft=pn+(wr||vr?"["+I.call(E.call([],wr||[],vr||[]),": ")+"] ":"");return it.length===0?Ft+"{}":dt?Ft+"{"+de(it,dt)+"}":Ft+"{ "+I.call(it,", ")+" }"}return String(ie)};function O(K,ie,Te){var Ce=(Te.quoteStyle||ie)==="double"?'"':"'";return Ce+K+Ce}function J(K){return k.call(String(K),/"/g,""")}function pe(K){return M(K)==="[object Array]"&&(!D||!(typeof K=="object"&&D in K))}function ee(K){return M(K)==="[object Date]"&&(!D||!(typeof K=="object"&&D in K))}function ve(K){return M(K)==="[object RegExp]"&&(!D||!(typeof K=="object"&&D in K))}function G(K){return M(K)==="[object Error]"&&(!D||!(typeof K=="object"&&D in K))}function R(K){return M(K)==="[object String]"&&(!D||!(typeof K=="object"&&D in K))}function ne(K){return M(K)==="[object Number]"&&(!D||!(typeof K=="object"&&D in K))}function V(K){return M(K)==="[object Boolean]"&&(!D||!(typeof K=="object"&&D in K))}function Y(K){if(F)return K&&typeof K=="object"&&K instanceof Symbol;if(typeof K=="symbol")return!0;if(!K||typeof K!="object"||!q)return!1;try{return q.call(K),!0}catch{}return!1}function X(K){if(!K||typeof K!="object"||!$)return!1;try{return $.call(K),!0}catch{}return!1}var be=Object.prototype.hasOwnProperty||function(K){return K in(this||Jr)};function se(K,ie){return be.call(K,ie)}function M(K){return b.call(K)}function H(K){if(K.name)return K.name;var ie=w.call(y.call(K),/^function\s*([\w$]+)/);return ie?ie[1]:null}function te(K,ie){if(K.indexOf)return K.indexOf(ie);for(var Te=0,Ce=K.length;Te<Ce;Te++)if(K[Te]===ie)return Te;return-1}function he(K){if(!t||!K||typeof K!="object")return!1;try{t.call(K);try{s.call(K)}catch{return!0}return K instanceof Map}catch{}return!1}function fe(K){if(!c||!K||typeof K!="object")return!1;try{c.call(K,c);try{d.call(K,d)}catch{return!0}return K instanceof WeakMap}catch{}return!1}function ye(K){if(!g||!K||typeof K!="object")return!1;try{return g.call(K),!0}catch{}return!1}function z(K){if(!s||!K||typeof K!="object")return!1;try{s.call(K);try{t.call(K)}catch{return!0}return K instanceof Set}catch{}return!1}function ge(K){if(!d||!K||typeof K!="object")return!1;try{d.call(K,d);try{c.call(K,c)}catch{return!0}return K instanceof WeakSet}catch{}return!1}function we(K){return!K||typeof K!="object"?!1:typeof HTMLElement<"u"&&K instanceof HTMLElement?!0:typeof K.nodeName=="string"&&typeof K.getAttribute=="function"}function ae(K,ie){if(K.length>ie.maxStringLength){var Te=K.length-ie.maxStringLength,Ce="... "+Te+" more character"+(Te>1?"s":"");return ae(m.call(K,0,ie.maxStringLength),ie)+Ce}var Le=k.call(k.call(K,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Me);return O(Le,"single",ie)}function Me(K){var ie=K.charCodeAt(0),Te={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Te?"\\"+Te:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function p(K){return"Object("+K+")"}function _(K){return K+" { ? }"}function A(K,ie,Te,Ce){var Le=Ce?de(Te,Ce):I.call(Te,", ");return K+" ("+ie+") {"+Le+"}"}function B(K){for(var ie=0;ie<K.length;ie++)if(te(K[ie],`
|
|
1
|
+
var AikaaraChat=(function(Ne){"use strict";class Yo{identifier;callbacks={};sendFn;constructor(e,t){this.identifier=e,this.sendFn=t}onReceived(e){return this.callbacks.received=e,this}onConnected(e){return this.callbacks.connected=e,this}onDisconnected(e){return this.callbacks.disconnected=e,this}onRejected(e){return this.callbacks.rejected=e,this}perform(e,t={}){this.sendFn({action:e,...t})}_notifyReceived(e){this.callbacks.received?.(e)}_notifyConnected(){this.callbacks.connected?.()}_notifyDisconnected(){this.callbacks.disconnected?.()}_notifyRejected(){this.callbacks.rejected?.()}}class fn{ws=null;url;subscriptions=new Map;welcomePromise=null;pendingSubscriptions=new Map;constructor(e){this.url=e}connect(){return new Promise((e,t)=>{this.welcomePromise={resolve:e,reject:t},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=r=>{this.handleMessage(r)},this.ws.onerror=()=>{const r=new Error("WebSocket connection error");this.welcomePromise?.reject(r),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(r=>r._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(e=>e._notifyDisconnected()),this.subscriptions.clear()}subscribe(e){const t=JSON.stringify(e),r=new Yo(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 _r{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 zc=1e3,Vc=10,Kc=400,Gc=600,Jo="#6366f1",Yc=12,Jc="system-ui, -apple-system, sans-serif",Qo="Type a message...",Qc="bottom-right",Xc="light",Zc={x:20,y:20},mn="aikaara_conversation_id";class Xo extends _r{client;config;state="disconnected";reconnectAttempt=0;reconnectTimer=null;constructor(e){super(),this.config=e;const t=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new fn(t)}async connect(){const e=this.reconnectAttempt>0;this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0,e&&this.emit("reconnected",void 0)}catch(t){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw t}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,t){const r=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(r,"send_message",{content:t})}sendUserEvent(e,t,r,o){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...o&&{source:o}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??Vc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??zc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const o=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new fn(o),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const o=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${o}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class Zo{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,o){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=o}setAuthRefreshHook(e){this.refreshHook=e}getAuthToken(){return this.authToken}setAuthToken(e){this.authToken=e}async createConversation(e){const t={conversation:{...e.extUid&&{ext_uid:e.extUid},...e.systemPromptId&&{system_prompt_id:e.systemPromptId},...e.channel&&{channel:e.channel},...e.title&&{title:e.title}}};return this.request("POST","/api/v1/conversations",t)}async updateContext(e,t){const r=this.authToken?`/dashboard/sidekick_conversations/${e}`:`/api/v1/conversations/${e}`;await this.request("PATCH",r,t)}async getMessages(e){return(await this.request("GET",`/api/v1/conversations/${e}/messages`)).map(this.mapMessage)}mapMessage(e){return{id:String(e.id),conversationId:String(e.conversation_id),role:e.role,content:e.content||"",toolCalls:e.tool_calls?.map(t=>({id:t.id,type:t.type,function:t.function})),toolCallResults:e.tool_call_results,tokensInput:e.tokens_input,tokensOutput:e.tokens_output,metadata:e.metadata,createdAt:e.created_at,status:"complete"}}async request(e,t,r){const o=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(o,e,r);if(n.status===401&&this.refreshHook){let a=null;try{a=await this.refreshHook()}catch(l){console.warn("[aikaara-chat-sdk] auth refresh hook threw",l)}a&&(this.authToken=a,n=await this.fetchWithHeaders(o,e,r))}if(!n.ok){const a=await n.text();let l;try{const c=JSON.parse(a);l=c.error||c.message||a}catch{l=a}throw new Error(`API error ${n.status}: ${l}`)}const s=await n.json();if(s&&typeof s=="object"&&"success"in s){if(!s.success)throw new Error(`API error: ${s.message||"Request failed"}`);return s.data}return s}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 es{_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=ts(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=ts(t,r);if(o){const n=xr(o),s=xr(r);!n&&s&&Object.assign(o,r,{id:o.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function ts(i,e,t=15e3){const r=e.attachments&&e.attachments[0],o=(e.metadata??{}).attributes;if(!(!!r||!!(o&&o.fileMessage)))return null;const s=xr(e),a=rs(e),l=ns(e);if(!s&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=i.length-1;u>=0;u--){const d=i[u],p=d.attachments&&d.attachments[0],g=(d.metadata??{}).attributes;if(!(!!p||!!(g&&g.fileMessage)))continue;const b=(d.content||"").trim().toLowerCase();if(b==="file_uploaded"||b==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const y=xr(d);if(s&&y&&s===y)return d;const w=rs(d);if(a&&w&&a===w)return d;const m=ns(d);if(l&&m&&l===m)return d}return null}function rs(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=is(i);if(t)return t}function ns(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(i.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=i.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function xr(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(i.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=is(i);if(r){const o=/[?&]cloudFileId=([^&]+)/.exec(r);if(o)return decodeURIComponent(o[1])}}function is(i){const e=i.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class os{_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(mn)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(mn)}catch{return null}}saveToStorage(e){try{localStorage.setItem(mn,e)}catch{}}}var gn=Object.defineProperty,eu=Object.getOwnPropertyDescriptor,tu=Object.getOwnPropertyNames,ru=Object.prototype.hasOwnProperty,Qe=(i,e)=>()=>(i&&(e=i(i=0)),e),me=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Ht=(i,e)=>{for(var t in e)gn(i,t,{get:e[t],enumerable:!0})},nu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of tu(e))!ru.call(i,o)&&o!==t&&gn(i,o,{get:()=>e[o],enumerable:!(r=eu(e,o))||r.enumerable});return i},je=i=>nu(gn({},"__esModule",{value:!0}),i),le=Qe(()=>{}),De={};Ht(De,{_debugEnd:()=>Qn,_debugProcess:()=>Jn,_events:()=>pi,_eventsCount:()=>fi,_exiting:()=>jn,_fatalExceptions:()=>Kn,_getActiveHandles:()=>hs,_getActiveRequests:()=>ds,_kill:()=>Un,_linkedBinding:()=>cs,_maxListeners:()=>hi,_preload_modules:()=>ci,_rawDebug:()=>Mn,_startProfilerIdleNotifier:()=>Xn,_stopProfilerIdleNotifier:()=>Zn,_tickCallback:()=>Yn,abort:()=>ni,addListener:()=>mi,allowedNodeEnvironmentFlags:()=>zn,arch:()=>vn,argv:()=>_n,argv0:()=>li,assert:()=>ps,binding:()=>In,browser:()=>Ln,chdir:()=>Pn,config:()=>$n,cpuUsage:()=>ir,cwd:()=>Cn,debugPort:()=>ai,default:()=>xi,dlopen:()=>us,domain:()=>Rn,emit:()=>wi,emitWarning:()=>An,env:()=>kn,execArgv:()=>xn,execPath:()=>si,exit:()=>Hn,features:()=>Vn,hasUncaughtExceptionCaptureCallback:()=>fs,hrtime:()=>Sr,kill:()=>qn,listeners:()=>gs,memoryUsage:()=>Fn,moduleLoadList:()=>Nn,nextTick:()=>as,off:()=>bi,on:()=>ft,once:()=>gi,openStdin:()=>Wn,pid:()=>ii,platform:()=>wn,ppid:()=>oi,prependListener:()=>ki,prependOnceListener:()=>_i,reallyExit:()=>Dn,release:()=>On,removeAllListeners:()=>vi,removeListener:()=>yi,resourceUsage:()=>Bn,setSourceMapsEnabled:()=>ui,setUncaughtExceptionCaptureCallback:()=>Gn,stderr:()=>ti,stdin:()=>ri,stdout:()=>ei,title:()=>yn,umask:()=>Tn,uptime:()=>ms,version:()=>Sn,versions:()=>En});function bn(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function iu(){!Mt||!Nt||(Mt=!1,Nt.length?ot=Nt.concat(ot):nr=-1,ot.length&&ss())}function ss(){if(!Mt){var i=setTimeout(iu,0);Mt=!0;for(var e=ot.length;e;){for(Nt=ot,ot=[];++nr<e;)Nt&&Nt[nr].run();nr=-1,e=ot.length}Nt=null,Mt=!1,clearTimeout(i)}}function as(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];ot.push(new ls(i,e)),ot.length===1&&!Mt&&setTimeout(ss,0)}function ls(i,e){this.fun=i,this.array=e}function We(){}function cs(i){bn("_linkedBinding")}function us(i){bn("dlopen")}function ds(){return[]}function hs(){return[]}function ps(i,e){if(!i)throw new Error(e||"assertion error")}function fs(){return!1}function ms(){return mt.now()/1e3}function Sr(i){var e=Math.floor((Date.now()-mt.now())*.001),t=mt.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return i&&(r=r-i[0],o=o-i[1],o<0&&(r--,o+=Er)),[r,o]}function ft(){return xi}function gs(i){return[]}var ot,Mt,Nt,nr,yn,vn,wn,kn,_n,xn,Sn,En,An,In,Tn,Cn,Pn,On,Ln,Mn,Nn,Rn,jn,$n,Dn,Un,ir,Bn,Fn,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ni,ii,oi,si,ai,li,ci,ui,mt,di,Er,hi,pi,fi,mi,gi,bi,yi,vi,wi,ki,_i,xi,ou=Qe(()=>{le(),ue(),ce(),ot=[],Mt=!1,nr=-1,ls.prototype.run=function(){this.fun.apply(null,this.array)},yn="browser",vn="x64",wn="browser",kn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},_n=["/usr/bin/node"],xn=[],Sn="v16.8.0",En={},An=function(i,e){console.warn((e?e+": ":"")+i)},In=function(i){bn("binding")},Tn=function(i){return 0},Cn=function(){return"/"},Pn=function(i){},On={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Ln=!0,Mn=We,Nn=[],Rn={},jn=!1,$n={},Dn=We,Un=We,ir=function(){return{}},Bn=ir,Fn=ir,qn=We,Hn=We,Wn=We,zn={},Vn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Kn=We,Gn=We,Yn=We,Jn=We,Qn=We,Xn=We,Zn=We,ei=void 0,ti=void 0,ri=void 0,ni=We,ii=2,oi=1,si="/bin/usr/node",ai=9229,li="node",ci=[],ui=We,mt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},mt.now===void 0&&(di=Date.now(),mt.timing&&mt.timing.navigationStart&&(di=mt.timing.navigationStart),mt.now=()=>Date.now()-di),Er=1e9,Sr.bigint=function(i){var e=Sr(i);return typeof BigInt>"u"?e[0]*Er+e[1]:BigInt(e[0]*Er)+BigInt(e[1])},hi=10,pi={},fi=0,mi=ft,gi=ft,bi=ft,yi=ft,vi=ft,wi=We,ki=ft,_i=ft,xi={version:Sn,versions:En,arch:vn,platform:wn,browser:Ln,release:On,_rawDebug:Mn,moduleLoadList:Nn,binding:In,_linkedBinding:cs,_events:pi,_eventsCount:fi,_maxListeners:hi,on:ft,addListener:mi,once:gi,off:bi,removeListener:yi,removeAllListeners:vi,emit:wi,prependListener:ki,prependOnceListener:_i,listeners:gs,domain:Rn,_exiting:jn,config:$n,dlopen:us,uptime:ms,_getActiveRequests:ds,_getActiveHandles:hs,reallyExit:Dn,_kill:Un,cpuUsage:ir,resourceUsage:Bn,memoryUsage:Fn,kill:qn,exit:Hn,openStdin:Wn,allowedNodeEnvironmentFlags:zn,assert:ps,features:Vn,_fatalExceptions:Kn,setUncaughtExceptionCaptureCallback:Gn,hasUncaughtExceptionCaptureCallback:fs,emitWarning:An,nextTick:as,_tickCallback:Yn,_debugProcess:Jn,_debugEnd:Qn,_startProfilerIdleNotifier:Xn,_stopProfilerIdleNotifier:Zn,stdout:ei,stdin:ri,stderr:ti,abort:ni,umask:Tn,chdir:Pn,cwd:Cn,env:kn,title:yn,argv:_n,execArgv:xn,pid:ii,ppid:oi,execPath:si,debugPort:ai,hrtime:Sr,argv0:li,_preload_modules:ci,setSourceMapsEnabled:ui}}),ce=Qe(()=>{ou()});function su(){if(Si)return Wt;Si=!0,Wt.byteLength=a,Wt.toByteArray=c,Wt.fromByteArray=p;for(var i=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,n=r.length;o<n;++o)i[o]=r[o],e[r.charCodeAt(o)]=o;e[45]=62,e[95]=63;function s(g){var h=g.length;if(h%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=g.indexOf("=");b===-1&&(b=h);var y=b===h?0:4-b%4;return[b,y]}function a(g){var h=s(g),b=h[0],y=h[1];return(b+y)*3/4-y}function l(g,h,b){return(h+b)*3/4-b}function c(g){var h,b=s(g),y=b[0],w=b[1],m=new t(l(g,y,w)),k=0,x=w>0?y-4:y,v;for(v=0;v<x;v+=4)h=e[g.charCodeAt(v)]<<18|e[g.charCodeAt(v+1)]<<12|e[g.charCodeAt(v+2)]<<6|e[g.charCodeAt(v+3)],m[k++]=h>>16&255,m[k++]=h>>8&255,m[k++]=h&255;return w===2&&(h=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[k++]=h&255),w===1&&(h=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[k++]=h>>8&255,m[k++]=h&255),m}function u(g){return i[g>>18&63]+i[g>>12&63]+i[g>>6&63]+i[g&63]}function d(g,h,b){for(var y,w=[],m=h;m<b;m+=3)y=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(y));return w.join("")}function p(g){for(var h,b=g.length,y=b%3,w=[],m=16383,k=0,x=b-y;k<x;k+=m)w.push(d(g,k,k+m>x?x:k+m));return y===1?(h=g[b-1],w.push(i[h>>2]+i[h<<4&63]+"==")):y===2&&(h=(g[b-2]<<8)+g[b-1],w.push(i[h>>10]+i[h>>4&63]+i[h<<2&63]+"=")),w.join("")}return Wt}function au(){return Ei?or:(Ei=!0,or.read=function(i,e,t,r,o){var n,s,a=o*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?o-1:0,p=t?-1:1,g=i[e+d];for(d+=p,n=g&(1<<-u)-1,g>>=-u,u+=a;u>0;n=n*256+i[e+d],d+=p,u-=8);for(s=n&(1<<-u)-1,n>>=-u,u+=r;u>0;s=s*256+i[e+d],d+=p,u-=8);if(n===0)n=1-c;else{if(n===l)return s?NaN:(g?-1:1)*(1/0);s=s+Math.pow(2,r),n=n-c}return(g?-1:1)*s*Math.pow(2,n-r)},or.write=function(i,e,t,r,o,n){var s,a,l,c=n*8-o-1,u=(1<<c)-1,d=u>>1,p=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,h=r?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+d>=1?e+=p/l:e+=p*Math.pow(2,1-d),e*l>=2&&(s++,l/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(e*l-1)*Math.pow(2,o),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;i[t+g]=a&255,g+=h,a/=256,o-=8);for(s=s<<o|a,c+=o;c>0;i[t+g]=s&255,g+=h,s/=256,c-=8);i[t+g-h]|=b*128},or)}function lu(){if(Ai)return Et;Ai=!0;let i=su(),e=au(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Et.Buffer=s,Et.SlowBuffer=w,Et.INSPECT_MAX_BYTES=50;let r=2147483647;Et.kMaxLength=r,s.TYPED_ARRAY_SUPPORT=o(),!s.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function o(){try{let f=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(f,_),f.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function n(f){if(f>r)throw new RangeError('The value "'+f+'" is invalid for option "size"');let _=new Uint8Array(f);return Object.setPrototypeOf(_,s.prototype),_}function s(f,_,A){if(typeof f=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(f)}return a(f,_,A)}s.poolSize=8192;function a(f,_,A){if(typeof f=="string")return d(f,_);if(ArrayBuffer.isView(f))return g(f);if(f==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof f);if(z(f,ArrayBuffer)||f&&z(f.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(z(f,SharedArrayBuffer)||f&&z(f.buffer,SharedArrayBuffer)))return h(f,_,A);if(typeof f=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=f.valueOf&&f.valueOf();if(B!=null&&B!==f)return s.from(B,_,A);let Z=b(f);if(Z)return Z;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof f[Symbol.toPrimitive]=="function")return s.from(f[Symbol.toPrimitive]("string"),_,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof f)}s.from=function(f,_,A){return a(f,_,A)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(f){if(typeof f!="number")throw new TypeError('"size" argument must be of type number');if(f<0)throw new RangeError('The value "'+f+'" is invalid for option "size"')}function c(f,_,A){return l(f),f<=0?n(f):_!==void 0?typeof A=="string"?n(f).fill(_,A):n(f).fill(_):n(f)}s.alloc=function(f,_,A){return c(f,_,A)};function u(f){return l(f),n(f<0?0:y(f)|0)}s.allocUnsafe=function(f){return u(f)},s.allocUnsafeSlow=function(f){return u(f)};function d(f,_){if((typeof _!="string"||_==="")&&(_="utf8"),!s.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let A=m(f,_)|0,B=n(A),Z=B.write(f,_);return Z!==A&&(B=B.slice(0,Z)),B}function p(f){let _=f.length<0?0:y(f.length)|0,A=n(_);for(let B=0;B<_;B+=1)A[B]=f[B]&255;return A}function g(f){if(z(f,Uint8Array)){let _=new Uint8Array(f);return h(_.buffer,_.byteOffset,_.byteLength)}return p(f)}function h(f,_,A){if(_<0||f.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(f.byteLength<_+(A||0))throw new RangeError('"length" is outside of buffer bounds');let B;return _===void 0&&A===void 0?B=new Uint8Array(f):A===void 0?B=new Uint8Array(f,_):B=new Uint8Array(f,_,A),Object.setPrototypeOf(B,s.prototype),B}function b(f){if(s.isBuffer(f)){let _=y(f.length)|0,A=n(_);return A.length===0||f.copy(A,0,0,_),A}if(f.length!==void 0)return typeof f.length!="number"||ge(f.length)?n(0):p(f);if(f.type==="Buffer"&&Array.isArray(f.data))return p(f.data)}function y(f){if(f>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return f|0}function w(f){return+f!=f&&(f=0),s.alloc(+f)}s.isBuffer=function(f){return f!=null&&f._isBuffer===!0&&f!==s.prototype},s.compare=function(f,_){if(z(f,Uint8Array)&&(f=s.from(f,f.offset,f.byteLength)),z(_,Uint8Array)&&(_=s.from(_,_.offset,_.byteLength)),!s.isBuffer(f)||!s.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(f===_)return 0;let A=f.length,B=_.length;for(let Z=0,de=Math.min(A,B);Z<de;++Z)if(f[Z]!==_[Z]){A=f[Z],B=_[Z];break}return A<B?-1:B<A?1:0},s.isEncoding=function(f){switch(String(f).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(f,_){if(!Array.isArray(f))throw new TypeError('"list" argument must be an Array of Buffers');if(f.length===0)return s.alloc(0);let A;if(_===void 0)for(_=0,A=0;A<f.length;++A)_+=f[A].length;let B=s.allocUnsafe(_),Z=0;for(A=0;A<f.length;++A){let de=f[A];if(z(de,Uint8Array))Z+de.length>B.length?(s.isBuffer(de)||(de=s.from(de)),de.copy(B,Z)):Uint8Array.prototype.set.call(B,de,Z);else if(s.isBuffer(de))de.copy(B,Z);else throw new TypeError('"list" argument must be an Array of Buffers');Z+=de.length}return B};function m(f,_){if(s.isBuffer(f))return f.length;if(ArrayBuffer.isView(f)||z(f,ArrayBuffer))return f.byteLength;if(typeof f!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof f);let A=f.length,B=arguments.length>2&&arguments[2]===!0;if(!B&&A===0)return 0;let Z=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return H(f).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(f).length;default:if(Z)return B?-1:H(f).length;_=(""+_).toLowerCase(),Z=!0}}s.byteLength=m;function k(f,_,A){let B=!1;if((_===void 0||_<0)&&(_=0),_>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,_>>>=0,A<=_))return"";for(f||(f="utf8");;)switch(f){case"hex":return W(this,_,A);case"utf8":case"utf-8":return q(this,_,A);case"ascii":return oe(this,_,A);case"latin1":case"binary":return j(this,_,A);case"base64":return T(this,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,_,A);default:if(B)throw new TypeError("Unknown encoding: "+f);f=(f+"").toLowerCase(),B=!0}}s.prototype._isBuffer=!0;function x(f,_,A){let B=f[_];f[_]=f[A],f[A]=B}s.prototype.swap16=function(){let f=this.length;if(f%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<f;_+=2)x(this,_,_+1);return this},s.prototype.swap32=function(){let f=this.length;if(f%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<f;_+=4)x(this,_,_+3),x(this,_+1,_+2);return this},s.prototype.swap64=function(){let f=this.length;if(f%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<f;_+=8)x(this,_,_+7),x(this,_+1,_+6),x(this,_+2,_+5),x(this,_+3,_+4);return this},s.prototype.toString=function(){let f=this.length;return f===0?"":arguments.length===0?q(this,0,f):k.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(f){if(!s.isBuffer(f))throw new TypeError("Argument must be a Buffer");return this===f?!0:s.compare(this,f)===0},s.prototype.inspect=function(){let f="",_=Et.INSPECT_MAX_BYTES;return f=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(f+=" ... "),"<Buffer "+f+">"},t&&(s.prototype[t]=s.prototype.inspect),s.prototype.compare=function(f,_,A,B,Z){if(z(f,Uint8Array)&&(f=s.from(f,f.offset,f.byteLength)),!s.isBuffer(f))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof f);if(_===void 0&&(_=0),A===void 0&&(A=f?f.length:0),B===void 0&&(B=0),Z===void 0&&(Z=this.length),_<0||A>f.length||B<0||Z>this.length)throw new RangeError("out of range index");if(B>=Z&&_>=A)return 0;if(B>=Z)return-1;if(_>=A)return 1;if(_>>>=0,A>>>=0,B>>>=0,Z>>>=0,this===f)return 0;let de=Z-B,_e=A-_,K=Math.min(de,_e),ie=this.slice(B,Z),Te=f.slice(_,A);for(let Ce=0;Ce<K;++Ce)if(ie[Ce]!==Te[Ce]){de=ie[Ce],_e=Te[Ce];break}return de<_e?-1:_e<de?1:0};function v(f,_,A,B,Z){if(f.length===0)return-1;if(typeof A=="string"?(B=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,ge(A)&&(A=Z?0:f.length-1),A<0&&(A=f.length+A),A>=f.length){if(Z)return-1;A=f.length-1}else if(A<0)if(Z)A=0;else return-1;if(typeof _=="string"&&(_=s.from(_,B)),s.isBuffer(_))return _.length===0?-1:S(f,_,A,B,Z);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?Z?Uint8Array.prototype.indexOf.call(f,_,A):Uint8Array.prototype.lastIndexOf.call(f,_,A):S(f,[_],A,B,Z);throw new TypeError("val must be string, number or Buffer")}function S(f,_,A,B,Z){let de=1,_e=f.length,K=_.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(f.length<2||_.length<2)return-1;de=2,_e/=2,K/=2,A/=2}function ie(Ce,Le){return de===1?Ce[Le]:Ce.readUInt16BE(Le*de)}let Te;if(Z){let Ce=-1;for(Te=A;Te<_e;Te++)if(ie(f,Te)===ie(_,Ce===-1?0:Te-Ce)){if(Ce===-1&&(Ce=Te),Te-Ce+1===K)return Ce*de}else Ce!==-1&&(Te-=Te-Ce),Ce=-1}else for(A+K>_e&&(A=_e-K),Te=A;Te>=0;Te--){let Ce=!0;for(let Le=0;Le<K;Le++)if(ie(f,Te+Le)!==ie(_,Le)){Ce=!1;break}if(Ce)return Te}return-1}s.prototype.includes=function(f,_,A){return this.indexOf(f,_,A)!==-1},s.prototype.indexOf=function(f,_,A){return v(this,f,_,A,!0)},s.prototype.lastIndexOf=function(f,_,A){return v(this,f,_,A,!1)};function E(f,_,A,B){A=Number(A)||0;let Z=f.length-A;B?(B=Number(B),B>Z&&(B=Z)):B=Z;let de=_.length;B>de/2&&(B=de/2);let _e;for(_e=0;_e<B;++_e){let K=parseInt(_.substr(_e*2,2),16);if(ge(K))return _e;f[A+_e]=K}return _e}function I(f,_,A,B){return ye(H(_,f.length-A),f,A,B)}function P(f,_,A,B){return ye(te(_),f,A,B)}function L(f,_,A,B){return ye(fe(_),f,A,B)}function $(f,_,A,B){return ye(he(_,f.length-A),f,A,B)}s.prototype.write=function(f,_,A,B){if(_===void 0)B="utf8",A=this.length,_=0;else if(A===void 0&&typeof _=="string")B=_,A=this.length,_=0;else if(isFinite(_))_=_>>>0,isFinite(A)?(A=A>>>0,B===void 0&&(B="utf8")):(B=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let Z=this.length-_;if((A===void 0||A>Z)&&(A=Z),f.length>0&&(A<0||_<0)||_>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let de=!1;for(;;)switch(B){case"hex":return E(this,f,_,A);case"utf8":case"utf-8":return I(this,f,_,A);case"ascii":case"latin1":case"binary":return P(this,f,_,A);case"base64":return L(this,f,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return $(this,f,_,A);default:if(de)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),de=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(f,_,A){return _===0&&A===f.length?i.fromByteArray(f):i.fromByteArray(f.slice(_,A))}function q(f,_,A){A=Math.min(f.length,A);let B=[],Z=_;for(;Z<A;){let de=f[Z],_e=null,K=de>239?4:de>223?3:de>191?2:1;if(Z+K<=A){let ie,Te,Ce,Le;switch(K){case 1:de<128&&(_e=de);break;case 2:ie=f[Z+1],(ie&192)===128&&(Le=(de&31)<<6|ie&63,Le>127&&(_e=Le));break;case 3:ie=f[Z+1],Te=f[Z+2],(ie&192)===128&&(Te&192)===128&&(Le=(de&15)<<12|(ie&63)<<6|Te&63,Le>2047&&(Le<55296||Le>57343)&&(_e=Le));break;case 4:ie=f[Z+1],Te=f[Z+2],Ce=f[Z+3],(ie&192)===128&&(Te&192)===128&&(Ce&192)===128&&(Le=(de&15)<<18|(ie&63)<<12|(Te&63)<<6|Ce&63,Le>65535&&Le<1114112&&(_e=Le))}}_e===null?(_e=65533,K=1):_e>65535&&(_e-=65536,B.push(_e>>>10&1023|55296),_e=56320|_e&1023),B.push(_e),Z+=K}return D(B)}let F=4096;function D(f){let _=f.length;if(_<=F)return String.fromCharCode.apply(String,f);let A="",B=0;for(;B<_;)A+=String.fromCharCode.apply(String,f.slice(B,B+=F));return A}function oe(f,_,A){let B="";A=Math.min(f.length,A);for(let Z=_;Z<A;++Z)B+=String.fromCharCode(f[Z]&127);return B}function j(f,_,A){let B="";A=Math.min(f.length,A);for(let Z=_;Z<A;++Z)B+=String.fromCharCode(f[Z]);return B}function W(f,_,A){let B=f.length;(!_||_<0)&&(_=0),(!A||A<0||A>B)&&(A=B);let Z="";for(let de=_;de<A;++de)Z+=we[f[de]];return Z}function re(f,_,A){let B=f.slice(_,A),Z="";for(let de=0;de<B.length-1;de+=2)Z+=String.fromCharCode(B[de]+B[de+1]*256);return Z}s.prototype.slice=function(f,_){let A=this.length;f=~~f,_=_===void 0?A:~~_,f<0?(f+=A,f<0&&(f=0)):f>A&&(f=A),_<0?(_+=A,_<0&&(_=0)):_>A&&(_=A),_<f&&(_=f);let B=this.subarray(f,_);return Object.setPrototypeOf(B,s.prototype),B};function U(f,_,A){if(f%1!==0||f<0)throw new RangeError("offset is not uint");if(f+_>A)throw new RangeError("Trying to access beyond buffer length")}s.prototype.readUintLE=s.prototype.readUIntLE=function(f,_,A){f=f>>>0,_=_>>>0,A||U(f,_,this.length);let B=this[f],Z=1,de=0;for(;++de<_&&(Z*=256);)B+=this[f+de]*Z;return B},s.prototype.readUintBE=s.prototype.readUIntBE=function(f,_,A){f=f>>>0,_=_>>>0,A||U(f,_,this.length);let B=this[f+--_],Z=1;for(;_>0&&(Z*=256);)B+=this[f+--_]*Z;return B},s.prototype.readUint8=s.prototype.readUInt8=function(f,_){return f=f>>>0,_||U(f,1,this.length),this[f]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(f,_){return f=f>>>0,_||U(f,2,this.length),this[f]|this[f+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(f,_){return f=f>>>0,_||U(f,2,this.length),this[f]<<8|this[f+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(f,_){return f=f>>>0,_||U(f,4,this.length),(this[f]|this[f+1]<<8|this[f+2]<<16)+this[f+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(f,_){return f=f>>>0,_||U(f,4,this.length),this[f]*16777216+(this[f+1]<<16|this[f+2]<<8|this[f+3])},s.prototype.readBigUInt64LE=ae(function(f){f=f>>>0,X(f,"offset");let _=this[f],A=this[f+7];(_===void 0||A===void 0)&&be(f,this.length-8);let B=_+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24,Z=this[++f]+this[++f]*2**8+this[++f]*2**16+A*2**24;return BigInt(B)+(BigInt(Z)<<BigInt(32))}),s.prototype.readBigUInt64BE=ae(function(f){f=f>>>0,X(f,"offset");let _=this[f],A=this[f+7];(_===void 0||A===void 0)&&be(f,this.length-8);let B=_*2**24+this[++f]*2**16+this[++f]*2**8+this[++f],Z=this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(Z)}),s.prototype.readIntLE=function(f,_,A){f=f>>>0,_=_>>>0,A||U(f,_,this.length);let B=this[f],Z=1,de=0;for(;++de<_&&(Z*=256);)B+=this[f+de]*Z;return Z*=128,B>=Z&&(B-=Math.pow(2,8*_)),B},s.prototype.readIntBE=function(f,_,A){f=f>>>0,_=_>>>0,A||U(f,_,this.length);let B=_,Z=1,de=this[f+--B];for(;B>0&&(Z*=256);)de+=this[f+--B]*Z;return Z*=128,de>=Z&&(de-=Math.pow(2,8*_)),de},s.prototype.readInt8=function(f,_){return f=f>>>0,_||U(f,1,this.length),this[f]&128?(255-this[f]+1)*-1:this[f]},s.prototype.readInt16LE=function(f,_){f=f>>>0,_||U(f,2,this.length);let A=this[f]|this[f+1]<<8;return A&32768?A|4294901760:A},s.prototype.readInt16BE=function(f,_){f=f>>>0,_||U(f,2,this.length);let A=this[f+1]|this[f]<<8;return A&32768?A|4294901760:A},s.prototype.readInt32LE=function(f,_){return f=f>>>0,_||U(f,4,this.length),this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24},s.prototype.readInt32BE=function(f,_){return f=f>>>0,_||U(f,4,this.length),this[f]<<24|this[f+1]<<16|this[f+2]<<8|this[f+3]},s.prototype.readBigInt64LE=ae(function(f){f=f>>>0,X(f,"offset");let _=this[f],A=this[f+7];(_===void 0||A===void 0)&&be(f,this.length-8);let B=this[f+4]+this[f+5]*2**8+this[f+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(_+this[++f]*256+this[++f]*65536+this[++f]*16777216)}),s.prototype.readBigInt64BE=ae(function(f){f=f>>>0,X(f,"offset");let _=this[f],A=this[f+7];(_===void 0||A===void 0)&&be(f,this.length-8);let B=(_<<24)+this[++f]*2**16+this[++f]*2**8+this[++f];return(BigInt(B)<<BigInt(32))+BigInt(this[++f]*16777216+this[++f]*65536+this[++f]*256+A)}),s.prototype.readFloatLE=function(f,_){return f=f>>>0,_||U(f,4,this.length),e.read(this,f,!0,23,4)},s.prototype.readFloatBE=function(f,_){return f=f>>>0,_||U(f,4,this.length),e.read(this,f,!1,23,4)},s.prototype.readDoubleLE=function(f,_){return f=f>>>0,_||U(f,8,this.length),e.read(this,f,!0,52,8)},s.prototype.readDoubleBE=function(f,_){return f=f>>>0,_||U(f,8,this.length),e.read(this,f,!1,52,8)};function Q(f,_,A,B,Z,de){if(!s.isBuffer(f))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>Z||_<de)throw new RangeError('"value" argument is out of bounds');if(A+B>f.length)throw new RangeError("Index out of range")}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(f,_,A,B){if(f=+f,_=_>>>0,A=A>>>0,!B){let _e=Math.pow(2,8*A)-1;Q(this,f,_,A,_e,0)}let Z=1,de=0;for(this[_]=f&255;++de<A&&(Z*=256);)this[_+de]=f/Z&255;return _+A},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(f,_,A,B){if(f=+f,_=_>>>0,A=A>>>0,!B){let _e=Math.pow(2,8*A)-1;Q(this,f,_,A,_e,0)}let Z=A-1,de=1;for(this[_+Z]=f&255;--Z>=0&&(de*=256);)this[_+Z]=f/de&255;return _+A},s.prototype.writeUint8=s.prototype.writeUInt8=function(f,_,A){return f=+f,_=_>>>0,A||Q(this,f,_,1,255,0),this[_]=f&255,_+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(f,_,A){return f=+f,_=_>>>0,A||Q(this,f,_,2,65535,0),this[_]=f&255,this[_+1]=f>>>8,_+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(f,_,A){return f=+f,_=_>>>0,A||Q(this,f,_,2,65535,0),this[_]=f>>>8,this[_+1]=f&255,_+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(f,_,A){return f=+f,_=_>>>0,A||Q(this,f,_,4,4294967295,0),this[_+3]=f>>>24,this[_+2]=f>>>16,this[_+1]=f>>>8,this[_]=f&255,_+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(f,_,A){return f=+f,_=_>>>0,A||Q(this,f,_,4,4294967295,0),this[_]=f>>>24,this[_+1]=f>>>16,this[_+2]=f>>>8,this[_+3]=f&255,_+4};function O(f,_,A,B,Z){Y(_,B,Z,f,A,7);let de=Number(_&BigInt(4294967295));f[A++]=de,de=de>>8,f[A++]=de,de=de>>8,f[A++]=de,de=de>>8,f[A++]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return f[A++]=_e,_e=_e>>8,f[A++]=_e,_e=_e>>8,f[A++]=_e,_e=_e>>8,f[A++]=_e,A}function J(f,_,A,B,Z){Y(_,B,Z,f,A,7);let de=Number(_&BigInt(4294967295));f[A+7]=de,de=de>>8,f[A+6]=de,de=de>>8,f[A+5]=de,de=de>>8,f[A+4]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return f[A+3]=_e,_e=_e>>8,f[A+2]=_e,_e=_e>>8,f[A+1]=_e,_e=_e>>8,f[A]=_e,A+8}s.prototype.writeBigUInt64LE=ae(function(f,_=0){return O(this,f,_,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=ae(function(f,_=0){return J(this,f,_,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(f,_,A,B){if(f=+f,_=_>>>0,!B){let K=Math.pow(2,8*A-1);Q(this,f,_,A,K-1,-K)}let Z=0,de=1,_e=0;for(this[_]=f&255;++Z<A&&(de*=256);)f<0&&_e===0&&this[_+Z-1]!==0&&(_e=1),this[_+Z]=(f/de>>0)-_e&255;return _+A},s.prototype.writeIntBE=function(f,_,A,B){if(f=+f,_=_>>>0,!B){let K=Math.pow(2,8*A-1);Q(this,f,_,A,K-1,-K)}let Z=A-1,de=1,_e=0;for(this[_+Z]=f&255;--Z>=0&&(de*=256);)f<0&&_e===0&&this[_+Z+1]!==0&&(_e=1),this[_+Z]=(f/de>>0)-_e&255;return _+A},s.prototype.writeInt8=function(f,_,A){return f=+f,_=_>>>0,A||Q(this,f,_,1,127,-128),f<0&&(f=255+f+1),this[_]=f&255,_+1},s.prototype.writeInt16LE=function(f,_,A){return f=+f,_=_>>>0,A||Q(this,f,_,2,32767,-32768),this[_]=f&255,this[_+1]=f>>>8,_+2},s.prototype.writeInt16BE=function(f,_,A){return f=+f,_=_>>>0,A||Q(this,f,_,2,32767,-32768),this[_]=f>>>8,this[_+1]=f&255,_+2},s.prototype.writeInt32LE=function(f,_,A){return f=+f,_=_>>>0,A||Q(this,f,_,4,2147483647,-2147483648),this[_]=f&255,this[_+1]=f>>>8,this[_+2]=f>>>16,this[_+3]=f>>>24,_+4},s.prototype.writeInt32BE=function(f,_,A){return f=+f,_=_>>>0,A||Q(this,f,_,4,2147483647,-2147483648),f<0&&(f=4294967295+f+1),this[_]=f>>>24,this[_+1]=f>>>16,this[_+2]=f>>>8,this[_+3]=f&255,_+4},s.prototype.writeBigInt64LE=ae(function(f,_=0){return O(this,f,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=ae(function(f,_=0){return J(this,f,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function pe(f,_,A,B,Z,de){if(A+B>f.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function ee(f,_,A,B,Z){return _=+_,A=A>>>0,Z||pe(f,_,A,4),e.write(f,_,A,B,23,4),A+4}s.prototype.writeFloatLE=function(f,_,A){return ee(this,f,_,!0,A)},s.prototype.writeFloatBE=function(f,_,A){return ee(this,f,_,!1,A)};function ve(f,_,A,B,Z){return _=+_,A=A>>>0,Z||pe(f,_,A,8),e.write(f,_,A,B,52,8),A+8}s.prototype.writeDoubleLE=function(f,_,A){return ve(this,f,_,!0,A)},s.prototype.writeDoubleBE=function(f,_,A){return ve(this,f,_,!1,A)},s.prototype.copy=function(f,_,A,B){if(!s.isBuffer(f))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),_>=f.length&&(_=f.length),_||(_=0),B>0&&B<A&&(B=A),B===A||f.length===0||this.length===0)return 0;if(_<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),f.length-_<B-A&&(B=f.length-_+A);let Z=B-A;return this===f&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,A,B):Uint8Array.prototype.set.call(f,this.subarray(A,B),_),Z},s.prototype.fill=function(f,_,A,B){if(typeof f=="string"){if(typeof _=="string"?(B=_,_=0,A=this.length):typeof A=="string"&&(B=A,A=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!s.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(f.length===1){let de=f.charCodeAt(0);(B==="utf8"&&de<128||B==="latin1")&&(f=de)}}else typeof f=="number"?f=f&255:typeof f=="boolean"&&(f=Number(f));if(_<0||this.length<_||this.length<A)throw new RangeError("Out of range index");if(A<=_)return this;_=_>>>0,A=A===void 0?this.length:A>>>0,f||(f=0);let Z;if(typeof f=="number")for(Z=_;Z<A;++Z)this[Z]=f;else{let de=s.isBuffer(f)?f:s.from(f,B),_e=de.length;if(_e===0)throw new TypeError('The value "'+f+'" is invalid for argument "value"');for(Z=0;Z<A-_;++Z)this[Z+_]=de[Z%_e]}return this};let G={};function R(f,_,A){G[f]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${f}]`,this.stack,delete this.name}get code(){return f}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${f}]: ${this.message}`}}}R("ERR_BUFFER_OUT_OF_BOUNDS",function(f){return f?`${f} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),R("ERR_INVALID_ARG_TYPE",function(f,_){return`The "${f}" argument must be of type number. Received type ${typeof _}`},TypeError),R("ERR_OUT_OF_RANGE",function(f,_,A){let B=`The value of "${f}" is out of range.`,Z=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?Z=ne(String(A)):typeof A=="bigint"&&(Z=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(Z=ne(Z)),Z+="n"),B+=` It must be ${_}. Received ${Z}`,B},RangeError);function ne(f){let _="",A=f.length,B=f[0]==="-"?1:0;for(;A>=B+4;A-=3)_=`_${f.slice(A-3,A)}${_}`;return`${f.slice(0,A)}${_}`}function V(f,_,A){X(_,"offset"),(f[_]===void 0||f[_+A]===void 0)&&be(_,f.length-(A+1))}function Y(f,_,A,B,Z,de){if(f>A||f<_){let _e=typeof _=="bigint"?"n":"",K;throw _===0||_===BigInt(0)?K=`>= 0${_e} and < 2${_e} ** ${(de+1)*8}${_e}`:K=`>= -(2${_e} ** ${(de+1)*8-1}${_e}) and < 2 ** ${(de+1)*8-1}${_e}`,new G.ERR_OUT_OF_RANGE("value",K,f)}V(B,Z,de)}function X(f,_){if(typeof f!="number")throw new G.ERR_INVALID_ARG_TYPE(_,"number",f)}function be(f,_,A){throw Math.floor(f)!==f?(X(f,A),new G.ERR_OUT_OF_RANGE("offset","an integer",f)):_<0?new G.ERR_BUFFER_OUT_OF_BOUNDS:new G.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,f)}let se=/[^+/0-9A-Za-z-_]/g;function M(f){if(f=f.split("=")[0],f=f.trim().replace(se,""),f.length<2)return"";for(;f.length%4!==0;)f=f+"=";return f}function H(f,_){_=_||1/0;let A,B=f.length,Z=null,de=[];for(let _e=0;_e<B;++_e){if(A=f.charCodeAt(_e),A>55295&&A<57344){if(!Z){if(A>56319){(_-=3)>-1&&de.push(239,191,189);continue}else if(_e+1===B){(_-=3)>-1&&de.push(239,191,189);continue}Z=A;continue}if(A<56320){(_-=3)>-1&&de.push(239,191,189),Z=A;continue}A=(Z-55296<<10|A-56320)+65536}else Z&&(_-=3)>-1&&de.push(239,191,189);if(Z=null,A<128){if((_-=1)<0)break;de.push(A)}else if(A<2048){if((_-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((_-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((_-=4)<0)break;de.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return de}function te(f){let _=[];for(let A=0;A<f.length;++A)_.push(f.charCodeAt(A)&255);return _}function he(f,_){let A,B,Z,de=[];for(let _e=0;_e<f.length&&!((_-=2)<0);++_e)A=f.charCodeAt(_e),B=A>>8,Z=A%256,de.push(Z),de.push(B);return de}function fe(f){return i.toByteArray(M(f))}function ye(f,_,A,B){let Z;for(Z=0;Z<B&&!(Z+A>=_.length||Z>=f.length);++Z)_[Z+A]=f[Z];return Z}function z(f,_){return f instanceof _||f!=null&&f.constructor!=null&&f.constructor.name!=null&&f.constructor.name===_.name}function ge(f){return f!==f}let we=(function(){let f="0123456789abcdef",_=new Array(256);for(let A=0;A<16;++A){let B=A*16;for(let Z=0;Z<16;++Z)_[B+Z]=f[A]+f[Z]}return _})();function ae(f){return typeof BigInt>"u"?Me:f}function Me(){throw new Error("BigInt not supported")}return Et}var Wt,Si,or,Ei,Et,Ai,cu=Qe(()=>{le(),ue(),ce(),Wt={},Si=!1,or={},Ei=!1,Et={},Ai=!1}),qe={};Ht(qe,{Buffer:()=>Ar,INSPECT_MAX_BYTES:()=>bs,default:()=>gt,kMaxLength:()=>ys});var gt,Ar,bs,ys,He=Qe(()=>{le(),ue(),ce(),cu(),gt=lu(),gt.Buffer,gt.SlowBuffer,gt.INSPECT_MAX_BYTES,gt.kMaxLength,Ar=gt.Buffer,bs=gt.INSPECT_MAX_BYTES,ys=gt.kMaxLength}),ue=Qe(()=>{He()}),Be=me((i,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}}),vs=me((i,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[o,n]){let s=r.shift();return n==="f"?s.toFixed(6):n==="j"?JSON.stringify(s):n==="s"&&typeof s=="object"?`${s.constructor!==Object?s.constructor.name:""} {}`.trim():s.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"{}"}}}}),Ye=me((i,e)=>{le(),ue(),ce();var{format:t,inspect:r}=vs(),{AggregateError:o}=Be(),n=globalThis.AggregateError||o,s=Symbol("kIsNodeError"),a=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function d(m,k){if(!m)throw new u.ERR_INTERNAL_ASSERTION(k)}function p(m){let k="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)k=`_${m.slice(x-3,x)}${k}`;return`${m.slice(0,x)}${k}`}function g(m,k,x){if(typeof k=="function")return d(k.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${k.length}).`),k(...x);let v=(k.match(/%[dfijoOs]/g)||[]).length;return d(v===x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${v}).`),x.length===0?k:t(k,...x)}function h(m,k,x){x||(x=Error);class v extends x{constructor(...E){super(g(m,k,E))}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[s]=!0,u[m]=v}function b(m){let k=c+m.name;return Object.defineProperty(m,"name",{value:k}),m}function y(m,k){if(m&&k&&m!==k){if(Array.isArray(k.errors))return k.errors.push(m),k;let x=new n([k,m],k.message);return x.code=k.code,x}return m||k}var w=class extends Error{constructor(m="The operation was aborted",k=void 0){if(k!==void 0&&typeof k!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",k);super(m,k),this.code="ABORT_ERR",this.name="AbortError"}};h("ERR_ASSERTION","%s",Error),h("ERR_INVALID_ARG_TYPE",(m,k,x)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(k)||(k=[k]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let S=[],E=[],I=[];for(let L of k)d(typeof L=="string","All expected entries have to be of type string"),a.includes(L)?S.push(L.toLowerCase()):l.test(L)?E.push(L):(d(L!=="object",'The value "object" should be written as "Object"'),I.push(L));if(E.length>0){let L=S.indexOf("object");L!==-1&&(S.splice(S,L,1),E.push("Object"))}if(S.length>0){switch(S.length){case 1:v+=`of type ${S[0]}`;break;case 2:v+=`one of type ${S[0]} or ${S[1]}`;break;default:{let L=S.pop();v+=`one of type ${S.join(", ")}, or ${L}`}}(E.length>0||I.length>0)&&(v+=" or ")}if(E.length>0){switch(E.length){case 1:v+=`an instance of ${E[0]}`;break;case 2:v+=`an instance of ${E[0]} or ${E[1]}`;break;default:{let L=E.pop();v+=`an instance of ${E.join(", ")}, or ${L}`}}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 L=I.pop();v+=`one of ${I.join(", ")}, or ${L}`}}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 L=r(x,{depth:-1});v+=`. Received ${L}`}}else{let L=r(x,{colors:!1});L.length>25&&(L=`${L.slice(0,25)}...`),v+=`. Received type ${typeof x} (${L})`}return v},TypeError),h("ERR_INVALID_ARG_VALUE",(m,k,x="is invalid")=>{let v=r(k);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${x}. Received ${v}`},TypeError),h("ERR_INVALID_RETURN_VALUE",(m,k,x)=>{var v;let S=x!=null&&(v=x.constructor)!==null&&v!==void 0&&v.name?`instance of ${x.constructor.name}`:`type ${typeof x}`;return`Expected ${m} to be returned from the "${k}" function but got ${S}.`},TypeError),h("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let k,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:k+=`The ${m[0]} argument`;break;case 2:k+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();k+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${k} must be specified`},TypeError),h("ERR_OUT_OF_RANGE",(m,k,x)=>{d(k,'Missing "range" argument');let v;if(Number.isInteger(x)&&Math.abs(x)>2**32)v=p(String(x));else if(typeof x=="bigint"){v=String(x);let S=BigInt(2)**BigInt(32);(x>S||x<-S)&&(v=p(v)),v+="n"}else v=r(x);return`The value of "${m}" is out of range. It must be ${k}. Received ${v}`},RangeError),h("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),h("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),h("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),h("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),h("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),h("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),h("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),h("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),h("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),h("ERR_STREAM_WRITE_AFTER_END","write after end",Error),h("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:b(y),hideStackFrames:b,codes:u}}),sr=me((i,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}),At={};Ht(At,{EventEmitter:()=>ws,default:()=>zt,defaultMaxListeners:()=>ks,init:()=>_s,listenerCount:()=>xs,on:()=>Ss,once:()=>Es});function uu(){if(Ii)return ar;Ii=!0;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(x,v,S){return Function.prototype.apply.call(x,v,S)},t;i&&typeof i.ownKeys=="function"?t=i.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)}ar=n,ar.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var s=10;function a(x){if(typeof x!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof x)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return s},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+".");s=x}}),n.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(x){if(typeof x!="number"||x<0||o(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function l(x){return x._maxListeners===void 0?n.defaultMaxListeners:x._maxListeners}n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(x){for(var v=[],S=1;S<arguments.length;S++)v.push(arguments[S]);var E=x==="error",I=this._events;if(I!==void 0)E=E&&I.error===void 0;else if(!E)return!1;if(E){var P;if(v.length>0&&(P=v[0]),P instanceof Error)throw P;var L=new Error("Unhandled error."+(P?" ("+P.message+")":""));throw L.context=P,L}var $=I[x];if($===void 0)return!1;if(typeof $=="function")e($,this,v);else for(var T=$.length,q=h($,T),S=0;S<T;++S)e(q[S],this,v);return!0};function c(x,v,S,E){var I,P,L;if(a(S),P=x._events,P===void 0?(P=x._events=Object.create(null),x._eventsCount=0):(P.newListener!==void 0&&(x.emit("newListener",v,S.listener?S.listener:S),P=x._events),L=P[v]),L===void 0)L=P[v]=S,++x._eventsCount;else if(typeof L=="function"?L=P[v]=E?[S,L]:[L,S]:E?L.unshift(S):L.push(S),I=l(x),I>0&&L.length>I&&!L.warned){L.warned=!0;var $=new Error("Possible EventEmitter memory leak detected. "+L.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");$.name="MaxListenersExceededWarning",$.emitter=x,$.type=v,$.count=L.length,r($)}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,S){var E={fired:!1,wrapFn:void 0,target:x,type:v,listener:S},I=u.bind(E);return I.listener=S,E.wrapFn=I,I}n.prototype.once=function(x,v){return a(v),this.on(x,d(this,x,v)),this},n.prototype.prependOnceListener=function(x,v){return a(v),this.prependListener(x,d(this,x,v)),this},n.prototype.removeListener=function(x,v){var S,E,I,P,L;if(a(v),E=this._events,E===void 0)return this;if(S=E[x],S===void 0)return this;if(S===v||S.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete E[x],E.removeListener&&this.emit("removeListener",x,S.listener||v));else if(typeof S!="function"){for(I=-1,P=S.length-1;P>=0;P--)if(S[P]===v||S[P].listener===v){L=S[P].listener,I=P;break}if(I<0)return this;I===0?S.shift():b(S,I),S.length===1&&(E[x]=S[0]),E.removeListener!==void 0&&this.emit("removeListener",x,L||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(x){var v,S,E;if(S=this._events,S===void 0)return this;if(S.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):S[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete S[x]),this;if(arguments.length===0){var I=Object.keys(S),P;for(E=0;E<I.length;++E)P=I[E],P!=="removeListener"&&this.removeAllListeners(P);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=S[x],typeof v=="function")this.removeListener(x,v);else if(v!==void 0)for(E=v.length-1;E>=0;E--)this.removeListener(x,v[E]);return this};function p(x,v,S){var E=x._events;if(E===void 0)return[];var I=E[v];return I===void 0?[]:typeof I=="function"?S?[I.listener||I]:[I]:S?y(I):h(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 S=v[x];if(typeof S=="function")return 1;if(S!==void 0)return S.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function h(x,v){for(var S=new Array(v),E=0;E<v;++E)S[E]=x[E];return S}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),S=0;S<v.length;++S)v[S]=x[S].listener||x[S];return v}function w(x,v){return new Promise(function(S,E){function I(L){x.removeListener(v,P),E(L)}function P(){typeof x.removeListener=="function"&&x.removeListener("error",I),S([].slice.call(arguments))}k(x,v,P,{once:!0}),v!=="error"&&m(x,I,{once:!0})})}function m(x,v,S){typeof x.on=="function"&&k(x,"error",v,S)}function k(x,v,S,E){if(typeof x.on=="function")E.once?x.once(v,S):x.on(v,S);else if(typeof x.addEventListener=="function")x.addEventListener(v,function I(P){E.once&&x.removeEventListener(v,I),S(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return ar}var ar,Ii,zt,ws,ks,_s,xs,Ss,Es,Rt=Qe(()=>{le(),ue(),ce(),ar={},Ii=!1,zt=uu(),zt.once,zt.once=function(i,e){return new Promise((t,r)=>{function o(...s){n!==void 0&&i.removeListener("error",n),t(s)}let n;e!=="error"&&(n=s=>{i.removeListener(name,o),r(s)},i.once("error",n)),i.once(e,o)})},zt.on=function(i,e){let t=[],r=[],o=null,n=!1,s={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(o){let u=Promise.reject(o);return o=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){i.removeListener(e,a),i.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){o=c,i.removeListener(e,a),i.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return i.on(e,a),i.on("error",l),s;function a(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function l(c){n=!0;let u=r.shift();u?u.reject(c):o=c,s.return()}},{EventEmitter:ws,defaultMaxListeners:ks,init:_s,listenerCount:xs,on:Ss,once:Es}=zt}),Xe=me((i,e)=>{le(),ue(),ce();var t=(He(),je(qe)),{format:r,inspect:o}=vs(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ye(),{kResistStopPropagation:s,AggregateError:a,SymbolDispose:l}=Be(),c=globalThis.AbortSignal||sr().AbortSignal,u=globalThis.AbortController||sr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,g=typeof p<"u"?function(y){return y instanceof p}:function(y){return!1},h=(y,w)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new n(w,"AbortSignal",y)},b=(y,w)=>{if(typeof y!="function")throw new n(w,"Function",y)};e.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(y){let w=!1;return function(...m){w||(w=!0,y.apply(this,m))}},createDeferredPromise:function(){let y,w;return{promise:new Promise((m,k)=>{y=m,w=k}),resolve:y,reject:w}},promisify(y){return new Promise((w,m)=>{y((k,...x)=>k?m(k):w(...x))})},debuglog(){return function(){}},format:r,inspect:o,types:{isAsyncFunction(y){return y instanceof d},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:g,deprecate(y,w){return y},addAbortListener:(Rt(),je(At)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);h(y,"signal"),b(w,"listener");let m;return y.aborted?queueMicrotask(()=>w()):(y.addEventListener("abort",w,{__proto__:null,once:!0,[s]:!0}),m=()=>{y.removeEventListener("abort",w)}),{__proto__:null,[l](){var k;(k=m)===null||k===void 0||k()}}},AbortSignalAny:c.any||function(y){if(y.length===1)return y[0];let w=new u,m=()=>w.abort();return y.forEach(k=>{h(k,"signals"),k.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{y.forEach(k=>k.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),lr=me((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:o,ArrayPrototypeMap:n,NumberIsInteger:s,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:g,StringPrototypeToUpperCase:h,StringPrototypeTrim:b}=Be(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:k,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ye(),{normalizeEncoding:S}=Xe(),{isAsyncFunction:E,isArrayBufferView:I}=Xe().types,P={};function L(z){return z===(z|0)}function $(z){return z===z>>>0}var T=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function F(z,ge,we){if(typeof z>"u"&&(z=we),typeof z=="string"){if(p(T,z)===null)throw new k(ge,z,q);z=u(z,8)}return j(z,ge),z}var D=y((z,ge,we=c,ae=l)=>{if(typeof z!="number")throw new m(ge,"number",z);if(!s(z))throw new x(ge,"an integer",z);if(z<we||z>ae)throw new x(ge,`>= ${we} && <= ${ae}`,z)}),oe=y((z,ge,we=-2147483648,ae=2147483647)=>{if(typeof z!="number")throw new m(ge,"number",z);if(!s(z))throw new x(ge,"an integer",z);if(z<we||z>ae)throw new x(ge,`>= ${we} && <= ${ae}`,z)}),j=y((z,ge,we=!1)=>{if(typeof z!="number")throw new m(ge,"number",z);if(!s(z))throw new x(ge,"an integer",z);let ae=we?1:0,Me=4294967295;if(z<ae||z>Me)throw new x(ge,`>= ${ae} && <= ${Me}`,z)});function W(z,ge){if(typeof z!="string")throw new m(ge,"string",z)}function re(z,ge,we=void 0,ae){if(typeof z!="number")throw new m(ge,"number",z);if(we!=null&&z<we||ae!=null&&z>ae||(we!=null||ae!=null)&&a(z))throw new x(ge,`${we!=null?`>= ${we}`:""}${we!=null&&ae!=null?" && ":""}${ae!=null?`<= ${ae}`:""}`,z)}var U=y((z,ge,we)=>{if(!r(we,z)){let ae="must be one of: "+o(n(we,Me=>typeof Me=="string"?`'${Me}'`:g(Me)),", ");throw new k(ge,z,ae)}});function Q(z,ge){if(typeof z!="boolean")throw new m(ge,"boolean",z)}function O(z,ge,we){return z==null||!d(z,ge)?we:z[ge]}var J=y((z,ge,we=null)=>{let ae=O(we,"allowArray",!1),Me=O(we,"allowFunction",!1);if(!O(we,"nullable",!1)&&z===null||!ae&&t(z)||typeof z!="object"&&(!Me||typeof z!="function"))throw new m(ge,"Object",z)}),pe=y((z,ge)=>{if(z!=null&&typeof z!="object"&&typeof z!="function")throw new m(ge,"a dictionary",z)}),ee=y((z,ge,we=0)=>{if(!t(z))throw new m(ge,"Array",z);if(z.length<we){let ae=`must be longer than ${we}`;throw new k(ge,z,ae)}});function ve(z,ge){ee(z,ge);for(let we=0;we<z.length;we++)W(z[we],`${ge}[${we}]`)}function G(z,ge){ee(z,ge);for(let we=0;we<z.length;we++)Q(z[we],`${ge}[${we}]`)}function R(z,ge){ee(z,ge);for(let we=0;we<z.length;we++){let ae=z[we],Me=`${ge}[${we}]`;if(ae==null)throw new m(Me,"AbortSignal",ae);be(ae,Me)}}function ne(z,ge="signal"){if(W(z,ge),P[z]===void 0)throw P[h(z)]!==void 0?new v(z+" (signals must use all capital letters)"):new v(z)}var V=y((z,ge="buffer")=>{if(!I(z))throw new m(ge,["Buffer","TypedArray","DataView"],z)});function Y(z,ge){let we=S(ge),ae=z.length;if(we==="hex"&&ae%2!==0)throw new k("encoding",ge,`is invalid for data of length ${ae}`)}function X(z,ge="Port",we=!0){if(typeof z!="number"&&typeof z!="string"||typeof z=="string"&&b(z).length===0||+z!==+z>>>0||z>65535||z===0&&!we)throw new w(ge,z,we);return z|0}var be=y((z,ge)=>{if(z!==void 0&&(z===null||typeof z!="object"||!("aborted"in z)))throw new m(ge,"AbortSignal",z)}),se=y((z,ge)=>{if(typeof z!="function")throw new m(ge,"Function",z)}),M=y((z,ge)=>{if(typeof z!="function"||E(z))throw new m(ge,"Function",z)}),H=y((z,ge)=>{if(z!==void 0)throw new m(ge,"undefined",z)});function te(z,ge,we){if(!r(we,z))throw new m(ge,`('${o(we,"|")}')`,z)}var he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(z,ge){if(typeof z>"u"||!p(he,z))throw new k(ge,z,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(z){if(typeof z=="string")return fe(z,"hints"),z;if(t(z)){let ge=z.length,we="";if(ge===0)return we;for(let ae=0;ae<ge;ae++){let Me=z[ae];fe(Me,"hints"),we+=Me,ae!==ge-1&&(we+=", ")}return we}throw new k("hints",z,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:L,isUint32:$,parseFileMode:F,validateArray:ee,validateStringArray:ve,validateBooleanArray:G,validateAbortSignalArray:R,validateBoolean:Q,validateBuffer:V,validateDictionary:pe,validateEncoding:Y,validateFunction:se,validateInt32:oe,validateInteger:D,validateNumber:re,validateObject:J,validateOneOf:U,validatePlainFunction:M,validatePort:X,validateSignalName:ne,validateString:W,validateUint32:j,validateUndefined:H,validateUnion:te,validateAbortSignal:be,validateLinkHeaderValue:ye}}),jt=me((i,e)=>{le(),ue(),ce();var t=e.exports={},r,o;function n(){throw new Error("setTimeout has not been defined")}function s(){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=s}catch{o=s}})();function a(w){if(r===setTimeout)return setTimeout(w,0);if((r===n||!r)&&setTimeout)return r=setTimeout,setTimeout(w,0);try{return r(w,0)}catch{try{return r.call(null,w,0)}catch{return r.call(this,w,0)}}}function l(w){if(o===clearTimeout)return clearTimeout(w);if((o===s||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(w);try{return o(w)}catch{try{return o.call(null,w)}catch{return o.call(this,w)}}}var c=[],u=!1,d,p=-1;function g(){!u||!d||(u=!1,d.length?c=d.concat(c):p=-1,c.length&&h())}function h(){if(!u){var w=a(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,l(w)}}t.nextTick=function(w){var m=new Array(arguments.length-1);if(arguments.length>1)for(var k=1;k<arguments.length;k++)m[k-1]=arguments[k];c.push(new b(w,m)),c.length===1&&!u&&a(h)};function b(w,m){this.fun=w,this.array=m}b.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function y(){}t.on=y,t.addListener=y,t.once=y,t.off=y,t.removeListener=y,t.removeAllListeners=y,t.emit=y,t.prependListener=y,t.prependOnceListener=y,t.listeners=function(w){return[]},t.binding=function(w){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(w){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),bt=me((i,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:o}=Be(),n=o("nodejs.stream.destroyed"),s=o("nodejs.stream.errored"),a=o("nodejs.stream.readable"),l=o("nodejs.stream.writable"),c=o("nodejs.stream.disturbed"),u=o("nodejs.webstream.isClosedPromise"),d=o("nodejs.webstream.controllerErrorFunction");function p(O,J=!1){var pe;return!!(O&&typeof O.pipe=="function"&&typeof O.on=="function"&&(!J||typeof O.pause=="function"&&typeof O.resume=="function")&&(!O._writableState||((pe=O._readableState)===null||pe===void 0?void 0:pe.readable)!==!1)&&(!O._writableState||O._readableState))}function g(O){var J;return!!(O&&typeof O.write=="function"&&typeof O.on=="function"&&(!O._readableState||((J=O._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function h(O){return!!(O&&typeof O.pipe=="function"&&O._readableState&&typeof O.on=="function"&&typeof O.write=="function")}function b(O){return O&&(O._readableState||O._writableState||typeof O.write=="function"&&typeof O.on=="function"||typeof O.pipe=="function"&&typeof O.on=="function")}function y(O){return!!(O&&!b(O)&&typeof O.pipeThrough=="function"&&typeof O.getReader=="function"&&typeof O.cancel=="function")}function w(O){return!!(O&&!b(O)&&typeof O.getWriter=="function"&&typeof O.abort=="function")}function m(O){return!!(O&&!b(O)&&typeof O.readable=="object"&&typeof O.writable=="object")}function k(O){return y(O)||w(O)||m(O)}function x(O,J){return O==null?!1:J===!0?typeof O[t]=="function":J===!1?typeof O[r]=="function":typeof O[t]=="function"||typeof O[r]=="function"}function v(O){if(!b(O))return null;let J=O._writableState,pe=O._readableState,ee=J||pe;return!!(O.destroyed||O[n]||ee!=null&&ee.destroyed)}function S(O){if(!g(O))return null;if(O.writableEnded===!0)return!0;let J=O._writableState;return J!=null&&J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function E(O,J){if(!g(O))return null;if(O.writableFinished===!0)return!0;let pe=O._writableState;return pe!=null&&pe.errored?!1:typeof pe?.finished!="boolean"?null:!!(pe.finished||J===!1&&pe.ended===!0&&pe.length===0)}function I(O){if(!p(O))return null;if(O.readableEnded===!0)return!0;let J=O._readableState;return!J||J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function P(O,J){if(!p(O))return null;let pe=O._readableState;return pe!=null&&pe.errored?!1:typeof pe?.endEmitted!="boolean"?null:!!(pe.endEmitted||J===!1&&pe.ended===!0&&pe.length===0)}function L(O){return O&&O[a]!=null?O[a]:typeof O?.readable!="boolean"?null:v(O)?!1:p(O)&&O.readable&&!P(O)}function $(O){return O&&O[l]!=null?O[l]:typeof O?.writable!="boolean"?null:v(O)?!1:g(O)&&O.writable&&!S(O)}function T(O,J){return b(O)?v(O)?!0:!(J?.readable!==!1&&L(O)||J?.writable!==!1&&$(O)):null}function q(O){var J,pe;return b(O)?O.writableErrored?O.writableErrored:(J=(pe=O._writableState)===null||pe===void 0?void 0:pe.errored)!==null&&J!==void 0?J:null:null}function F(O){var J,pe;return b(O)?O.readableErrored?O.readableErrored:(J=(pe=O._readableState)===null||pe===void 0?void 0:pe.errored)!==null&&J!==void 0?J:null:null}function D(O){if(!b(O))return null;if(typeof O.closed=="boolean")return O.closed;let J=O._writableState,pe=O._readableState;return typeof J?.closed=="boolean"||typeof pe?.closed=="boolean"?J?.closed||pe?.closed:typeof O._closed=="boolean"&&oe(O)?O._closed:null}function oe(O){return typeof O._closed=="boolean"&&typeof O._defaultKeepAlive=="boolean"&&typeof O._removedConnection=="boolean"&&typeof O._removedContLen=="boolean"}function j(O){return typeof O._sent100=="boolean"&&oe(O)}function W(O){var J;return typeof O._consuming=="boolean"&&typeof O._dumped=="boolean"&&((J=O.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function re(O){if(!b(O))return null;let J=O._writableState,pe=O._readableState,ee=J||pe;return!ee&&j(O)||!!(ee&&ee.autoDestroy&&ee.emitClose&&ee.closed===!1)}function U(O){var J;return!!(O&&((J=O[c])!==null&&J!==void 0?J:O.readableDidRead||O.readableAborted))}function Q(O){var J,pe,ee,ve,G,R,ne,V,Y,X;return!!(O&&((J=(pe=(ee=(ve=(G=(R=O[s])!==null&&R!==void 0?R:O.readableErrored)!==null&&G!==void 0?G:O.writableErrored)!==null&&ve!==void 0?ve:(ne=O._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&ee!==void 0?ee:(V=O._writableState)===null||V===void 0?void 0:V.errorEmitted)!==null&&pe!==void 0?pe:(Y=O._readableState)===null||Y===void 0?void 0:Y.errored)!==null&&J!==void 0?J:!((X=O._writableState)===null||X===void 0)&&X.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:U,kIsDisturbed:c,isErrored:Q,kIsErrored:s,isReadable:L,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:D,isDuplexNodeStream:h,isFinished:T,isIterable:x,isReadableNodeStream:p,isReadableStream:y,isReadableEnded:I,isReadableFinished:P,isReadableErrored:F,isNodeStream:b,isWebStream:k,isWritable:$,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:S,isWritableFinished:E,isWritableErrored:q,isServerRequest:W,isServerResponse:j,willEmitClose:re,isTransformStream:m}}),It=me((i,e)=>{le(),ue(),ce();var t=jt(),{AbortError:r,codes:o}=Ye(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:s}=o,{kEmptyObject:a,once:l}=Xe(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:p}=lr(),{Promise:g,PromisePrototypeThen:h,SymbolDispose:b}=Be(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:k,isReadableFinished:x,isReadableErrored:v,isWritable:S,isWritableNodeStream:E,isWritableStream:I,isWritableFinished:P,isWritableErrored:L,isNodeStream:$,willEmitClose:T,kIsClosedPromise:q}=bt(),F;function D(U){return U.setHeader&&typeof U.abort=="function"}var oe=()=>{};function j(U,Q,O){var J,pe;if(arguments.length===2?(O=Q,Q=a):Q==null?Q=a:d(Q,"options"),u(O,"callback"),c(Q.signal,"options.signal"),O=l(O),k(U)||I(U))return W(U,Q,O);if(!$(U))throw new n("stream",["ReadableStream","WritableStream","Stream"],U);let ee=(J=Q.readable)!==null&&J!==void 0?J:m(U),ve=(pe=Q.writable)!==null&&pe!==void 0?pe:E(U),G=U._writableState,R=U._readableState,ne=()=>{U.writable||X()},V=T(U)&&m(U)===ee&&E(U)===ve,Y=P(U,!1),X=()=>{Y=!0,U.destroyed&&(V=!1),!(V&&(!U.readable||ee))&&(!ee||be)&&O.call(U)},be=x(U,!1),se=()=>{be=!0,U.destroyed&&(V=!1),!(V&&(!U.writable||ve))&&(!ve||Y)&&O.call(U)},M=z=>{O.call(U,z)},H=y(U),te=()=>{H=!0;let z=L(U)||v(U);if(z&&typeof z!="boolean")return O.call(U,z);if(ee&&!be&&m(U,!0)&&!x(U,!1))return O.call(U,new s);if(ve&&!Y&&!P(U,!1))return O.call(U,new s);O.call(U)},he=()=>{H=!0;let z=L(U)||v(U);if(z&&typeof z!="boolean")return O.call(U,z);O.call(U)},fe=()=>{U.req.on("finish",X)};D(U)?(U.on("complete",X),V||U.on("abort",te),U.req?fe():U.on("request",fe)):ve&&!G&&(U.on("end",ne),U.on("close",ne)),!V&&typeof U.aborted=="boolean"&&U.on("aborted",te),U.on("end",se),U.on("finish",X),Q.error!==!1&&U.on("error",M),U.on("close",te),H?t.nextTick(te):G!=null&&G.errorEmitted||R!=null&&R.errorEmitted?V||t.nextTick(he):(!ee&&(!V||w(U))&&(Y||S(U)===!1)||!ve&&(!V||S(U))&&(be||w(U)===!1)||R&&U.req&&U.aborted)&&t.nextTick(he);let ye=()=>{O=oe,U.removeListener("aborted",te),U.removeListener("complete",X),U.removeListener("abort",te),U.removeListener("request",fe),U.req&&U.req.removeListener("finish",X),U.removeListener("end",ne),U.removeListener("close",ne),U.removeListener("finish",X),U.removeListener("end",se),U.removeListener("error",M),U.removeListener("close",te)};if(Q.signal&&!H){let z=()=>{let ge=O;ye(),ge.call(U,new r(void 0,{cause:Q.signal.reason}))};if(Q.signal.aborted)t.nextTick(z);else{F=F||Xe().addAbortListener;let ge=F(Q.signal,z),we=O;O=l((...ae)=>{ge[b](),we.apply(U,ae)})}}return ye}function W(U,Q,O){let J=!1,pe=oe;if(Q.signal)if(pe=()=>{J=!0,O.call(U,new r(void 0,{cause:Q.signal.reason}))},Q.signal.aborted)t.nextTick(pe);else{F=F||Xe().addAbortListener;let ve=F(Q.signal,pe),G=O;O=l((...R)=>{ve[b](),G.apply(U,R)})}let ee=(...ve)=>{J||t.nextTick(()=>O.apply(U,ve))};return h(U[q].promise,ee,ee),oe}function re(U,Q){var O;let J=!1;return Q===null&&(Q=a),(O=Q)!==null&&O!==void 0&&O.cleanup&&(p(Q.cleanup,"cleanup"),J=Q.cleanup),new g((pe,ee)=>{let ve=j(U,Q,G=>{J&&ve(),G?ee(G):pe()})})}e.exports=j,e.exports.finished=re}),Vt=me((i,e)=>{le(),ue(),ce();var t=jt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:n}=Ye(),{Symbol:s}=Be(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=bt(),d=s("kDestroy"),p=s("kConstruct");function g(T,q,F){T&&(T.stack,q&&!q.errored&&(q.errored=T),F&&!F.errored&&(F.errored=T))}function h(T,q){let F=this._readableState,D=this._writableState,oe=D||F;return D!=null&&D.destroyed||F!=null&&F.destroyed?(typeof q=="function"&&q(),this):(g(T,D,F),D&&(D.destroyed=!0),F&&(F.destroyed=!0),oe.constructed?b(this,T,q):this.once(d,function(j){b(this,r(j,T),q)}),this)}function b(T,q,F){let D=!1;function oe(j){if(D)return;D=!0;let W=T._readableState,re=T._writableState;g(j,re,W),re&&(re.closed=!0),W&&(W.closed=!0),typeof F=="function"&&F(j),j?t.nextTick(y,T,j):t.nextTick(w,T)}try{T._destroy(q||null,oe)}catch(j){oe(j)}}function y(T,q){m(T,q),w(T)}function w(T){let q=T._readableState,F=T._writableState;F&&(F.closeEmitted=!0),q&&(q.closeEmitted=!0),(F!=null&&F.emitClose||q!=null&&q.emitClose)&&T.emit("close")}function m(T,q){let F=T._readableState,D=T._writableState;D!=null&&D.errorEmitted||F!=null&&F.errorEmitted||(D&&(D.errorEmitted=!0),F&&(F.errorEmitted=!0),T.emit("error",q))}function k(){let T=this._readableState,q=this._writableState;T&&(T.constructed=!0,T.closed=!1,T.closeEmitted=!1,T.destroyed=!1,T.errored=null,T.errorEmitted=!1,T.reading=!1,T.ended=T.readable===!1,T.endEmitted=T.readable===!1),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function x(T,q,F){let D=T._readableState,oe=T._writableState;if(oe!=null&&oe.destroyed||D!=null&&D.destroyed)return this;D!=null&&D.autoDestroy||oe!=null&&oe.autoDestroy?T.destroy(q):q&&(q.stack,oe&&!oe.errored&&(oe.errored=q),D&&!D.errored&&(D.errored=q),F?t.nextTick(m,T,q):m(T,q))}function v(T,q){if(typeof T._construct!="function")return;let F=T._readableState,D=T._writableState;F&&(F.constructed=!1),D&&(D.constructed=!1),T.once(p,q),!(T.listenerCount(p)>1)&&t.nextTick(S,T)}function S(T){let q=!1;function F(D){if(q){x(T,D??new o);return}q=!0;let oe=T._readableState,j=T._writableState,W=j||oe;oe&&(oe.constructed=!0),j&&(j.constructed=!0),W.destroyed?T.emit(d,D):D?x(T,D,!0):t.nextTick(E,T)}try{T._construct(D=>{t.nextTick(F,D)})}catch(D){t.nextTick(F,D)}}function E(T){T.emit(p)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function P(T){T.emit("close")}function L(T,q){T.emit("error",q),t.nextTick(P,T)}function $(T,q){!T||l(T)||(!q&&!c(T)&&(q=new n),u(T)?(T.socket=null,T.destroy(q)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(q):typeof T.close=="function"?T.close():q?t.nextTick(L,T,q):t.nextTick(P,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:$,destroy:h,undestroy:k,errorOrDestroy:x}}),Ti=me((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Be(),{EventEmitter:o}=(Rt(),je(At));function n(a){o.call(this,a)}r(n.prototype,o.prototype),r(n,o),n.prototype.pipe=function(a,l){let c=this;function u(w){a.writable&&a.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function d(){c.readable&&c.resume&&c.resume()}a.on("drain",d),!a._isStdio&&(!l||l.end!==!1)&&(c.on("end",g),c.on("close",h));let p=!1;function g(){p||(p=!0,a.end())}function h(){p||(p=!0,typeof a.destroy=="function"&&a.destroy())}function b(w){y(),o.listenerCount(this,"error")===0&&this.emit("error",w)}s(c,"error",b),s(a,"error",b);function y(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",g),c.removeListener("close",h),c.removeListener("error",b),a.removeListener("error",b),c.removeListener("end",y),c.removeListener("close",y),a.removeListener("close",y)}return c.on("end",y),c.on("close",y),a.on("close",y),a.emit("pipe",c),a};function s(a,l,c){if(typeof a.prependListener=="function")return a.prependListener(l,c);!a._events||!a._events[l]?a.on(l,c):t(a._events[l])?a._events[l].unshift(c):a._events[l]=[c,a._events[l]]}e.exports={Stream:n,prependListener:s}}),Ir=me((i,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Be(),{AbortError:r,codes:o}=Ye(),{isNodeStream:n,isWebStream:s,kControllerErrorFunction:a}=bt(),l=It(),{ERR_INVALID_ARG_TYPE:c}=o,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)&&!s(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 h=n(g)?()=>{g.destroy(new r(void 0,{cause:p.reason}))}:()=>{g[a](new r(void 0,{cause:p.reason}))};if(p.aborted)h();else{u=u||Xe().addAbortListener;let b=u(p,h);l(g,b[t])}return g}}),du=me((i,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:o,Uint8Array:n}=Be(),{Buffer:s}=(He(),je(qe)),{inspect:a}=Xe();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(l){let c={data:l,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(l){let c={data:l,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let l=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,l}clear(){this.head=this.tail=null,this.length=0}join(l){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=l+c.data;return u}concat(l){if(this.length===0)return s.alloc(0);let c=s.allocUnsafe(l>>>0),u=this.head,d=0;for(;u;)o(c,u.data,d),d+=u.data.length,u=u.next;return c}consume(l,c){let u=this.head.data;if(l<u.length){let d=u.slice(0,l);return this.head.data=u.slice(l),d}return l===u.length?this.shift():c?this._getString(l):this._getBuffer(l)}first(){return this.head.data}*[r](){for(let l=this.head;l;l=l.next)yield l.data}_getString(l){let c="",u=this.head,d=0;do{let p=u.data;if(l>p.length)c+=p,l-=p.length;else{l===p.length?(c+=p,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,l),this.head=u,u.data=t(p,l));break}++d}while((u=u.next)!==null);return this.length-=d,c}_getBuffer(l){let c=s.allocUnsafe(l),u=l,d=this.head,p=0;do{let g=d.data;if(l>g.length)o(c,g,u-l),l-=g.length;else{l===g.length?(o(c,g,u-l),++p,d.next?this.head=d.next:this.head=this.tail=null):(o(c,new n(g.buffer,g.byteOffset,l),u-l),this.head=d,d.data=g.slice(l));break}++p}while((d=d.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),Tr=me((i,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Be(),{validateInteger:o}=lr(),{ERR_INVALID_ARG_VALUE:n}=Ye().codes,s=16*1024,a=16;function l(p,g,h){return p.highWaterMark!=null?p.highWaterMark:g?p[h]:null}function c(p){return p?a:s}function u(p,g){o(g,"value",0),p?a=g:s=g}function d(p,g,h,b){let y=l(g,b,h);if(y!=null){if(!r(y)||y<0){let w=b?`options.${h}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),hu=me((i,e)=>{le(),ue(),ce();var t=(He(),je(qe)),r=t.Buffer;function o(s,a){for(var l in s)a[l]=s[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(o(t,i),i.Buffer=n);function n(s,a,l){return r(s,a,l)}n.prototype=Object.create(r.prototype),o(r,n),n.from=function(s,a,l){if(typeof s=="number")throw new TypeError("Argument must not be a number");return r(s,a,l)},n.alloc=function(s,a,l){if(typeof s!="number")throw new TypeError("Argument must be a number");var c=r(s);return a!==void 0?typeof l=="string"?c.fill(a,l):c.fill(a):c.fill(0),c},n.allocUnsafe=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return r(s)},n.allocUnsafeSlow=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(s)}}),pu=me(i=>{le(),ue(),ce();var e=hu().Buffer,t=e.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(m){if(!m)return"utf8";for(var k;;)switch(m){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return m;default:if(k)return;m=(""+m).toLowerCase(),k=!0}}function o(m){var k=r(m);if(typeof k!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return k||m}i.StringDecoder=n;function n(m){this.encoding=o(m);var k;switch(this.encoding){case"utf16le":this.text=p,this.end=g,k=4;break;case"utf8":this.fillLast=c,k=4;break;case"base64":this.text=h,this.end=b,k=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(k)}n.prototype.write=function(m){if(m.length===0)return"";var k,x;if(this.lastNeed){if(k=this.fillLast(m),k===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?k?k+this.text(m,x):this.text(m,x):k||""},n.prototype.end=d,n.prototype.text=u,n.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length};function s(m){return m<=127?0:m>>5===6?2:m>>4===14?3:m>>3===30?4:m>>6===2?-1:-2}function a(m,k,x){var v=k.length-1;if(v<x)return 0;var S=s(k[v]);return S>=0?(S>0&&(m.lastNeed=S-1),S):--v<x||S===-2?0:(S=s(k[v]),S>=0?(S>0&&(m.lastNeed=S-2),S):--v<x||S===-2?0:(S=s(k[v]),S>=0?(S>0&&(S===2?S=0:m.lastNeed=S-3),S):0))}function l(m,k,x){if((k[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&k.length>1){if((k[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&k.length>2&&(k[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var k=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,k,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,k,0,m.length),this.lastNeed-=m.length}function u(m,k){var x=a(this,m,k);if(!this.lastNeed)return m.toString("utf8",k);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",k,v)}function d(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+"�":k}function p(m,k){if((m.length-k)%2===0){var x=m.toString("utf16le",k);if(x){var v=x.charCodeAt(x.length-1);if(v>=55296&&v<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1],x.slice(0,-1)}return x}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",k,m.length-1)}function g(m){var k=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,x)}return k}function h(m,k){var x=(m.length-k)%3;return x===0?m.toString("base64",k):(this.lastNeed=3-x,this.lastTotal=3,x===1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",k,m.length-x))}function b(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+this.lastChar.toString("base64",0,3-this.lastNeed):k}function y(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),As=me((i,e)=>{le(),ue(),ce();var t=jt(),{PromisePrototypeThen:r,SymbolAsyncIterator:o,SymbolIterator:n}=Be(),{Buffer:s}=(He(),je(qe)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ye().codes;function c(u,d,p){let g;if(typeof d=="string"||d instanceof s)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let h;if(d&&d[o])h=!0,g=d[o]();else if(d&&d[n])h=!1,g=d[n]();else throw new a("iterable",["Iterable"],d);let b=new u({objectMode:!0,highWaterMark:1,...p}),y=!1;b._read=function(){y||(y=!0,m())},b._destroy=function(k,x){r(w(k),()=>t.nextTick(x,k),v=>t.nextTick(x,v||k))};async function w(k){let x=k!=null,v=typeof g.throw=="function";if(x&&v){let{value:S,done:E}=await g.throw(k);if(await S,E)return}if(typeof g.return=="function"){let{value:S}=await g.return();await S}}async function m(){for(;;){try{let{value:k,done:x}=h?await g.next():g.next();if(x)b.push(null);else{let v=k&&typeof k.then=="function"?await k:k;if(v===null)throw y=!1,new l;if(b.push(v))continue;y=!1}}catch(k){b.destroy(k)}break}}return b}e.exports=c}),Cr=me((i,e)=>{le(),ue(),ce();var t=jt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:o,NumberIsNaN:n,NumberParseInt:s,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:g,Symbol:h}=Be();e.exports=ae,ae.ReadableState=we;var{EventEmitter:b}=(Rt(),je(At)),{Stream:y,prependListener:w}=Ti(),{Buffer:m}=(He(),je(qe)),{addAbortSignal:k}=Ir(),x=It(),v=Xe().debuglog("stream",C=>{v=C}),S=du(),E=Vt(),{getHighWaterMark:I,getDefaultHighWaterMark:P}=Tr(),{aggregateTwoErrors:L,codes:{ERR_INVALID_ARG_TYPE:$,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:q,ERR_STREAM_PUSH_AFTER_EOF:F,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:D},AbortError:oe}=Ye(),{validateObject:j}=lr(),W=h("kPaused"),{StringDecoder:re}=pu(),U=As();c(ae.prototype,y.prototype),c(ae,y);var Q=()=>{},{errorOrDestroy:O}=E,J=1,pe=2,ee=4,ve=8,G=16,R=32,ne=64,V=128,Y=256,X=512,be=1024,se=2048,M=4096,H=8192,te=16384,he=32768,fe=65536,ye=1<<17,z=1<<18;function ge(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(N){N?this.state|=C:this.state&=~C}}}a(we.prototype,{objectMode:ge(J),ended:ge(pe),endEmitted:ge(ee),reading:ge(ve),constructed:ge(G),sync:ge(R),needReadable:ge(ne),emittedReadable:ge(V),readableListening:ge(Y),resumeScheduled:ge(X),errorEmitted:ge(be),emitClose:ge(se),autoDestroy:ge(M),destroyed:ge(H),closed:ge(te),closeEmitted:ge(he),multiAwaitDrain:ge(fe),readingMore:ge(ye),dataEmitted:ge(z)});function we(C,N,ke){typeof ke!="boolean"&&(ke=N instanceof yt()),this.state=se|M|G|R,C&&C.objectMode&&(this.state|=J),ke&&C&&C.readableObjectMode&&(this.state|=J),this.highWaterMark=C?I(this,C,"readableHighWaterMark",ke):P(!1),this.buffer=new S,this.length=0,this.pipes=[],this.flowing=null,this[W]=null,C&&C.emitClose===!1&&(this.state&=~se),C&&C.autoDestroy===!1&&(this.state&=~M),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 ae(C){if(!(this instanceof ae))return new ae(C);let N=this instanceof yt();this._readableState=new we(C,this,N),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&&!N&&k(C.signal,this)),y.call(this,C),E.construct(this,()=>{this._readableState.needReadable&&K(this,this._readableState)})}ae.prototype.destroy=E.destroy,ae.prototype._undestroy=E.undestroy,ae.prototype._destroy=function(C,N){N(C)},ae.prototype[b.captureRejectionSymbol]=function(C){this.destroy(C)},ae.prototype[p]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new oe,this.destroy(C)),new u((N,ke)=>x(this,Se=>Se&&Se!==C?ke(Se):N(null)))},ae.prototype.push=function(C,N){return Me(this,C,N,!1)},ae.prototype.unshift=function(C,N){return Me(this,C,N,!0)};function Me(C,N,ke,Se){v("readableAddChunk",N);let Ae=C._readableState,Fe;if((Ae.state&J)===0&&(typeof N=="string"?(ke=ke||Ae.defaultEncoding,Ae.encoding!==ke&&(Se&&Ae.encoding?N=m.from(N,ke).toString(Ae.encoding):(N=m.from(N,ke),ke=""))):N instanceof m?ke="":y._isUint8Array(N)?(N=y._uint8ArrayToBuffer(N),ke=""):N!=null&&(Fe=new $("chunk",["string","Buffer","Uint8Array"],N))),Fe)O(C,Fe);else if(N===null)Ae.state&=~ve,Z(C,Ae);else if((Ae.state&J)!==0||N&&N.length>0)if(Se)if((Ae.state&ee)!==0)O(C,new D);else{if(Ae.destroyed||Ae.errored)return!1;f(C,Ae,N,!0)}else if(Ae.ended)O(C,new F);else{if(Ae.destroyed||Ae.errored)return!1;Ae.state&=~ve,Ae.decoder&&!ke?(N=Ae.decoder.write(N),Ae.objectMode||N.length!==0?f(C,Ae,N,!1):K(C,Ae)):f(C,Ae,N,!1)}else Se||(Ae.state&=~ve,K(C,Ae));return!Ae.ended&&(Ae.length<Ae.highWaterMark||Ae.length===0)}function f(C,N,ke,Se){N.flowing&&N.length===0&&!N.sync&&C.listenerCount("data")>0?((N.state&fe)!==0?N.awaitDrainWriters.clear():N.awaitDrainWriters=null,N.dataEmitted=!0,C.emit("data",ke)):(N.length+=N.objectMode?1:ke.length,Se?N.buffer.unshift(ke):N.buffer.push(ke),(N.state&ne)!==0&&de(C)),K(C,N)}ae.prototype.isPaused=function(){let C=this._readableState;return C[W]===!0||C.flowing===!1},ae.prototype.setEncoding=function(C){let N=new re(C);this._readableState.decoder=N,this._readableState.encoding=this._readableState.decoder.encoding;let ke=this._readableState.buffer,Se="";for(let Ae of ke)Se+=N.write(Ae);return ke.clear(),Se!==""&&ke.push(Se),this._readableState.length=Se.length,this};var _=1073741824;function A(C){if(C>_)throw new q("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function B(C,N){return C<=0||N.length===0&&N.ended?0:(N.state&J)!==0?1:n(C)?N.flowing&&N.length?N.buffer.first().length:N.length:C<=N.length?C:N.ended?N.length:0}ae.prototype.read=function(C){v("read",C),C===void 0?C=NaN:o(C)||(C=s(C,10));let N=this._readableState,ke=C;if(C>N.highWaterMark&&(N.highWaterMark=A(C)),C!==0&&(N.state&=~V),C===0&&N.needReadable&&((N.highWaterMark!==0?N.length>=N.highWaterMark:N.length>0)||N.ended))return v("read: emitReadable",N.length,N.ended),N.length===0&&N.ended?dt(this):de(this),null;if(C=B(C,N),C===0&&N.ended)return N.length===0&&dt(this),null;let Se=(N.state&ne)!==0;if(v("need readable",Se),(N.length===0||N.length-C<N.highWaterMark)&&(Se=!0,v("length less than watermark",Se)),N.ended||N.reading||N.destroyed||N.errored||!N.constructed)Se=!1,v("reading, ended or constructing",Se);else if(Se){v("do read"),N.state|=ve|R,N.length===0&&(N.state|=ne);try{this._read(N.highWaterMark)}catch(Fe){O(this,Fe)}N.state&=~R,N.reading||(C=B(ke,N))}let Ae;return C>0?Ae=tr(C,N):Ae=null,Ae===null?(N.needReadable=N.length<=N.highWaterMark,C=0):(N.length-=C,N.multiAwaitDrain?N.awaitDrainWriters.clear():N.awaitDrainWriters=null),N.length===0&&(N.ended||(N.needReadable=!0),ke!==C&&N.ended&&dt(this)),Ae!==null&&!N.errorEmitted&&!N.closeEmitted&&(N.dataEmitted=!0,this.emit("data",Ae)),Ae};function Z(C,N){if(v("onEofChunk"),!N.ended){if(N.decoder){let ke=N.decoder.end();ke&&ke.length&&(N.buffer.push(ke),N.length+=N.objectMode?1:ke.length)}N.ended=!0,N.sync?de(C):(N.needReadable=!1,N.emittedReadable=!0,_e(C))}}function de(C){let N=C._readableState;v("emitReadable",N.needReadable,N.emittedReadable),N.needReadable=!1,N.emittedReadable||(v("emitReadable",N.flowing),N.emittedReadable=!0,t.nextTick(_e,C))}function _e(C){let N=C._readableState;v("emitReadable_",N.destroyed,N.length,N.ended),!N.destroyed&&!N.errored&&(N.length||N.ended)&&(C.emit("readable"),N.emittedReadable=!1),N.needReadable=!N.flowing&&!N.ended&&N.length<=N.highWaterMark,ct(C)}function K(C,N){!N.readingMore&&N.constructed&&(N.readingMore=!0,t.nextTick(ie,C,N))}function ie(C,N){for(;!N.reading&&!N.ended&&(N.length<N.highWaterMark||N.flowing&&N.length===0);){let ke=N.length;if(v("maybeReadMore read 0"),C.read(0),ke===N.length)break}N.readingMore=!1}ae.prototype._read=function(C){throw new T("_read()")},ae.prototype.pipe=function(C,N){let ke=this,Se=this._readableState;Se.pipes.length===1&&(Se.multiAwaitDrain||(Se.multiAwaitDrain=!0,Se.awaitDrainWriters=new d(Se.awaitDrainWriters?[Se.awaitDrainWriters]:[]))),Se.pipes.push(C),v("pipe count=%d opts=%j",Se.pipes.length,N);let Ae=(!N||N.end!==!1)&&C!==t.stdout&&C!==t.stderr?Je:qt;Se.endEmitted?t.nextTick(Ae):ke.once("end",Ae),C.on("unpipe",Fe);function Fe(pt,St){v("onunpipe"),pt===ke&&St&&St.hasUnpiped===!1&&(St.hasUnpiped=!0,vr())}function Je(){v("onend"),C.end()}let it,yr=!1;function vr(){v("cleanup"),C.removeListener("close",ht),C.removeListener("finish",Lt),it&&C.removeListener("drain",it),C.removeListener("error",Ft),C.removeListener("unpipe",Fe),ke.removeListener("end",Je),ke.removeListener("end",qt),ke.removeListener("data",pn),yr=!0,it&&Se.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&it()}function wr(){yr||(Se.pipes.length===1&&Se.pipes[0]===C?(v("false write response, pause",0),Se.awaitDrainWriters=C,Se.multiAwaitDrain=!1):Se.pipes.length>1&&Se.pipes.includes(C)&&(v("false write response, pause",Se.awaitDrainWriters.size),Se.awaitDrainWriters.add(C)),ke.pause()),it||(it=Te(ke,C),C.on("drain",it))}ke.on("data",pn);function pn(pt){v("ondata");let St=C.write(pt);v("dest.write",St),St===!1&&wr()}function Ft(pt){if(v("onerror",pt),qt(),C.removeListener("error",Ft),C.listenerCount("error")===0){let St=C._writableState||C._readableState;St&&!St.errorEmitted?O(C,pt):C.emit("error",pt)}}w(C,"error",Ft);function ht(){C.removeListener("finish",Lt),qt()}C.once("close",ht);function Lt(){v("onfinish"),C.removeListener("close",ht),qt()}C.once("finish",Lt);function qt(){v("unpipe"),ke.unpipe(C)}return C.emit("pipe",ke),C.writableNeedDrain===!0?wr():Se.flowing||(v("pipe resume"),ke.resume()),C};function Te(C,N){return function(){let ke=C._readableState;ke.awaitDrainWriters===N?(v("pipeOnDrain",1),ke.awaitDrainWriters=null):ke.multiAwaitDrain&&(v("pipeOnDrain",ke.awaitDrainWriters.size),ke.awaitDrainWriters.delete(N)),(!ke.awaitDrainWriters||ke.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}ae.prototype.unpipe=function(C){let N=this._readableState,ke={hasUnpiped:!1};if(N.pipes.length===0)return this;if(!C){let Ae=N.pipes;N.pipes=[],this.pause();for(let Fe=0;Fe<Ae.length;Fe++)Ae[Fe].emit("unpipe",this,{hasUnpiped:!1});return this}let Se=r(N.pipes,C);return Se===-1?this:(N.pipes.splice(Se,1),N.pipes.length===0&&this.pause(),C.emit("unpipe",this,ke),this)},ae.prototype.on=function(C,N){let ke=y.prototype.on.call(this,C,N),Se=this._readableState;return C==="data"?(Se.readableListening=this.listenerCount("readable")>0,Se.flowing!==!1&&this.resume()):C==="readable"&&!Se.endEmitted&&!Se.readableListening&&(Se.readableListening=Se.needReadable=!0,Se.flowing=!1,Se.emittedReadable=!1,v("on readable",Se.length,Se.reading),Se.length?de(this):Se.reading||t.nextTick(Le,this)),ke},ae.prototype.addListener=ae.prototype.on,ae.prototype.removeListener=function(C,N){let ke=y.prototype.removeListener.call(this,C,N);return C==="readable"&&t.nextTick(Ce,this),ke},ae.prototype.off=ae.prototype.removeListener,ae.prototype.removeAllListeners=function(C){let N=y.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Ce,this),N};function Ce(C){let N=C._readableState;N.readableListening=C.listenerCount("readable")>0,N.resumeScheduled&&N[W]===!1?N.flowing=!0:C.listenerCount("data")>0?C.resume():N.readableListening||(N.flowing=null)}function Le(C){v("readable nexttick read 0"),C.read(0)}ae.prototype.resume=function(){let C=this._readableState;return C.flowing||(v("resume"),C.flowing=!C.readableListening,Re(this,C)),C[W]=!1,this};function Re(C,N){N.resumeScheduled||(N.resumeScheduled=!0,t.nextTick(lt,C,N))}function lt(C,N){v("resume",N.reading),N.reading||C.read(0),N.resumeScheduled=!1,C.emit("resume"),ct(C),N.flowing&&!N.reading&&C.read(0)}ae.prototype.pause=function(){return v("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(v("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[W]=!0,this};function ct(C){let N=C._readableState;for(v("flow",N.flowing);N.flowing&&C.read()!==null;);}ae.prototype.wrap=function(C){let N=!1;C.on("data",Se=>{!this.push(Se)&&C.pause&&(N=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",Se=>{O(this,Se)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{N&&C.resume&&(N=!1,C.resume())};let ke=l(C);for(let Se=1;Se<ke.length;Se++){let Ae=ke[Se];this[Ae]===void 0&&typeof C[Ae]=="function"&&(this[Ae]=C[Ae].bind(C))}return this},ae.prototype[g]=function(){return Ge(this)},ae.prototype.iterator=function(C){return C!==void 0&&j(C,"options"),Ge(this,C)};function Ge(C,N){typeof C.read!="function"&&(C=ae.wrap(C,{objectMode:!0}));let ke=ut(C,N);return ke.stream=C,ke}async function*ut(C,N){let ke=Q;function Se(Je){this===C?(ke(),ke=Q):ke=Je}C.on("readable",Se);let Ae,Fe=x(C,{writable:!1},Je=>{Ae=Je?L(Ae,Je):null,ke(),ke=Q});try{for(;;){let Je=C.destroyed?null:C.read();if(Je!==null)yield Je;else{if(Ae)throw Ae;if(Ae===null)return;await new u(Se)}}}catch(Je){throw Ae=L(Ae,Je),Ae}finally{(Ae||N?.destroyOnReturn!==!1)&&(Ae===void 0||C._readableState.autoDestroy)?E.destroyer(C,null):(C.off("readable",Se),Fe())}}a(ae.prototype,{readable:{__proto__:null,get(){let C=this._readableState;return!!C&&C.readable!==!1&&!C.destroyed&&!C.errorEmitted&&!C.endEmitted},set(C){this._readableState&&(this._readableState.readable=!!C)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(C){this._readableState&&(this._readableState.flowing=C)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(C){this._readableState&&(this._readableState.destroyed=C)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),a(we.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[W]!==!1},set(C){this[W]=!!C}}}),ae._fromList=tr;function tr(C,N){if(N.length===0)return null;let ke;return N.objectMode?ke=N.buffer.shift():!C||C>=N.length?(N.decoder?ke=N.buffer.join(""):N.buffer.length===1?ke=N.buffer.first():ke=N.buffer.concat(N.length),N.buffer.clear()):ke=N.buffer.consume(C,N.decoder),ke}function dt(C){let N=C._readableState;v("endReadable",N.endEmitted),N.endEmitted||(N.ended=!0,t.nextTick(et,N,C))}function et(C,N){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,N.emit("end"),N.writable&&N.allowHalfOpen===!1)t.nextTick(hn,N);else if(C.autoDestroy){let ke=N._writableState;(!ke||ke.autoDestroy&&(ke.finished||ke.writable===!1))&&N.destroy()}}}function hn(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}ae.from=function(C,N){return U(ae,C,N)};var rr;function br(){return rr===void 0&&(rr={}),rr}ae.fromWeb=function(C,N){return br().newStreamReadableFromReadableStream(C,N)},ae.toWeb=function(C,N){return br().newReadableStreamFromStreamReadable(C,N)},ae.wrap=function(C,N){var ke,Se;return new ae({objectMode:(ke=(Se=C.readableObjectMode)!==null&&Se!==void 0?Se:C.objectMode)!==null&&ke!==void 0?ke:!0,...N,destroy(Ae,Fe){E.destroyer(C,Ae),Fe(Ae)}}).wrap(C)}}),Ci=me((i,e)=>{le(),ue(),ce();var t=jt(),{ArrayPrototypeSlice:r,Error:o,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:s,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=Be();e.exports=j,j.WritableState=D;var{EventEmitter:p}=(Rt(),je(At)),g=Ti().Stream,{Buffer:h}=(He(),je(qe)),b=Vt(),{addAbortSignal:y}=Ir(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=Tr(),{ERR_INVALID_ARG_TYPE:k,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:S,ERR_STREAM_DESTROYED:E,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:P,ERR_STREAM_WRITE_AFTER_END:L,ERR_UNKNOWN_ENCODING:$}=Ye().codes,{errorOrDestroy:T}=b;l(j.prototype,g.prototype),l(j,g);function q(){}var F=u("kOnFinished");function D(M,H,te){typeof te!="boolean"&&(te=H instanceof yt()),this.objectMode=!!(M&&M.objectMode),te&&(this.objectMode=this.objectMode||!!(M&&M.writableObjectMode)),this.highWaterMark=M?w(this,M,"writableHighWaterMark",te):m(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let he=!!(M&&M.decodeStrings===!1);this.decodeStrings=!he,this.defaultEncoding=M&&M.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=O.bind(void 0,H),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,oe(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!M||M.emitClose!==!1,this.autoDestroy=!M||M.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[F]=[]}function oe(M){M.buffered=[],M.bufferedIndex=0,M.allBuffers=!0,M.allNoop=!0}D.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},s(D.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function j(M){let H=this instanceof yt();if(!H&&!n(j,this))return new j(M);this._writableState=new D(M,this,H),M&&(typeof M.write=="function"&&(this._write=M.write),typeof M.writev=="function"&&(this._writev=M.writev),typeof M.destroy=="function"&&(this._destroy=M.destroy),typeof M.final=="function"&&(this._final=M.final),typeof M.construct=="function"&&(this._construct=M.construct),M.signal&&y(M.signal,this)),g.call(this,M),b.construct(this,()=>{let te=this._writableState;te.writing||ve(this,te),V(this,te)})}s(j,d,{__proto__:null,value:function(M){return n(this,M)?!0:this!==j?!1:M&&M._writableState instanceof D}}),j.prototype.pipe=function(){T(this,new S)};function W(M,H,te,he){let fe=M._writableState;if(typeof te=="function")he=te,te=fe.defaultEncoding;else{if(!te)te=fe.defaultEncoding;else if(te!=="buffer"&&!h.isEncoding(te))throw new $(te);typeof he!="function"&&(he=q)}if(H===null)throw new P;if(!fe.objectMode)if(typeof H=="string")fe.decodeStrings!==!1&&(H=h.from(H,te),te="buffer");else if(H instanceof h)te="buffer";else if(g._isUint8Array(H))H=g._uint8ArrayToBuffer(H),te="buffer";else throw new k("chunk",["string","Buffer","Uint8Array"],H);let ye;return fe.ending?ye=new L:fe.destroyed&&(ye=new E("write")),ye?(t.nextTick(he,ye),T(M,ye,!0),ye):(fe.pendingcb++,re(M,fe,H,te,he))}j.prototype.write=function(M,H,te){return W(this,M,H,te)===!0},j.prototype.cork=function(){this._writableState.corked++},j.prototype.uncork=function(){let M=this._writableState;M.corked&&(M.corked--,M.writing||ve(this,M))},j.prototype.setDefaultEncoding=function(M){if(typeof M=="string"&&(M=c(M)),!h.isEncoding(M))throw new $(M);return this._writableState.defaultEncoding=M,this};function re(M,H,te,he,fe){let ye=H.objectMode?1:te.length;H.length+=ye;let z=H.length<H.highWaterMark;return z||(H.needDrain=!0),H.writing||H.corked||H.errored||!H.constructed?(H.buffered.push({chunk:te,encoding:he,callback:fe}),H.allBuffers&&he!=="buffer"&&(H.allBuffers=!1),H.allNoop&&fe!==q&&(H.allNoop=!1)):(H.writelen=ye,H.writecb=fe,H.writing=!0,H.sync=!0,M._write(te,he,H.onwrite),H.sync=!1),z&&!H.errored&&!H.destroyed}function U(M,H,te,he,fe,ye,z){H.writelen=he,H.writecb=z,H.writing=!0,H.sync=!0,H.destroyed?H.onwrite(new E("write")):te?M._writev(fe,H.onwrite):M._write(fe,ye,H.onwrite),H.sync=!1}function Q(M,H,te,he){--H.pendingcb,he(te),ee(H),T(M,te)}function O(M,H){let te=M._writableState,he=te.sync,fe=te.writecb;if(typeof fe!="function"){T(M,new v);return}te.writing=!1,te.writecb=null,te.length-=te.writelen,te.writelen=0,H?(H.stack,te.errored||(te.errored=H),M._readableState&&!M._readableState.errored&&(M._readableState.errored=H),he?t.nextTick(Q,M,te,H,fe):Q(M,te,H,fe)):(te.buffered.length>te.bufferedIndex&&ve(M,te),he?te.afterWriteTickInfo!==null&&te.afterWriteTickInfo.cb===fe?te.afterWriteTickInfo.count++:(te.afterWriteTickInfo={count:1,cb:fe,stream:M,state:te},t.nextTick(J,te.afterWriteTickInfo)):pe(M,te,1,fe))}function J({stream:M,state:H,count:te,cb:he}){return H.afterWriteTickInfo=null,pe(M,H,te,he)}function pe(M,H,te,he){for(!H.ending&&!M.destroyed&&H.length===0&&H.needDrain&&(H.needDrain=!1,M.emit("drain"));te-- >0;)H.pendingcb--,he();H.destroyed&&ee(H),V(M,H)}function ee(M){if(M.writing)return;for(let fe=M.bufferedIndex;fe<M.buffered.length;++fe){var H;let{chunk:ye,callback:z}=M.buffered[fe],ge=M.objectMode?1:ye.length;M.length-=ge,z((H=M.errored)!==null&&H!==void 0?H:new E("write"))}let te=M[F].splice(0);for(let fe=0;fe<te.length;fe++){var he;te[fe]((he=M.errored)!==null&&he!==void 0?he:new E("end"))}oe(M)}function ve(M,H){if(H.corked||H.bufferProcessing||H.destroyed||!H.constructed)return;let{buffered:te,bufferedIndex:he,objectMode:fe}=H,ye=te.length-he;if(!ye)return;let z=he;if(H.bufferProcessing=!0,ye>1&&M._writev){H.pendingcb-=ye-1;let ge=H.allNoop?q:ae=>{for(let Me=z;Me<te.length;++Me)te[Me].callback(ae)},we=H.allNoop&&z===0?te:r(te,z);we.allBuffers=H.allBuffers,U(M,H,!0,H.length,we,"",ge),oe(H)}else{do{let{chunk:ge,encoding:we,callback:ae}=te[z];te[z++]=null;let Me=fe?1:ge.length;U(M,H,!1,Me,ge,we,ae)}while(z<te.length&&!H.writing);z===te.length?oe(H):z>256?(te.splice(0,z),H.bufferedIndex=0):H.bufferedIndex=z}H.bufferProcessing=!1}j.prototype._write=function(M,H,te){if(this._writev)this._writev([{chunk:M,encoding:H}],te);else throw new x("_write()")},j.prototype._writev=null,j.prototype.end=function(M,H,te){let he=this._writableState;typeof M=="function"?(te=M,M=null,H=null):typeof H=="function"&&(te=H,H=null);let fe;if(M!=null){let ye=W(this,M,H);ye instanceof o&&(fe=ye)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,V(this,he,!0),he.ended=!0):he.finished?fe=new I("end"):he.destroyed&&(fe=new E("end"))),typeof te=="function"&&(fe||he.finished?t.nextTick(te,fe):he[F].push(te)),this};function G(M){return M.ending&&!M.destroyed&&M.constructed&&M.length===0&&!M.errored&&M.buffered.length===0&&!M.finished&&!M.writing&&!M.errorEmitted&&!M.closeEmitted}function R(M,H){let te=!1;function he(fe){if(te){T(M,fe??v());return}if(te=!0,H.pendingcb--,fe){let ye=H[F].splice(0);for(let z=0;z<ye.length;z++)ye[z](fe);T(M,fe,H.sync)}else G(H)&&(H.prefinished=!0,M.emit("prefinish"),H.pendingcb++,t.nextTick(Y,M,H))}H.sync=!0,H.pendingcb++;try{M._final(he)}catch(fe){he(fe)}H.sync=!1}function ne(M,H){!H.prefinished&&!H.finalCalled&&(typeof M._final=="function"&&!H.destroyed?(H.finalCalled=!0,R(M,H)):(H.prefinished=!0,M.emit("prefinish")))}function V(M,H,te){G(H)&&(ne(M,H),H.pendingcb===0&&(te?(H.pendingcb++,t.nextTick((he,fe)=>{G(fe)?Y(he,fe):fe.pendingcb--},M,H)):G(H)&&(H.pendingcb++,Y(M,H))))}function Y(M,H){H.pendingcb--,H.finished=!0;let te=H[F].splice(0);for(let he=0;he<te.length;he++)te[he]();if(M.emit("finish"),H.autoDestroy){let he=M._readableState;(!he||he.autoDestroy&&(he.endEmitted||he.readable===!1))&&M.destroy()}}a(j.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(M){this._writableState&&(this._writableState.destroyed=M)}},writable:{__proto__:null,get(){let M=this._writableState;return!!M&&M.writable!==!1&&!M.destroyed&&!M.errored&&!M.ending&&!M.ended},set(M){this._writableState&&(this._writableState.writable=!!M)}},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 M=this._writableState;return M?!M.destroyed&&!M.ending&&M.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 X=b.destroy;j.prototype.destroy=function(M,H){let te=this._writableState;return!te.destroyed&&(te.bufferedIndex<te.buffered.length||te[F].length)&&t.nextTick(ee,te),X.call(this,M,H),this},j.prototype._undestroy=b.undestroy,j.prototype._destroy=function(M,H){H(M)},j.prototype[p.captureRejectionSymbol]=function(M){this.destroy(M)};var be;function se(){return be===void 0&&(be={}),be}j.fromWeb=function(M,H){return se().newStreamWritableFromWritableStream(M,H)},j.toWeb=function(M){return se().newWritableStreamFromStreamWritable(M)}}),fu=me((i,e)=>{le(),ue(),ce();var t=jt(),r=(He(),je(qe)),{isReadable:o,isWritable:n,isIterable:s,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=bt(),g=It(),{AbortError:h,codes:{ERR_INVALID_ARG_TYPE:b,ERR_INVALID_RETURN_VALUE:y}}=Ye(),{destroyer:w}=Vt(),m=yt(),k=Cr(),x=Ci(),{createDeferredPromise:v}=Xe(),S=As(),E=globalThis.Blob||r.Blob,I=typeof E<"u"?function(F){return F instanceof E}:function(F){return!1},P=globalThis.AbortController||sr().AbortController,{FunctionPrototypeCall:L}=Be(),$=class extends m{constructor(F){super(F),F?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),F?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function F(D,oe){if(u(D))return D;if(l(D))return q({readable:D});if(c(D))return q({writable:D});if(a(D))return q({writable:!1,readable:!1});if(d(D))return q({readable:k.fromWeb(D)});if(p(D))return q({writable:x.fromWeb(D)});if(typeof D=="function"){let{value:W,write:re,final:U,destroy:Q}=T(D);if(s(W))return S($,W,{objectMode:!0,write:re,final:U,destroy:Q});let O=W?.then;if(typeof O=="function"){let J,pe=L(O,W,ee=>{if(ee!=null)throw new y("nully","body",ee)},ee=>{w(J,ee)});return J=new $({objectMode:!0,readable:!1,write:re,final(ee){U(async()=>{try{await pe,t.nextTick(ee,null)}catch(ve){t.nextTick(ee,ve)}})},destroy:Q})}throw new y("Iterable, AsyncIterable or AsyncFunction",oe,W)}if(I(D))return F(D.arrayBuffer());if(s(D))return S($,D,{objectMode:!0,writable:!1});if(d(D?.readable)&&p(D?.writable))return $.fromWeb(D);if(typeof D?.writable=="object"||typeof D?.readable=="object"){let W=D!=null&&D.readable?l(D?.readable)?D?.readable:F(D.readable):void 0,re=D!=null&&D.writable?c(D?.writable)?D?.writable:F(D.writable):void 0;return q({readable:W,writable:re})}let j=D?.then;if(typeof j=="function"){let W;return L(j,D,re=>{re!=null&&W.push(re),W.push(null)},re=>{w(W,re)}),W=new $({objectMode:!0,writable:!1,read(){}})}throw new b(oe,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],D)};function T(F){let{promise:D,resolve:oe}=v(),j=new P,W=j.signal;return{value:F((async function*(){for(;;){let re=D;D=null;let{chunk:U,done:Q,cb:O}=await re;if(t.nextTick(O),Q)return;if(W.aborted)throw new h(void 0,{cause:W.reason});({promise:D,resolve:oe}=v()),yield U}})(),{signal:W}),write(re,U,Q){let O=oe;oe=null,O({chunk:re,done:!1,cb:Q})},final(re){let U=oe;oe=null,U({done:!0,cb:re})},destroy(re,U){j.abort(),U(re)}}}function q(F){let D=F.readable&&typeof F.readable.read!="function"?k.wrap(F.readable):F.readable,oe=F.writable,j=!!o(D),W=!!n(oe),re,U,Q,O,J;function pe(ee){let ve=O;O=null,ve?ve(ee):ee&&J.destroy(ee)}return J=new $({readableObjectMode:!!(D!=null&&D.readableObjectMode),writableObjectMode:!!(oe!=null&&oe.writableObjectMode),readable:j,writable:W}),W&&(g(oe,ee=>{W=!1,ee&&w(D,ee),pe(ee)}),J._write=function(ee,ve,G){oe.write(ee,ve)?G():re=G},J._final=function(ee){oe.end(),U=ee},oe.on("drain",function(){if(re){let ee=re;re=null,ee()}}),oe.on("finish",function(){if(U){let ee=U;U=null,ee()}})),j&&(g(D,ee=>{j=!1,ee&&w(D,ee),pe(ee)}),D.on("readable",function(){if(Q){let ee=Q;Q=null,ee()}}),D.on("end",function(){J.push(null)}),J._read=function(){for(;;){let ee=D.read();if(ee===null){Q=J._read;return}if(!J.push(ee))return}}),J._destroy=function(ee,ve){!ee&&O!==null&&(ee=new h),Q=null,re=null,U=null,O===null?ve(ee):(O=ve,w(oe,ee),w(D,ee))},J}}),yt=me((i,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:o,ObjectSetPrototypeOf:n}=Be();e.exports=l;var s=Cr(),a=Ci();n(l.prototype,s.prototype),n(l,s);{let p=o(a.prototype);for(let g=0;g<p.length;g++){let h=p[g];l.prototype[h]||(l.prototype[h]=a.prototype[h])}}function l(p){if(!(this instanceof l))return new l(p);s.call(this,p),a.call(this,p),p?(this.allowHalfOpen=p.allowHalfOpen!==!1,p.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),p.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}t(l.prototype,{writable:{__proto__:null,...r(a.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(a.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(a.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(a.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(a.prototype,"writableLength")},writableFinished:{__proto__:null,...r(a.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(a.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(a.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(a.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(p){this._readableState&&this._writableState&&(this._readableState.destroyed=p,this._writableState.destroyed=p)}}});var c;function u(){return c===void 0&&(c={}),c}l.fromWeb=function(p,g){return u().newStreamDuplexFromReadableWritablePair(p,g)},l.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var d;l.from=function(p){return d||(d=fu()),d(p,"body")}}),Is=me((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Be();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:o}=Ye().codes,n=yt(),{getHighWaterMark:s}=Tr();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(d){if(!(this instanceof l))return new l(d);let p=d?s(this,d,"readableHighWaterMark",!0):null;p===0&&(d={...d,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:d.writableHighWaterMark||0}),n.call(this,d),this._readableState.sync=!1,this[a]=null,d&&(typeof d.transform=="function"&&(this._transform=d.transform),typeof d.flush=="function"&&(this._flush=d.flush)),this.on("prefinish",u)}function c(d){typeof this._flush=="function"&&!this.destroyed?this._flush((p,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)}l.prototype._final=c,l.prototype._transform=function(d,p,g){throw new o("_transform()")},l.prototype._write=function(d,p,g){let h=this._readableState,b=this._writableState,y=h.length;this._transform(d,p,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),b.ended||y===h.length||h.length<h.highWaterMark?g():this[a]=g})},l.prototype._read=function(){if(this[a]){let d=this[a];this[a]=null,d()}}}),Ts=me((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Be();e.exports=o;var r=Is();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,s,a){a(null,n)}}),Pi=me((i,e)=>{le(),ue(),ce();var t=jt(),{ArrayIsArray:r,Promise:o,SymbolAsyncIterator:n,SymbolDispose:s}=Be(),a=It(),{once:l}=Xe(),c=Vt(),u=yt(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:h,ERR_STREAM_DESTROYED:b,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ye(),{validateFunction:m,validateAbortSignal:k}=lr(),{isIterable:x,isReadable:v,isReadableNodeStream:S,isNodeStream:E,isTransformStream:I,isWebStream:P,isReadableStream:L,isReadableFinished:$}=bt(),T=globalThis.AbortController||sr().AbortController,q,F,D;function oe(ee,ve,G){let R=!1;ee.on("close",()=>{R=!0});let ne=a(ee,{readable:ve,writable:G},V=>{R=!V});return{destroy:V=>{R||(R=!0,c.destroyer(ee,V||new b("pipe")))},cleanup:ne}}function j(ee){return m(ee[ee.length-1],"streams[stream.length - 1]"),ee.pop()}function W(ee){if(x(ee))return ee;if(S(ee))return re(ee);throw new p("val",["Readable","Iterable","AsyncIterable"],ee)}async function*re(ee){F||(F=Cr()),yield*F.prototype[n].call(ee)}async function U(ee,ve,G,{end:R}){let ne,V=null,Y=se=>{if(se&&(ne=se),V){let M=V;V=null,M()}},X=()=>new o((se,M)=>{ne?M(ne):V=()=>{ne?M(ne):se()}});ve.on("drain",Y);let be=a(ve,{readable:!1},Y);try{ve.writableNeedDrain&&await X();for await(let se of ee)ve.write(se)||await X();R&&(ve.end(),await X()),G()}catch(se){G(ne!==se?d(ne,se):se)}finally{be(),ve.off("drain",Y)}}async function Q(ee,ve,G,{end:R}){I(ve)&&(ve=ve.writable);let ne=ve.getWriter();try{for await(let V of ee)await ne.ready,ne.write(V).catch(()=>{});await ne.ready,R&&await ne.close(),G()}catch(V){try{await ne.abort(V),G(V)}catch(Y){G(Y)}}}function O(...ee){return J(ee,l(j(ee)))}function J(ee,ve,G){if(ee.length===1&&r(ee[0])&&(ee=ee[0]),ee.length<2)throw new h("streams");let R=new T,ne=R.signal,V=G?.signal,Y=[];k(V,"options.signal");function X(){fe(new w)}D=D||Xe().addAbortListener;let be;V&&(be=D(V,X));let se,M,H=[],te=0;function he(we){fe(we,--te===0)}function fe(we,ae){var Me;if(we&&(!se||se.code==="ERR_STREAM_PREMATURE_CLOSE")&&(se=we),!(!se&&!ae)){for(;H.length;)H.shift()(se);(Me=be)===null||Me===void 0||Me[s](),R.abort(),ae&&(se||Y.forEach(f=>f()),t.nextTick(ve,se,M))}}let ye;for(let we=0;we<ee.length;we++){let ae=ee[we],Me=we<ee.length-1,f=we>0,_=Me||G?.end!==!1,A=we===ee.length-1;if(E(ae)){let B=function(Z){Z&&Z.name!=="AbortError"&&Z.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(Z)};if(_){let{destroy:Z,cleanup:de}=oe(ae,Me,f);H.push(Z),v(ae)&&A&&Y.push(de)}ae.on("error",B),v(ae)&&A&&Y.push(()=>{ae.removeListener("error",B)})}if(we===0)if(typeof ae=="function"){if(ye=ae({signal:ne}),!x(ye))throw new g("Iterable, AsyncIterable or Stream","source",ye)}else x(ae)||S(ae)||I(ae)?ye=ae:ye=u.from(ae);else if(typeof ae=="function"){if(I(ye)){var z;ye=W((z=ye)===null||z===void 0?void 0:z.readable)}else ye=W(ye);if(ye=ae(ye,{signal:ne}),Me){if(!x(ye,!0))throw new g("AsyncIterable",`transform[${we-1}]`,ye)}else{var ge;q||(q=Ts());let B=new q({objectMode:!0}),Z=(ge=ye)===null||ge===void 0?void 0:ge.then;if(typeof Z=="function")te++,Z.call(ye,K=>{M=K,K!=null&&B.write(K),_&&B.end(),t.nextTick(he)},K=>{B.destroy(K),t.nextTick(he,K)});else if(x(ye,!0))te++,U(ye,B,he,{end:_});else if(L(ye)||I(ye)){let K=ye.readable||ye;te++,U(K,B,he,{end:_})}else throw new g("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:de,cleanup:_e}=oe(ye,!1,!0);H.push(de),A&&Y.push(_e)}}else if(E(ae)){if(S(ye)){te+=2;let B=pe(ye,ae,he,{end:_});v(ae)&&A&&Y.push(B)}else if(I(ye)||L(ye)){let B=ye.readable||ye;te++,U(B,ae,he,{end:_})}else if(x(ye))te++,U(ye,ae,he,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else if(P(ae)){if(S(ye))te++,Q(W(ye),ae,he,{end:_});else if(L(ye)||x(ye))te++,Q(ye,ae,he,{end:_});else if(I(ye))te++,Q(ye.readable,ae,he,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else ye=u.from(ae)}return(ne!=null&&ne.aborted||V!=null&&V.aborted)&&t.nextTick(X),ye}function pe(ee,ve,G,{end:R}){let ne=!1;if(ve.on("close",()=>{ne||G(new y)}),ee.pipe(ve,{end:!1}),R){let V=function(){ne=!0,ve.end()};$(ee)?t.nextTick(V):ee.once("end",V)}else G();return a(ee,{readable:!0,writable:!1},V=>{let Y=ee._readableState;V&&V.code==="ERR_STREAM_PREMATURE_CLOSE"&&Y&&Y.ended&&!Y.errored&&!Y.errorEmitted?ee.once("end",G).once("error",G):G(V)}),a(ve,{readable:!1,writable:!0},G)}e.exports={pipelineImpl:J,pipeline:O}}),Cs=me((i,e)=>{le(),ue(),ce();var{pipeline:t}=Pi(),r=yt(),{destroyer:o}=Vt(),{isNodeStream:n,isReadable:s,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=bt(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:h}}=Ye(),b=It();e.exports=function(...y){if(y.length===0)throw new h("streams");if(y.length===1)return r.from(y[0]);let w=[...y];if(typeof y[0]=="function"&&(y[0]=r.from(y[0])),typeof y[y.length-1]=="function"){let T=y.length-1;y[T]=r.from(y[T])}for(let T=0;T<y.length;++T)if(!(!n(y[T])&&!l(y[T]))){if(T<y.length-1&&!(s(y[T])||d(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(y[T])||u(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be writable")}let m,k,x,v,S;function E(T){let q=v;v=null,q?q(T):T?S.destroy(T):!$&&!L&&S.destroy()}let I=y[0],P=t(y,E),L=!!(a(I)||u(I)||c(I)),$=!!(s(P)||d(P)||c(P));if(S=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(P!=null&&P.readableObjectMode),writable:L,readable:$}),L){if(n(I))S._write=function(q,F,D){I.write(q,F)?D():m=D},S._final=function(q){I.end(),k=q},I.on("drain",function(){if(m){let q=m;m=null,q()}});else if(l(I)){let q=(c(I)?I.writable:I).getWriter();S._write=async function(F,D,oe){try{await q.ready,q.write(F).catch(()=>{}),oe()}catch(j){oe(j)}},S._final=async function(F){try{await q.ready,q.close().catch(()=>{}),k=F}catch(D){F(D)}}}let T=c(P)?P.readable:P;b(T,()=>{if(k){let q=k;k=null,q()}})}if($){if(n(P))P.on("readable",function(){if(x){let T=x;x=null,T()}}),P.on("end",function(){S.push(null)}),S._read=function(){for(;;){let T=P.read();if(T===null){x=S._read;return}if(!S.push(T))return}};else if(l(P)){let T=(c(P)?P.readable:P).getReader();S._read=async function(){for(;;)try{let{value:q,done:F}=await T.read();if(!S.push(q))return;if(F){S.push(null);return}}catch{return}}}}return S._destroy=function(T,q){!T&&v!==null&&(T=new p),x=null,m=null,k=null,v===null?q(T):(v=q,n(P)&&o(P,T))},S}}),mu=me((i,e)=>{le(),ue(),ce();var t=globalThis.AbortController||sr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:s},AbortError:a}=Ye(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=lr(),d=Be().Symbol("kWeak"),p=Be().Symbol("kResistStopPropagation"),{finished:g}=It(),h=Cs(),{addAbortSignalNoValidate:b}=Ir(),{isWritable:y,isNodeStream:w}=bt(),{deprecate:m}=Xe(),{ArrayPrototypePush:k,Boolean:x,MathFloor:v,Number:S,NumberIsNaN:E,Promise:I,PromiseReject:P,PromiseResolve:L,PromisePrototypeThen:$,Symbol:T}=Be(),q=T("kEmpty"),F=T("kEof");function D(V,Y){if(Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),w(V)&&!y(V))throw new r("stream",V,"must be writable");let X=h(this,V);return Y!=null&&Y.signal&&b(Y.signal,X),X}function oe(V,Y){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal");let X=1;Y?.concurrency!=null&&(X=v(Y.concurrency));let be=X-1;return Y?.highWaterMark!=null&&(be=v(Y.highWaterMark)),c(X,"options.concurrency",1),c(be,"options.highWaterMark",0),be+=X,(async function*(){let se=Xe().AbortSignalAny([Y?.signal].filter(x)),M=this,H=[],te={signal:se},he,fe,ye=!1,z=0;function ge(){ye=!0,we()}function we(){z-=1,ae()}function ae(){fe&&!ye&&z<X&&H.length<be&&(fe(),fe=null)}async function Me(){try{for await(let f of M){if(ye)return;if(se.aborted)throw new a;try{if(f=V(f,te),f===q)continue;f=L(f)}catch(_){f=P(_)}z+=1,$(f,we,ge),H.push(f),he&&(he(),he=null),!ye&&(H.length>=be||z>=X)&&await new I(_=>{fe=_})}H.push(F)}catch(f){let _=P(f);$(_,we,ge),H.push(_)}finally{ye=!0,he&&(he(),he=null)}}Me();try{for(;;){for(;H.length>0;){let f=await H[0];if(f===F)return;if(se.aborted)throw new a;f!==q&&(yield f),H.shift(),ae()}await new I(f=>{he=f})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function j(V=void 0){return V!=null&&u(V,"options"),V?.signal!=null&&l(V.signal,"options.signal"),(async function*(){let Y=0;for await(let be of this){var X;if(V!=null&&(X=V.signal)!==null&&X!==void 0&&X.aborted)throw new a({cause:V.signal.reason});yield[Y++,be]}}).call(this)}async function W(V,Y=void 0){for await(let X of O.call(this,V,Y))return!0;return!1}async function re(V,Y=void 0){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);return!await W.call(this,async(...X)=>!await V(...X),Y)}async function U(V,Y){for await(let X of O.call(this,V,Y))return X}async function Q(V,Y){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);async function X(be,se){return await V(be,se),q}for await(let be of oe.call(this,X,Y));}function O(V,Y){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);async function X(be,se){return await V(be,se)?be:q}return oe.call(this,X,Y)}var J=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function pe(V,Y,X){var be;if(typeof V!="function")throw new o("reducer",["Function","AsyncFunction"],V);X!=null&&u(X,"options"),X?.signal!=null&&l(X.signal,"options.signal");let se=arguments.length>1;if(X!=null&&(be=X.signal)!==null&&be!==void 0&&be.aborted){let fe=new a(void 0,{cause:X.signal.reason});throw this.once("error",()=>{}),await g(this.destroy(fe)),fe}let M=new t,H=M.signal;if(X!=null&&X.signal){let fe={once:!0,[d]:this,[p]:!0};X.signal.addEventListener("abort",()=>M.abort(),fe)}let te=!1;try{for await(let fe of this){var he;if(te=!0,X!=null&&(he=X.signal)!==null&&he!==void 0&&he.aborted)throw new a;se?Y=await V(Y,fe,{signal:H}):(Y=fe,se=!0)}if(!te&&!se)throw new J}finally{M.abort()}return Y}async function ee(V){V!=null&&u(V,"options"),V?.signal!=null&&l(V.signal,"options.signal");let Y=[];for await(let be of this){var X;if(V!=null&&(X=V.signal)!==null&&X!==void 0&&X.aborted)throw new a(void 0,{cause:V.signal.reason});k(Y,be)}return Y}function ve(V,Y){let X=oe.call(this,V,Y);return(async function*(){for await(let be of X)yield*be}).call(this)}function G(V){if(V=S(V),E(V))return 0;if(V<0)throw new s("number",">= 0",V);return V}function R(V,Y=void 0){return Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),V=G(V),(async function*(){var X;if(Y!=null&&(X=Y.signal)!==null&&X!==void 0&&X.aborted)throw new a;for await(let se of this){var be;if(Y!=null&&(be=Y.signal)!==null&&be!==void 0&&be.aborted)throw new a;V--<=0&&(yield se)}}).call(this)}function ne(V,Y=void 0){return Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),V=G(V),(async function*(){var X;if(Y!=null&&(X=Y.signal)!==null&&X!==void 0&&X.aborted)throw new a;for await(let se of this){var be;if(Y!=null&&(be=Y.signal)!==null&&be!==void 0&&be.aborted)throw new a;if(V-- >0&&(yield se),V<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(j,"readable.asIndexedPairs will be removed in a future version."),drop:R,filter:O,flatMap:ve,map:oe,take:ne,compose:D},e.exports.promiseReturningOperators={every:re,forEach:Q,reduce:pe,toArray:ee,some:W,find:U}}),Ps=me((i,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Be(),{isIterable:o,isNodeStream:n,isWebStream:s}=bt(),{pipelineImpl:a}=Pi(),{finished:l}=It();Os();function c(...u){return new r((d,p)=>{let g,h,b=u[u.length-1];if(b&&typeof b=="object"&&!n(b)&&!o(b)&&!s(b)){let y=t(u);g=y.signal,h=y.end}a(u,(y,w)=>{y?p(y):d(w)},{signal:g,end:h})})}e.exports={finished:l,pipeline:c}}),Os=me((i,e)=>{le(),ue(),ce();var{Buffer:t}=(He(),je(qe)),{ObjectDefineProperty:r,ObjectKeys:o,ReflectApply:n}=Be(),{promisify:{custom:s}}=Xe(),{streamReturningOperators:a,promiseReturningOperators:l}=mu(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ye(),u=Cs(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=Tr(),{pipeline:g}=Pi(),{destroyer:h}=Vt(),b=It(),y=Ps(),w=bt(),m=e.exports=Ti().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=Cr();for(let x of o(a)){let v=function(...E){if(new.target)throw c();return m.Readable.from(n(S,this,E))},S=a[x];r(v,"name",{__proto__:null,value:S.name}),r(v,"length",{__proto__:null,value:S.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let x of o(l)){let v=function(...E){if(new.target)throw c();return n(S,this,E)},S=l[x];r(v,"name",{__proto__:null,value:S.name}),r(v,"length",{__proto__:null,value:S.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=Ci(),m.Duplex=yt(),m.Transform=Is(),m.PassThrough=Ts(),m.pipeline=g;var{addAbortSignal:k}=Ir();m.addAbortSignal=k,m.finished=b,m.destroy=h,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(g,s,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(b,s,{__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)}}),$t=me((i,e)=>{le(),ue(),ce();var t=Os(),r=Ps(),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}),gu=me((i,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}}}),bu=me((i,e)=>{le(),ue(),ce();var{Buffer:t}=(He(),je(qe)),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 s=0;for(let a=0;a<this._bufs.length;a++){let l=s+this._bufs[a].length;if(n<l||a===this._bufs.length-1)return[a,n-s];s=l}},o.prototype._reverseOffset=function(n){let s=n[0],a=n[1];for(let l=0;l<s;l++)a+=this._bufs[l].length;return a},o.prototype.getBuffers=function(){return this._bufs},o.prototype.get=function(n){if(n>this.length||n<0)return;let s=this._offset(n);return this._bufs[s[0]][s[1]]},o.prototype.slice=function(n,s){return typeof n=="number"&&n<0&&(n+=this.length),typeof s=="number"&&s<0&&(s+=this.length),this.copy(null,0,n,s)},o.prototype.copy=function(n,s,a,l){if((typeof a!="number"||a<0)&&(a=0),(typeof l!="number"||l>this.length)&&(l=this.length),a>=this.length||l<=0)return n||t.alloc(0);let c=!!n,u=this._offset(a),d=l-a,p=d,g=c&&s||0,h=u[1];if(a===0&&l===this.length){if(!c)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let b=0;b<this._bufs.length;b++)this._bufs[b].copy(n,g),g+=this._bufs[b].length;return n}if(p<=this._bufs[u[0]].length-h)return c?this._bufs[u[0]].copy(n,s,h,h+p):this._bufs[u[0]].slice(h,h+p);c||(n=t.allocUnsafe(d));for(let b=u[0];b<this._bufs.length;b++){let y=this._bufs[b].length-h;if(p>y)this._bufs[b].copy(n,g,h),g+=y;else{this._bufs[b].copy(n,g,h,h+p),g+=y;break}p-=y,h&&(h=0)}return n.length>g?n.slice(0,g):n},o.prototype.shallowSlice=function(n,s){if(n=n||0,s=typeof s!="number"?this.length:s,n<0&&(n+=this.length),s<0&&(s+=this.length),n===s)return this._new();let a=this._offset(n),l=this._offset(s),c=this._bufs.slice(a[0],l[0]+1);return l[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,l[1]),a[1]!==0&&(c[0]=c[0].slice(a[1])),this._new(c)},o.prototype.toString=function(n,s,a){return this.slice(s,a).toString(n)},o.prototype.consume=function(n){if(n=Math.trunc(n),Number.isNaN(n)||n<=0)return this;for(;this._bufs.length;)if(n>=this._bufs[0].length)n-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(n),this.length-=n;break}return this},o.prototype.duplicate=function(){let n=this._new();for(let s=0;s<this._bufs.length;s++)n.append(this._bufs[s]);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,s,a){if(n==null)return this;if(n.buffer)s.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[l,c]=a?[n.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n.length;u+=c)this._attach(n[u],s,a)}else if(this._isBufferList(n)){let[l,c]=a?[n._bufs.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],s,a)}else typeof n=="number"&&(n=n.toString()),s.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,s,a){if(a===void 0&&typeof s=="string"&&(a=s,s=void 0),typeof n=="function"||Array.isArray(n))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof n=="number"?n=t.from([n]):typeof n=="string"?n=t.from(n,a):this._isBufferList(n)?n=n.slice():Array.isArray(n.buffer)?n=t.from(n.buffer,n.byteOffset,n.byteLength):t.isBuffer(n)||(n=t.from(n)),s=Number(s||0),isNaN(s)&&(s=0),s<0&&(s=this.length+s),s<0&&(s=0),n.length===0)return s>this.length?this.length:s;let l=this._offset(s),c=l[0],u=l[1];for(;c<this._bufs.length;c++){let d=this._bufs[c];for(;u<d.length;)if(d.length-u>=n.length){let p=d.indexOf(n,u);if(p!==-1)return this._reverseOffset([c,p]);u=d.length-n.length+1}else{let p=this._reverseOffset([c,u]);if(this._match(p,n))return p;u++}u=0}return-1},o.prototype._match=function(n,s){if(this.length-n<s.length)return!1;for(let a=0;a<s.length;a++)if(this.get(n+a)!==s[a])return!1;return!0},(function(){let n={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let s in n)(function(a){n[a]===null?o.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:o.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(s)})(),o.prototype._isBufferList=function(n){return n instanceof o||o.isBufferList(n)},o.isBufferList=function(n){return n!=null&&n[r]},e.exports=o}),yu=me((i,e)=>{le(),ue(),ce();var t=$t().Duplex,r=gu(),o=bu();function n(s){if(!(this instanceof n))return new n(s);if(typeof s=="function"){this._callback=s;let a=(function(l){this._callback&&(this._callback(l),this._callback=null)}).bind(this);this.on("pipe",function(l){l.on("error",a)}),this.on("unpipe",function(l){l.removeListener("error",a)}),s=null}o._init.call(this,s),t.call(this)}r(n,t),Object.assign(n.prototype,o.prototype),n.prototype._new=function(s){return new n(s)},n.prototype._write=function(s,a,l){this._appendBuffer(s),typeof l=="function"&&l()},n.prototype._read=function(s){if(!this.length)return this.push(null);s=Math.min(s,this.length),this.push(this.slice(0,s)),this.consume(s)},n.prototype.end=function(s){t.prototype.end.call(this,s),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(s,a){this._bufs.length=0,this.length=0,a(s)},n.prototype._isBufferList=function(s){return s instanceof n||s instanceof o||n.isBufferList(s)},n.isBufferList=o.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=o}),vu=me((i,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}),Ls=me((i,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(He(),je(qe));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 s=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+s.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let s=t.types[n];t.codes[s]=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 s=t.properties[n];t.propertiesCodes[s]=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(s=>[0,1].map(a=>[0,1].map(l=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(a?t.DUP_MASK:0)|s<<t.QOS_SHIFT|l,0,!0),c})))}t.PUBLISH_HEADER=o("publish"),t.SUBSCRIBE_HEADER=o("subscribe"),t.SUBSCRIBE_OPTIONS_QOS_MASK=3,t.SUBSCRIBE_OPTIONS_NL_MASK=1,t.SUBSCRIBE_OPTIONS_NL_SHIFT=2,t.SUBSCRIBE_OPTIONS_RAP_MASK=1,t.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,t.SUBSCRIBE_OPTIONS_RH_MASK=3,t.SUBSCRIBE_OPTIONS_RH_SHIFT=4,t.SUBSCRIBE_OPTIONS_RH=[0,16,32],t.SUBSCRIBE_OPTIONS_NL=4,t.SUBSCRIBE_OPTIONS_RAP=8,t.SUBSCRIBE_OPTIONS_QOS=[0,1,2],t.UNSUBSCRIBE_HEADER=o("unsubscribe"),t.ACKS={unsuback:o("unsuback"),puback:o("puback"),pubcomp:o("pubcomp"),pubrel:o("pubrel"),pubrec:o("pubrec")},t.SUBACK_HEADER=r.from([t.codes.suback<<t.CMD_SHIFT]),t.VERSION3=r.from([3]),t.VERSION4=r.from([4]),t.VERSION5=r.from([5]),t.VERSION131=r.from([131]),t.VERSION132=r.from([132]),t.QOS=[0,1,2].map(n=>r.from([n])),t.EMPTY={pingreq:r.from([t.codes.pingreq<<4,0]),pingresp:r.from([t.codes.pingresp<<4,0]),disconnect:r.from([t.codes.disconnect<<4,0])},t.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},t.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},t.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},t.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}}),wu=me((i,e)=>{le(),ue(),ce();var t=1e3,r=t*60,o=r*60,n=o*24,s=n*7,a=n*365.25;e.exports=function(p,g){g=g||{};var h=typeof p;if(h==="string"&&p.length>0)return l(p);if(h==="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 l(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 h=parseFloat(g[1]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return h*a;case"weeks":case"week":case"w":return h*s;case"days":case"day":case"d":return h*n;case"hours":case"hour":case"hrs":case"hr":case"h":return h*o;case"minutes":case"minute":case"mins":case"min":case"m":return h*r;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}}}function c(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?d(p,g,n,"day"):g>=o?d(p,g,o,"hour"):g>=r?d(p,g,r,"minute"):g>=t?d(p,g,t,"second"):p+" ms"}function d(p,g,h,b){var y=g>=h*1.5;return Math.round(p/h)+" "+b+(y?"s":"")}}),ku=me((i,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=d,n.disable=c,n.enable=a,n.enabled=u,n.humanize=wu(),n.destroy=p,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function o(g){let h=0;for(let b=0;b<g.length;b++)h=(h<<5)-h+g.charCodeAt(b),h|=0;return n.colors[Math.abs(h)%n.colors.length]}n.selectColor=o;function n(g){let h,b=null,y,w;function m(...k){if(!m.enabled)return;let x=m,v=Number(new Date),S=v-(h||v);x.diff=S,x.prev=h,x.curr=v,h=v,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let E=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(I,P)=>{if(I==="%%")return"%";E++;let L=n.formatters[P];if(typeof L=="function"){let $=k[E];I=L.call(x,$),k.splice(E,1),E--}return I}),n.formatArgs.call(x,k),(x.log||n.log).apply(x,k)}return m.namespace=g,m.useColors=n.useColors(),m.color=n.selectColor(g),m.extend=s,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(y!==n.namespaces&&(y=n.namespaces,w=n.enabled(g)),w),set:k=>{b=k}}),typeof n.init=="function"&&n.init(m),m}function s(g,h){let b=n(this.namespace+(typeof h>"u"?":":h)+g);return b.log=this.log,b}function a(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let h=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let b of h)b[0]==="-"?n.skips.push(b.slice(1)):n.names.push(b)}function l(g,h){let b=0,y=0,w=-1,m=0;for(;b<g.length;)if(y<h.length&&(h[y]===g[b]||h[y]==="*"))h[y]==="*"?(w=y,m=b,y++):(b++,y++);else if(w!==-1)y=w+1,m++,b=m;else return!1;for(;y<h.length&&h[y]==="*";)y++;return y===h.length}function c(){let g=[...n.names,...n.skips.map(h=>"-"+h)].join(",");return n.enable(""),g}function u(g){for(let h of n.skips)if(l(g,h))return!1;for(let h of n.names)if(l(g,h))return!0;return!1}function d(g){return g instanceof Error?g.stack||g.message:g}function 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}),vt=me((i,e)=>{le(),ue(),ce(),i.formatArgs=r,i.save=o,i.load=n,i.useColors=t,i.storage=s(),i.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),i.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;l.splice(1,0,c,"color: inherit");let u=0,d=0;l[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(d=u))}),l.splice(d,0,c)}i.log=console.debug||console.log||(()=>{});function o(l){try{l?i.storage.setItem("debug",l):i.storage.removeItem("debug")}catch{}}function n(){let l;try{l=i.storage.getItem("debug")||i.storage.getItem("DEBUG")}catch{}return!l&&typeof De<"u"&&"env"in De&&(l=De.env.DEBUG),l}function s(){try{return localStorage}catch{}}e.exports=ku()(i);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),_u=me((i,e)=>{le(),ue(),ce();var t=yu(),{EventEmitter:r}=(Rt(),je(At)),o=vu(),n=Ls(),s=vt()("mqtt-packet:parser"),a=class Ko extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof Ko?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new Ko().parser(c)}_resetState(){s("_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),s("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++,s("parse: state complete. _stateCounter is now: %d",this._stateCounter),s("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return s("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,s("_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)),s("_parseLength %d",c.value),!!c}_parsePayload(){s("_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 s("_parsePayload complete result: %s",c),c}_parseConnect(){s("_parseConnect");let c,u,d,p,g={},h=this.packet,b=this._parseString();if(b===null)return this._emitError(new Error("Cannot parse protocolId"));if(b!=="MQTT"&&b!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(h.protocolId=b,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(h.protocolVersion=this._list.readUInt8(this._pos),h.protocolVersion>=128&&(h.bridgeMode=!0,h.protocolVersion=h.protocolVersion-128),h.protocolVersion!==3&&h.protocolVersion!==4&&h.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));g.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,g.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,g.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let y=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),w=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(g.will)h.will={},h.will.retain=y,h.will.qos=w;else{if(y)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(w)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(h.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,h.keepalive=this._parseNum(),h.keepalive===-1)return this._emitError(new Error("Packet too short"));if(h.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(h.properties=k)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(h.clientId=m,s("_parseConnect: packet.clientId: %s",h.clientId),g.will){if(h.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(h.will.properties=k)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(h.will.topic=c,s("_parseConnect: packet.will.topic: %s",h.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));h.will.payload=u,s("_parseConnect: packet.will.paylaod: %s",h.will.payload)}if(g.username){if(p=this._parseString(),p===null)return this._emitError(new Error("Cannot parse username"));h.username=p,s("_parseConnect: packet.username: %s",h.username)}if(g.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));h.password=d}return this.settings=h,s("_parseConnect: complete"),h}_parseConnack(){s("_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)}s("_parseConnack: complete")}_parsePublish(){s("_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),s("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){s("_parseSubscribe");let c=this.packet,u,d,p,g,h,b,y;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(c.properties=w)}if(c.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<c.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=c.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(d=this._parseByte(),this.settings.protocolVersion===5){if(d&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(d&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(b=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,h=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,g=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,g>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));y={topic:u,qos:p},this.settings.protocolVersion===5?(y.nl=b,y.rap=h,y.rh=g):this.settings.bridgeMode&&(y.rh=0,y.rap=!0,y.nl=!0),s("_parseSubscribe: push subscription `%s` to subscription",y),c.subscriptions.push(y)}}}_parseSuback(){s("_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(){s("_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"));s("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){s("_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(){s("_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}s("_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(s("_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 s("_parseDisconnect result: true"),!0}_parseAuth(){s("_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),s("_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):(s("_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,s("_parseString: result: %s",p),p}_parseStringPair(){return s("_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,s("_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,s("_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,s("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){s("_parseVarByteNum");let u=4,d=0,p=1,g=0,h=!1,b,y=this._pos?this._pos:0;for(;d<u&&y+d<this._list.length;){if(b=this._list.readUInt8(y+d++),g+=p*(b&n.VARBYTEINT_MASK),p*=128,(b&n.VARBYTEINT_FIN_MASK)===0){h=!0;break}if(this._list.length<=d)break}return!h&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=d),h?c?h={bytes:d,value:g}:h=g:h=!1,s("_parseVarByteNum: result: %o",h),h}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),s("_parseByte: result: %o",c),c}_parseByType(c){switch(s("_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(){s("_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 h=this._parseByType(n.propertiesTypes[g]);if(d[g][h.name])if(Array.isArray(d[g][h.name]))d[g][h.name].push(h.value);else{let b=d[g][h.name];d[g][h.name]=[b],d[g][h.name].push(h.value)}else d[g][h.name]=h.value;continue}d[g]?Array.isArray(d[g])?d[g].push(this._parseByType(n.propertiesTypes[g])):(d[g]=[d[g]],d[g].push(this._parseByType(n.propertiesTypes[g]))):d[g]=this._parseByType(n.propertiesTypes[g])}return d}_newPacket(){return s("_newPacket"),this.packet&&(this._list.consume(this.packet.length),s("_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)),s("_newPacket: new packet"),this.packet=new o,this._pos=0,!0}_emitError(c){s("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),xu=me((i,e)=>{le(),ue(),ce();var{Buffer:t}=(He(),je(qe)),r=65536,o={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function s(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function a(){for(let u=0;u<r;u++)o[u]=s(u)}function l(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:o,generateCache:a,generateNumber:s,genBufVariableByteInt:l,generate4ByteBuffer:c}}),Su=me((i,e)=>{le(),ue(),ce(),typeof De>"u"||!De.version||De.version.indexOf("v0.")===0||De.version.indexOf("v1.")===0&&De.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=De;function t(r,o,n,s){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var a=arguments.length,l,c;switch(a){case 0:case 1:return De.nextTick(r);case 2:return De.nextTick(function(){r.call(null,o)});case 3:return De.nextTick(function(){r.call(null,o,n)});case 4:return De.nextTick(function(){r.call(null,o,n,s)});default:for(l=new Array(a-1),c=0;c<l.length;)l[c++]=arguments[c];return De.nextTick(function(){r.apply(null,l)})}}}),Ms=me((i,e)=>{le(),ue(),ce();var t=Ls(),{Buffer:r}=(He(),je(qe)),o=r.allocUnsafe(0),n=r.from([0]),s=xu(),a=Su().nextTick,l=vt()("mqtt-packet:writeToStream"),c=s.cache,u=s.generateNumber,d=s.generateCache,p=s.genBufVariableByteInt,g=s.generate4ByteBuffer,h=j,b=!0;function y(G,R,ne){switch(l("generate called"),R.cork&&(R.cork(),a(w,R)),b&&(b=!1,d()),l("generate: packet.cmd: %s",G.cmd),G.cmd){case"connect":return m(G,R);case"connack":return k(G,R,ne);case"publish":return x(G,R,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(G,R,ne);case"subscribe":return S(G,R,ne);case"suback":return E(G,R,ne);case"unsubscribe":return I(G,R,ne);case"unsuback":return P(G,R,ne);case"pingreq":case"pingresp":return L(G,R);case"disconnect":return $(G,R,ne);case"auth":return T(G,R,ne);default:return R.destroy(new Error("Unknown command")),!1}}Object.defineProperty(y,"cacheNumbers",{get(){return h===j},set(G){G?((!c||Object.keys(c).length===0)&&(b=!0),h=j):(b=!1,h=W)}});function w(G){G.uncork()}function m(G,R,ne){let V=G||{},Y=V.protocolId||"MQTT",X=V.protocolVersion||4,be=V.will,se=V.clean,M=V.keepalive||0,H=V.clientId||"",te=V.username,he=V.password,fe=V.properties;se===void 0&&(se=!0);let ye=0;if(typeof Y!="string"&&!r.isBuffer(Y))return R.destroy(new Error("Invalid protocolId")),!1;if(ye+=Y.length+2,X!==3&&X!==4&&X!==5)return R.destroy(new Error("Invalid protocol version")),!1;if(ye+=1,(typeof H=="string"||r.isBuffer(H))&&(H||X>=4)&&(H||se))ye+=r.byteLength(H)+2;else{if(X<4)return R.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(se*1===0)return R.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof M!="number"||M<0||M>65535||M%1!==0)return R.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let z,ge;if(X===5){if(z=Q(R,fe),!z)return!1;ye+=z.length}if(be){if(typeof be!="object")return R.destroy(new Error("Invalid will")),!1;if(!be.topic||typeof be.topic!="string")return R.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(be.topic)+2,ye+=2,be.payload)if(be.payload.length>=0)typeof be.payload=="string"?ye+=r.byteLength(be.payload):ye+=be.payload.length;else return R.destroy(new Error("Invalid will payload")),!1;if(ge={},X===5){if(ge=Q(R,be.properties),!ge)return!1;ye+=ge.length}}let we=!1;if(te!=null)if(ve(te))we=!0,ye+=r.byteLength(te)+2;else return R.destroy(new Error("Invalid username")),!1;if(he!=null){if(!we)return R.destroy(new Error("Username is required to use password")),!1;if(ve(he))ye+=ee(he)+2;else return R.destroy(new Error("Invalid password")),!1}R.write(t.CONNECT_HEADER),F(R,ye),U(R,Y),V.bridgeMode&&(X+=128),R.write(X===131?t.VERSION131:X===132?t.VERSION132:X===4?t.VERSION4:X===5?t.VERSION5:t.VERSION3);let ae=0;return ae|=te!=null?t.USERNAME_MASK:0,ae|=he!=null?t.PASSWORD_MASK:0,ae|=be&&be.retain?t.WILL_RETAIN_MASK:0,ae|=be&&be.qos?be.qos<<t.WILL_QOS_SHIFT:0,ae|=be?t.WILL_FLAG_MASK:0,ae|=se?t.CLEAN_SESSION_MASK:0,R.write(r.from([ae])),h(R,M),X===5&&z.write(),U(R,H),be&&(X===5&&ge.write(),D(R,be.topic),U(R,be.payload)),te!=null&&U(R,te),he!=null&&U(R,he),!0}function k(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=V===5?Y.reasonCode:Y.returnCode,be=Y.properties,se=2;if(typeof X!="number")return R.destroy(new Error("Invalid return code")),!1;let M=null;if(V===5){if(M=Q(R,be),!M)return!1;se+=M.length}return R.write(t.CONNACK_HEADER),F(R,se),R.write(Y.sessionPresent?t.SESSIONPRESENT_HEADER:n),R.write(r.from([X])),M?.write(),!0}function x(G,R,ne){l("publish: packet: %o",G);let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.qos||0,be=Y.retain?t.RETAIN_MASK:0,se=Y.topic,M=Y.payload||o,H=Y.messageId,te=Y.properties,he=0;if(typeof se=="string")he+=r.byteLength(se)+2;else if(r.isBuffer(se))he+=se.length+2;else return R.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(M)?he+=M.length:he+=r.byteLength(M),X&&typeof H!="number")return R.destroy(new Error("Invalid messageId")),!1;X&&(he+=2);let fe=null;if(V===5){if(fe=Q(R,te),!fe)return!1;he+=fe.length}return R.write(t.PUBLISH_HEADER[X][Y.dup?1:0][be?1:0]),F(R,he),h(R,ee(se)),R.write(se),X>0&&h(R,H),fe?.write(),l("publish: payload: %o",M),R.write(M)}function v(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.cmd||"puback",be=Y.messageId,se=Y.dup&&X==="pubrel"?t.DUP_MASK:0,M=0,H=Y.reasonCode,te=Y.properties,he=V===5?3:2;if(X==="pubrel"&&(M=1),typeof be!="number")return R.destroy(new Error("Invalid messageId")),!1;let fe=null;if(V===5&&typeof te=="object"){if(fe=O(R,te,ne,he),!fe)return!1;he+=fe.length}return R.write(t.ACKS[X][M][se][0]),he===3&&(he+=H!==0?1:-1),F(R,he),h(R,be),V===5&&he!==2&&R.write(r.from([H])),fe!==null?fe.write():he===4&&R.write(r.from([0])),!0}function S(G,R,ne){l("subscribe: packet: ");let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.dup?t.DUP_MASK:0,be=Y.messageId,se=Y.subscriptions,M=Y.properties,H=0;if(typeof be!="number")return R.destroy(new Error("Invalid messageId")),!1;H+=2;let te=null;if(V===5){if(te=Q(R,M),!te)return!1;H+=te.length}if(typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){let ye=se[fe].topic,z=se[fe].qos;if(typeof ye!="string")return R.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof z!="number")return R.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(V===5){if(typeof(se[fe].nl||!1)!="boolean")return R.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(se[fe].rap||!1)!="boolean")return R.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let ge=se[fe].rh||0;if(typeof ge!="number"||ge>2)return R.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}H+=r.byteLength(ye)+2+1}else return R.destroy(new Error("Invalid subscriptions")),!1;l("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),R.write(t.SUBSCRIBE_HEADER[1][X?1:0][0]),F(R,H),h(R,be),te!==null&&te.write();let he=!0;for(let fe of se){let ye=fe.topic,z=fe.qos,ge=+fe.nl,we=+fe.rap,ae=fe.rh,Me;D(R,ye),Me=t.SUBSCRIBE_OPTIONS_QOS[z],V===5&&(Me|=ge?t.SUBSCRIBE_OPTIONS_NL:0,Me|=we?t.SUBSCRIBE_OPTIONS_RAP:0,Me|=ae?t.SUBSCRIBE_OPTIONS_RH[ae]:0),he=R.write(r.from([Me]))}return he}function E(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.messageId,be=Y.granted,se=Y.properties,M=0;if(typeof X!="number")return R.destroy(new Error("Invalid messageId")),!1;if(M+=2,typeof be=="object"&&be.length)for(let te=0;te<be.length;te+=1){if(typeof be[te]!="number")return R.destroy(new Error("Invalid qos vector")),!1;M+=1}else return R.destroy(new Error("Invalid qos vector")),!1;let H=null;if(V===5){if(H=O(R,se,ne,M),!H)return!1;M+=H.length}return R.write(t.SUBACK_HEADER),F(R,M),h(R,X),H!==null&&H.write(),R.write(r.from(be))}function I(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.messageId,be=Y.dup?t.DUP_MASK:0,se=Y.unsubscriptions,M=Y.properties,H=0;if(typeof X!="number")return R.destroy(new Error("Invalid messageId")),!1;if(H+=2,typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){if(typeof se[fe]!="string")return R.destroy(new Error("Invalid unsubscriptions")),!1;H+=r.byteLength(se[fe])+2}else return R.destroy(new Error("Invalid unsubscriptions")),!1;let te=null;if(V===5){if(te=Q(R,M),!te)return!1;H+=te.length}R.write(t.UNSUBSCRIBE_HEADER[1][be?1:0][0]),F(R,H),h(R,X),te!==null&&te.write();let he=!0;for(let fe=0;fe<se.length;fe++)he=D(R,se[fe]);return he}function P(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.messageId,be=Y.dup?t.DUP_MASK:0,se=Y.granted,M=Y.properties,H=Y.cmd,te=0,he=2;if(typeof X!="number")return R.destroy(new Error("Invalid messageId")),!1;if(V===5)if(typeof se=="object"&&se.length)for(let ye=0;ye<se.length;ye+=1){if(typeof se[ye]!="number")return R.destroy(new Error("Invalid qos vector")),!1;he+=1}else return R.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(V===5){if(fe=O(R,M,ne,he),!fe)return!1;he+=fe.length}return R.write(t.ACKS[H][te][be][0]),F(R,he),h(R,X),fe!==null&&fe.write(),V===5&&R.write(r.from(se)),!0}function L(G,R,ne){return R.write(t.EMPTY[G.cmd])}function $(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.reasonCode,be=Y.properties,se=V===5?1:0,M=null;if(V===5){if(M=O(R,be,ne,se),!M)return!1;se+=M.length}return R.write(r.from([t.codes.disconnect<<4])),F(R,se),V===5&&R.write(r.from([X])),M!==null&&M.write(),!0}function T(G,R,ne){let V=ne?ne.protocolVersion:4,Y=G||{},X=Y.reasonCode,be=Y.properties,se=V===5?1:0;V!==5&&R.destroy(new Error("Invalid mqtt version for auth packet"));let M=O(R,be,ne,se);return M?(se+=M.length,R.write(r.from([t.codes.auth<<4])),F(R,se),R.write(r.from([X])),M!==null&&M.write(),!0):!1}var q={};function F(G,R){if(R>t.VARBYTEINT_MAX)return G.destroy(new Error(`Invalid variable byte integer: ${R}`)),!1;let ne=q[R];return ne||(ne=p(R),R<16384&&(q[R]=ne)),l("writeVarByteInt: writing to stream: %o",ne),G.write(ne)}function D(G,R){let ne=r.byteLength(R);return h(G,ne),l("writeString: %s",R),G.write(R,"utf8")}function oe(G,R,ne){D(G,R),D(G,ne)}function j(G,R){return l("writeNumberCached: number: %d",R),l("writeNumberCached: %o",c[R]),G.write(c[R])}function W(G,R){let ne=u(R);return l("writeNumberGenerated: %o",ne),G.write(ne)}function re(G,R){let ne=g(R);return l("write4ByteNumber: %o",ne),G.write(ne)}function U(G,R){typeof R=="string"?D(G,R):R?(h(G,R.length),G.write(R)):h(G,0)}function Q(G,R){if(typeof R!="object"||R.length!=null)return{length:1,write(){pe(G,{},0)}};let ne=0;function V(Y,X){let be=t.propertiesTypes[Y],se=0;switch(be){case"byte":{if(typeof X!="boolean")return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=2;break}case"int8":{if(typeof X!="number"||X<0||X>255)return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=2;break}case"binary":{if(X&&X===null)return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=1+r.byteLength(X)+2;break}case"int16":{if(typeof X!="number"||X<0||X>65535)return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=3;break}case"int32":{if(typeof X!="number"||X<0||X>4294967295)return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=5;break}case"var":{if(typeof X!="number"||X<0||X>268435455)return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=1+r.byteLength(p(X));break}case"string":{if(typeof X!="string")return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=3+r.byteLength(X.toString());break}case"pair":{if(typeof X!="object")return G.destroy(new Error(`Invalid ${Y}: ${X}`)),!1;se+=Object.getOwnPropertyNames(X).reduce((M,H)=>{let te=X[H];return Array.isArray(te)?M+=te.reduce((he,fe)=>(he+=3+r.byteLength(H.toString())+2+r.byteLength(fe.toString()),he),0):M+=3+r.byteLength(H.toString())+2+r.byteLength(X[H].toString()),M},0);break}default:return G.destroy(new Error(`Invalid property ${Y}: ${X}`)),!1}return se}if(R)for(let Y in R){let X=0,be=0,se=R[Y];if(se!==void 0){if(Array.isArray(se))for(let M=0;M<se.length;M++){if(be=V(Y,se[M]),!be)return!1;X+=be}else{if(be=V(Y,se),!be)return!1;X=be}if(!X)return!1;ne+=X}}return{length:r.byteLength(p(ne))+ne,write(){pe(G,R,ne)}}}function O(G,R,ne,V){let Y=["reasonString","userProperties"],X=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,be=Q(G,R);if(X)for(;V+be.length>X;){let se=Y.shift();if(se&&R[se])delete R[se],be=Q(G,R);else return!1}return be}function J(G,R,ne){switch(t.propertiesTypes[R]){case"byte":{G.write(r.from([t.properties[R]])),G.write(r.from([+ne]));break}case"int8":{G.write(r.from([t.properties[R]])),G.write(r.from([ne]));break}case"binary":{G.write(r.from([t.properties[R]])),U(G,ne);break}case"int16":{G.write(r.from([t.properties[R]])),h(G,ne);break}case"int32":{G.write(r.from([t.properties[R]])),re(G,ne);break}case"var":{G.write(r.from([t.properties[R]])),F(G,ne);break}case"string":{G.write(r.from([t.properties[R]])),D(G,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(V=>{let Y=ne[V];Array.isArray(Y)?Y.forEach(X=>{G.write(r.from([t.properties[R]])),oe(G,V.toString(),X.toString())}):(G.write(r.from([t.properties[R]])),oe(G,V.toString(),Y.toString()))});break}default:return G.destroy(new Error(`Invalid property ${R} value: ${ne}`)),!1}}function pe(G,R,ne){F(G,ne);for(let V in R)if(Object.prototype.hasOwnProperty.call(R,V)&&R[V]!=null){let Y=R[V];if(Array.isArray(Y))for(let X=0;X<Y.length;X++)J(G,V,Y[X]);else J(G,V,Y)}}function ee(G){return G?G instanceof r?G.length:r.byteLength(G):0}function ve(G){return typeof G=="string"||G instanceof r}e.exports=y}),Eu=me((i,e)=>{le(),ue(),ce();var t=Ms(),{EventEmitter:r}=(Rt(),je(At)),{Buffer:o}=(He(),je(qe));function n(a,l){let c=new s;return t(a,c,l),c.concat()}var s=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(a){return this._array[this._i++]=a,!0}concat(){let a=0,l=new Array(this._array.length),c=this._array,u=0,d;for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?l[d]=c[d].length:l[d]=o.byteLength(c[d]),a+=l[d];let p=o.allocUnsafe(a);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(p,u),u+=l[d]):(p.write(c[d],u),u+=l[d]);return p}destroy(a){a&&this.emit("error",a)}};e.exports=n}),Au=me(i=>{le(),ue(),ce(),i.parser=_u().parser,i.generate=Eu(),i.writeToStream=Ms()}),Iu=me((i,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof Ar?Ar.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return o(n);let s=new Map;if(s.set(Date,d=>new Date(d)),s.set(Map,(d,p)=>new Map(l(Array.from(d),p))),s.set(Set,(d,p)=>new Set(l(Array.from(d),p))),n.constructorHandlers)for(let d of n.constructorHandlers)s.set(d[0],d[1]);let a=null;return n.proto?u:c;function l(d,p){let g=Object.keys(d),h=new Array(g.length);for(let b=0;b<g.length;b++){let y=g[b],w=d[y];typeof w!="object"||w===null?h[y]=w:w.constructor!==Object&&(a=s.get(w.constructor))?h[y]=a(w,p):ArrayBuffer.isView(w)?h[y]=t(w):h[y]=p(w)}return h}function c(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,c);if(d.constructor!==Object&&(a=s.get(d.constructor)))return a(d,c);let p={};for(let g in d){if(Object.hasOwnProperty.call(d,g)===!1)continue;let h=d[g];typeof h!="object"||h===null?p[g]=h:h.constructor!==Object&&(a=s.get(h.constructor))?p[g]=a(h,c):ArrayBuffer.isView(h)?p[g]=t(h):p[g]=c(h)}return p}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,u);if(d.constructor!==Object&&(a=s.get(d.constructor)))return a(d,u);let p={};for(let g in d){let h=d[g];typeof h!="object"||h===null?p[g]=h:h.constructor!==Object&&(a=s.get(h.constructor))?p[g]=a(h,u):ArrayBuffer.isView(h)?p[g]=t(h):p[g]=u(h)}return p}}function o(n){let s=[],a=[],l=new Map;if(l.set(Date,g=>new Date(g)),l.set(Map,(g,h)=>new Map(u(Array.from(g),h))),l.set(Set,(g,h)=>new Set(u(Array.from(g),h))),n.constructorHandlers)for(let g of n.constructorHandlers)l.set(g[0],g[1]);let c=null;return n.proto?p:d;function u(g,h){let b=Object.keys(g),y=new Array(b.length);for(let w=0;w<b.length;w++){let m=b[w],k=g[m];if(typeof k!="object"||k===null)y[m]=k;else if(k.constructor!==Object&&(c=l.get(k.constructor)))y[m]=c(k,h);else if(ArrayBuffer.isView(k))y[m]=t(k);else{let x=s.indexOf(k);x!==-1?y[m]=a[x]:y[m]=h(k)}}return y}function d(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,d);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,d);let h={};s.push(g),a.push(h);for(let b in g){if(Object.hasOwnProperty.call(g,b)===!1)continue;let y=g[b];if(typeof y!="object"||y===null)h[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))h[b]=c(y,d);else if(ArrayBuffer.isView(y))h[b]=t(y);else{let w=s.indexOf(y);w!==-1?h[b]=a[w]:h[b]=d(y)}}return s.pop(),a.pop(),h}function p(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,p);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,p);let h={};s.push(g),a.push(h);for(let b in g){let y=g[b];if(typeof y!="object"||y===null)h[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))h[b]=c(y,p);else if(ArrayBuffer.isView(y))h[b]=t(y);else{let w=s.indexOf(y);w!==-1?h[b]=a[w]:h[b]=p(y)}}return s.pop(),a.pop(),h}}}),Tu=me((i,e)=>{le(),ue(),ce(),e.exports=Iu()()}),Ns=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.validateTopic=e,i.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}}),Rs=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=$t(),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,s){return this._inflights.set(n.messageId,n),s&&s(),this}createStream(){let n=new e.Readable(t),s=[],a=!1,l=0;return this._inflights.forEach((c,u)=>{s.push(c)}),n._read=()=>{!a&&l<s.length?n.push(s[l++]):n.push(null)},n.destroy=c=>{if(!a)return a=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,s){let a=this._inflights.get(n.messageId);return a?(this._inflights.delete(n.messageId),s(null,a)):s&&s(new Error("missing packet")),this}get(n,s){let a=this._inflights.get(n.messageId);return a?s(null,a):s&&s(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};i.default=o}),Cu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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 s=o.topic.toString(),a=o.payload,{qos:l}=o,{messageId:c}=o,{options:u}=r;if(r.options.protocolVersion===5){let d;if(o.properties&&(d=o.properties.topicAlias),typeof d<"u")if(s.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)s=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",s,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(s,d))r.log("handlePublish :: registered topic: %s - alias: %d",s,d);else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",l),l){case 2:{u.customHandleAcks(s,a,o,(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(o,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(s,a,o,(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",s,a,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",s,a,o),r.handleMessage(o,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};i.default=t}),Pu=me((i,e)=>{e.exports={version:"5.15.0"}}),Kt=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.MQTTJS_VERSION=i.nextTick=i.ErrorWithSubackPacket=i.ErrorWithReasonCode=void 0,i.applyMixin=r;var e=class Rc extends Error{code;constructor(n,s){super(n),this.code=s,Object.setPrototypeOf(this,Rc.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};i.ErrorWithReasonCode=e;var t=class jc extends Error{packet;constructor(n,s){super(n),this.packet=s,Object.setPrototypeOf(this,jc.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};i.ErrorWithSubackPacket=t;function r(o,n,s=!1){let a=[n];for(;;){let l=a[0],c=Object.getPrototypeOf(l);if(c?.prototype)a.unshift(c);else break}for(let l of a)for(let c of Object.getOwnPropertyNames(l.prototype))(s||c!=="constructor")&&Object.defineProperty(o.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}i.nextTick=typeof De?.nextTick=="function"?De.nextTick:o=>{setTimeout(o,0)},i.MQTTJS_VERSION=Pu().version}),Pr=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=void 0;var e=Kt();i.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,s=o.cmd,a=null,l=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!l){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",s),s){case"pubcomp":case"puback":{let u=o.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,o)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=o.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,o)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=o.granted;for(let d=0;d<u.length;d++){let p=u[d];if((p&128)!==0){c=new Error(`Subscribe error: ${i.ReasonCodes[p]}`),c.code=p;let g=r.messageIdToTopic[n];g&&g.forEach(h=>{delete r._resubscribeTopics[h]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),l(c,o);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,o);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};i.default=t}),Ou=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Kt(),t=Pr(),r=(o,n)=>{let{options:s}=o,a=s.protocolVersion,l=a===5?n.reasonCode:n.returnCode;if(a!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${a}`,l);o.emit("error",c);return}o.handleAuth(n,(c,u)=>{if(c){o.emit("error",c);return}if(l===24)o.reconnecting=!1,o._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);o.emit("error",d)}})};i.default=r}),Lu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof De=="object"&&De?De:{},o=(g,h,b,y)=>{typeof r.emitWarning=="function"?r.emitWarning(g,h,b,y):console.error(`[${b}] ${h}: ${g}`)},n=globalThis.AbortController,s=globalThis.AbortSignal;if(typeof n>"u"){s=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(b,y){this._onabort.push(y)}},n=class{constructor(){h()}signal=new s;abort(b){if(!this.signal.aborted){this.signal.reason=b,this.signal.aborted=!0;for(let y of this.signal._onabort)y(b);this.signal.onabort?.(b)}}};let g=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",h=()=>{g&&(g=!1,o("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",h))}}var a=g=>!t.has(g),l=g=>g&&g===Math.floor(g)&&g>0&&isFinite(g),c=g=>l(g)?g<=Math.pow(2,8)?Uint8Array:g<=Math.pow(2,16)?Uint16Array:g<=Math.pow(2,32)?Uint32Array:g<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(g){super(g),this.fill(0)}},d=class kr{heap;length;static#l=!1;static create(h){let b=c(h);if(!b)return[];kr.#l=!0;let y=new kr(h,b);return kr.#l=!1,y}constructor(h,b){if(!kr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new b(h),this.length=0}push(h){this.heap[this.length++]=h}pop(){return this.heap[--this.length]}},p=class $c{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#h;#a;#o;#y;#s;#v;#w;#p;#k;#A;#u;static unsafeExposeInternals(h){return{starts:h.#w,ttls:h.#p,sizes:h.#v,keyMap:h.#n,keyList:h.#r,valList:h.#e,next:h.#c,prev:h.#h,get head(){return h.#a},get tail(){return h.#o},free:h.#y,isBackgroundFetch:b=>h.#t(b),backgroundFetch:(b,y,w,m)=>h.#N(b,y,w,m),moveToTail:b=>h.#C(b),indexes:b=>h.#_(b),rindexes:b=>h.#x(b),isStale:b=>h.#f(b)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#b}get size(){return this.#i}get fetchMethod(){return this.#P}get memoMethod(){return this.#O}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(h){let{max:b=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:k,updateAgeOnHas:x,allowStale:v,dispose:S,disposeAfter:E,noDisposeOnSet:I,noUpdateTTL:P,maxSize:L=0,maxEntrySize:$=0,sizeCalculation:T,fetchMethod:q,memoMethod:F,noDeleteOnFetchRejection:D,noDeleteOnStaleGet:oe,allowStaleOnFetchRejection:j,allowStaleOnFetchAbort:W,ignoreFetchAbort:re}=h;if(b!==0&&!l(b))throw new TypeError("max option must be a nonnegative integer");let U=b?c(b):Array;if(!U)throw new Error("invalid max value: "+b);if(this.#l=b,this.#d=L,this.maxEntrySize=$||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(F!==void 0&&typeof F!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=F,q!==void 0&&typeof q!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=q,this.#A=!!q,this.#n=new Map,this.#r=new Array(b).fill(void 0),this.#e=new Array(b).fill(void 0),this.#c=new U(b),this.#h=new U(b),this.#a=0,this.#o=0,this.#y=d.create(b),this.#i=0,this.#b=0,typeof S=="function"&&(this.#m=S),typeof E=="function"?(this.#g=E,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#k=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!P,this.noDeleteOnFetchRejection=!!D,this.allowStaleOnFetchRejection=!!j,this.allowStaleOnFetchAbort=!!W,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#d!==0&&!l(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!l(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!oe,this.updateAgeOnGet=!!k,this.updateAgeOnHas=!!x,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=y||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R()}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 Q="LRU_CACHE_UNBOUNDED";a(Q)&&(t.add(Q),o("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Q,$c))}}getRemainingTTL(h){return this.#n.has(h)?1/0:0}#R(){let h=new u(this.#l),b=new u(this.#l);this.#p=h,this.#w=b,this.#j=(m,k,x=e.now())=>{if(b[m]=k!==0?x:0,h[m]=k,k!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#f(m)&&this.#S(this.#r[m],"expire")},k+1);v.unref&&v.unref()}},this.#I=m=>{b[m]=h[m]!==0?e.now():0},this.#E=(m,k)=>{if(h[k]){let x=h[k],v=b[k];if(!x||!v)return;m.ttl=x,m.start=v,m.now=y||w();let S=m.now-v;m.remainingTTL=x-S}};let y=0,w=()=>{let m=e.now();if(this.ttlResolution>0){y=m;let k=setTimeout(()=>y=0,this.ttlResolution);k.unref&&k.unref()}return m};this.getRemainingTTL=m=>{let k=this.#n.get(m);if(k===void 0)return 0;let x=h[k],v=b[k];if(!x||!v)return 1/0;let S=(y||w())-v;return x-S},this.#f=m=>{let k=b[m],x=h[m];return!!x&&!!k&&(y||w())-k>x}}#I=()=>{};#E=()=>{};#j=()=>{};#f=()=>!1;#F(){let h=new u(this.#l);this.#b=0,this.#v=h,this.#T=b=>{this.#b-=h[b],h[b]=0},this.#$=(b,y,w,m)=>{if(this.#t(y))return 0;if(!l(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(y,b),!l(w))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return w},this.#L=(b,y,w)=>{if(h[b]=y,this.#d){let m=this.#d-h[b];for(;this.#b>m;)this.#M(!0)}this.#b+=h[b],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=h=>{};#L=(h,b,y)=>{};#$=(h,b,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:h=this.allowStale}={}){if(this.#i)for(let b=this.#o;!(!this.#D(b)||((h||!this.#f(b))&&(yield b),b===this.#a));)b=this.#h[b]}*#x({allowStale:h=this.allowStale}={}){if(this.#i)for(let b=this.#a;!(!this.#D(b)||((h||!this.#f(b))&&(yield b),b===this.#o));)b=this.#c[b]}#D(h){return h!==void 0&&this.#n.get(this.#r[h])===h}*entries(){for(let h of this.#_())this.#e[h]!==void 0&&this.#r[h]!==void 0&&!this.#t(this.#e[h])&&(yield[this.#r[h],this.#e[h]])}*rentries(){for(let h of this.#x())this.#e[h]!==void 0&&this.#r[h]!==void 0&&!this.#t(this.#e[h])&&(yield[this.#r[h],this.#e[h]])}*keys(){for(let h of this.#_()){let b=this.#r[h];b!==void 0&&!this.#t(this.#e[h])&&(yield b)}}*rkeys(){for(let h of this.#x()){let b=this.#r[h];b!==void 0&&!this.#t(this.#e[h])&&(yield b)}}*values(){for(let h of this.#_())this.#e[h]!==void 0&&!this.#t(this.#e[h])&&(yield this.#e[h])}*rvalues(){for(let h of this.#x())this.#e[h]!==void 0&&!this.#t(this.#e[h])&&(yield this.#e[h])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(h,b={}){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&h(m,this.#r[y],this))return this.get(this.#r[y],b)}}forEach(h,b=this){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&h.call(b,m,this.#r[y],this)}}rforEach(h,b=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&h.call(b,m,this.#r[y],this)}}purgeStale(){let h=!1;for(let b of this.#x({allowStale:!0}))this.#f(b)&&(this.#S(this.#r[b],"expire"),h=!0);return h}info(h){let b=this.#n.get(h);if(b===void 0)return;let y=this.#e[b],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#p&&this.#w){let k=this.#p[b],x=this.#w[b];if(k&&x){let v=k-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[b]),m}dump(){let h=[];for(let b of this.#_({allowStale:!0})){let y=this.#r[b],w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||y===void 0)continue;let k={value:m};if(this.#p&&this.#w){k.ttl=this.#p[b];let x=e.now()-this.#w[b];k.start=Math.floor(Date.now()-x)}this.#v&&(k.size=this.#v[b]),h.unshift([y,k])}return h}load(h){this.clear();for(let[b,y]of h){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(b,y.value,y)}}set(h,b,y={}){if(b===void 0)return this.delete(h),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:k=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=y,{noUpdateTTL:S=this.noUpdateTTL}=y,E=this.#$(h,b,y.size||0,x);if(this.maxEntrySize&&E>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(h,"set"),this;let I=this.#i===0?void 0:this.#n.get(h);if(I===void 0)I=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#M(!1):this.#i,this.#r[I]=h,this.#e[I]=b,this.#n.set(h,I),this.#c[this.#o]=I,this.#h[I]=this.#o,this.#o=I,this.#i++,this.#L(I,E,v),v&&(v.set="add"),S=!1;else{this.#C(I);let P=this.#e[I];if(b!==P){if(this.#A&&this.#t(P)){P.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:L}=P;L!==void 0&&!k&&(this.#k&&this.#m?.(L,h,"set"),this.#u&&this.#s?.push([L,h,"set"]))}else k||(this.#k&&this.#m?.(P,h,"set"),this.#u&&this.#s?.push([P,h,"set"]));if(this.#T(I),this.#L(I,E,v),this.#e[I]=b,v){v.set="replace";let L=P&&this.#t(P)?P.__staleWhileFetching:P;L!==void 0&&(v.oldValue=L)}}else v&&(v.set="update")}if(w!==0&&!this.#p&&this.#R(),this.#p&&(S||this.#j(I,w,m),v&&this.#E(v,I)),!k&&this.#u&&this.#s){let P=this.#s,L;for(;L=P?.shift();)this.#g?.(...L)}return this}pop(){try{for(;this.#i;){let h=this.#e[this.#a];if(this.#M(!0),this.#t(h)){if(h.__staleWhileFetching)return h.__staleWhileFetching}else if(h!==void 0)return h}}finally{if(this.#u&&this.#s){let h=this.#s,b;for(;b=h?.shift();)this.#g?.(...b)}}}#M(h){let b=this.#a,y=this.#r[b],w=this.#e[b];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(b),h&&(this.#r[b]=void 0,this.#e[b]=void 0,this.#y.push(b)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[b],this.#n.delete(y),this.#i--,b}has(h,b={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=b,m=this.#n.get(h);if(m!==void 0){let k=this.#e[m];if(this.#t(k)&&k.__staleWhileFetching===void 0)return!1;if(this.#f(m))w&&(w.has="stale",this.#E(w,m));else return y&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(h,b={}){let{allowStale:y=this.allowStale}=b,w=this.#n.get(h);if(w===void 0||!y&&this.#f(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#N(h,b,y,w){let m=b===void 0?void 0:this.#e[b];if(this.#t(m))return m;let k=new n,{signal:x}=y;x?.addEventListener("abort",()=>k.abort(x.reason),{signal:k.signal});let v={signal:k.signal,options:y,context:w},S=(T,q=!1)=>{let{aborted:F}=k.signal,D=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(F&&!q?(y.status.fetchAborted=!0,y.status.fetchError=k.signal.reason,D&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),F&&!D&&!q)return I(k.signal.reason);let oe=L;return this.#e[b]===L&&(T===void 0?oe.__staleWhileFetching?this.#e[b]=oe.__staleWhileFetching:this.#S(h,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(h,T,v.options))),T},E=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:q}=k.signal,F=q&&y.allowStaleOnFetchAbort,D=F||y.allowStaleOnFetchRejection,oe=D||y.noDeleteOnFetchRejection,j=L;if(this.#e[b]===L&&(!oe||j.__staleWhileFetching===void 0?this.#S(h,"fetch"):F||(this.#e[b]=j.__staleWhileFetching)),D)return y.status&&j.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),j.__staleWhileFetching;if(j.__returned===j)throw T},P=(T,q)=>{let F=this.#P?.(h,m,v);F&&F instanceof Promise&&F.then(D=>T(D===void 0?void 0:D),q),k.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=D=>S(D,!0)))})};y.status&&(y.status.fetchDispatched=!0);let L=new Promise(P).then(S,E),$=Object.assign(L,{__abortController:k,__staleWhileFetching:m,__returned:void 0});return b===void 0?(this.set(h,$,{...v.options,status:void 0}),b=this.#n.get(h)):this.#e[b]=$,$}#t(h){if(!this.#A)return!1;let b=h;return!!b&&b instanceof Promise&&b.hasOwnProperty("__staleWhileFetching")&&b.__abortController instanceof n}async fetch(h,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:k=this.ttl,noDisposeOnSet:x=this.noDisposeOnSet,size:v=0,sizeCalculation:S=this.sizeCalculation,noUpdateTTL:E=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:L=this.ignoreFetchAbort,allowStaleOnFetchAbort:$=this.allowStaleOnFetchAbort,context:T,forceRefresh:q=!1,status:F,signal:D}=b;if(!this.#A)return F&&(F.fetch="get"),this.get(h,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:F});let oe={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:k,noDisposeOnSet:x,size:v,sizeCalculation:S,noUpdateTTL:E,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:$,ignoreFetchAbort:L,status:F,signal:D},j=this.#n.get(h);if(j===void 0){F&&(F.fetch="miss");let W=this.#N(h,j,oe,T);return W.__returned=W}else{let W=this.#e[j];if(this.#t(W)){let O=y&&W.__staleWhileFetching!==void 0;return F&&(F.fetch="inflight",O&&(F.returnedStale=!0)),O?W.__staleWhileFetching:W.__returned=W}let re=this.#f(j);if(!q&&!re)return F&&(F.fetch="hit"),this.#C(j),w&&this.#I(j),F&&this.#E(F,j),W;let U=this.#N(h,j,oe,T),Q=U.__staleWhileFetching!==void 0&&y;return F&&(F.fetch=re?"stale":"refresh",Q&&re&&(F.returnedStale=!0)),Q?U.__staleWhileFetching:U.__returned=U}}async forceFetch(h,b={}){let y=await this.fetch(h,b);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(h,b={}){let y=this.#O;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,...k}=b,x=this.get(h,k);if(!m&&x!==void 0)return x;let v=y(h,x,{options:k,context:w});return this.set(h,v,k),v}get(h,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:k}=b,x=this.#n.get(h);if(x!==void 0){let v=this.#e[x],S=this.#t(v);return k&&this.#E(k,x),this.#f(x)?(k&&(k.get="stale"),S?(k&&y&&v.__staleWhileFetching!==void 0&&(k.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(h,"expire"),k&&y&&(k.returnedStale=!0),y?v:void 0)):(k&&(k.get="hit"),S?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else k&&(k.get="miss")}#U(h,b){this.#h[b]=h,this.#c[h]=b}#C(h){h!==this.#o&&(h===this.#a?this.#a=this.#c[h]:this.#U(this.#h[h],this.#c[h]),this.#U(this.#o,h),this.#o=h)}delete(h){return this.#S(h,"delete")}#S(h,b){let y=!1;if(this.#i!==0){let w=this.#n.get(h);if(w!==void 0)if(y=!0,this.#i===1)this.#B(b);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(m,h,b),this.#u&&this.#s?.push([m,h,b])),this.#n.delete(h),this.#r[w]=void 0,this.#e[w]=void 0,w===this.#o)this.#o=this.#h[w];else if(w===this.#a)this.#a=this.#c[w];else{let k=this.#h[w];this.#c[k]=this.#c[w];let x=this.#c[w];this.#h[x]=this.#h[w]}this.#i--,this.#y.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.shift();)this.#g?.(...m)}return y}clear(){return this.#B("delete")}#B(h){for(let b of this.#x({allowStale:!0})){let y=this.#e[b];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let w=this.#r[b];this.#k&&this.#m?.(y,w,h),this.#u&&this.#s?.push([y,w,h])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#p&&this.#w&&(this.#p.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)}}};i.LRUCache=p}),wt=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.ContainerIterator=i.Container=i.Base=void 0;var e=class{constructor(o=0){this.iteratorType=o}equals(o){return this.o===o.o}};i.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};i.Base=t;var r=class extends t{};i.Container=r}),Mu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=wt(),t=class extends e.Base{constructor(o=[]){super(),this.S=[];let n=this;o.forEach(function(s){n.push(s)})}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;i.default=r}),Nu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=wt(),t=class extends e.Base{constructor(o=[]){super(),this.j=0,this.q=[];let n=this;o.forEach(function(s){n.push(s)})}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 s=this.i;for(let a=0;a<s;++a)this.q[a]=this.q[this.j+a];this.j=0,this.q[this.i]=o}else this.q[this.j+this.i]=o;return++this.i}pop(){if(this.i===0)return;let o=this.q[this.j++];return this.i-=1,o}front(){if(this.i!==0)return this.q[this.j]}},r=t;i.default=r}),Ru=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=wt(),t=class extends e.Base{constructor(o=[],n=function(a,l){return a>l?-1:a<l?1:0},s=!0){if(super(),this.v=n,Array.isArray(o))this.C=s?[...o]:o;else{this.C=[];let l=this;o.forEach(function(c){l.C.push(c)})}this.i=this.C.length;let a=this.i>>1;for(let l=this.i-1>>1;l>=0;--l)this.k(l,a)}m(o){let n=this.C[o];for(;o>0;){let s=o-1>>1,a=this.C[s];if(this.v(a,n)<=0)break;this.C[o]=a,o=s}this.C[o]=n}k(o,n){let s=this.C[o];for(;o<n;){let a=o<<1|1,l=a+1,c=this.C[a];if(l<this.i&&this.v(c,this.C[l])>0&&(a=l,c=this.C[l]),this.v(c,s)>=0)break;this.C[o]=c,o=a}this.C[o]=s}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;i.default=r}),Oi=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=wt(),t=class extends e.Container{},r=t;i.default=r}),kt=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),js=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.RandomIterator=void 0;var e=wt(),t=kt(),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)}};i.RandomIterator=r}),ju=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(Oi()),t=js();function r(a){return a&&a.t?a:{default:a}}var o=class Dc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Dc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=!0){if(super(),Array.isArray(a))this.J=l?[...a]:a,this.i=a.length;else{this.J=[];let c=this;a.forEach(function(u){c.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new o(0,this)}end(){return new o(this.i,this)}rBegin(){return new o(this.i-1,this,1)}rEnd(){return new o(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J[a]}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J.splice(a,1),this.i-=1,this.i}eraseElementByValue(a){let l=0;for(let c=0;c<this.i;++c)this.J[c]!==a&&(this.J[l++]=this.J[c]);return this.i=this.J.length=l,this.i}eraseElementByIterator(a){let l=a.o;return a=a.next(),this.eraseElementByPos(l),a}pushBack(a){return this.J.push(a),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;this.J[a]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;return this.J.splice(a,0,...new Array(c).fill(l)),this.i+=c,this.i}find(a){for(let l=0;l<this.i;++l)if(this.J[l]===a)return new o(l,this);return this.end()}reverse(){this.J.reverse()}unique(){let a=1;for(let l=1;l<this.i;++l)this.J[l]!==this.J[l-1]&&(this.J[a++]=this.J[l]);return this.i=this.J.length=a,this.i}sort(a){this.J.sort(a)}forEach(a){for(let l=0;l<this.i;++l)a(this.J[l],l,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},s=n;i.default=s}),$u=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o(Oi()),t=wt(),r=kt();function o(l){return l&&l.t?l:{default:l}}var n=class Uc 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 Uc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.default{constructor(l=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;l.forEach(function(u){c.pushBack(u)})}V(l){let{L:c,B:u}=l;c.B=u,u.L=c,l===this.p&&(this.p=u),l===this._&&(this._=c),this.i-=1}G(l,c){let u=c.B,d={l,L:c,B:u};c.B=d,u.L=d,c===this.h&&(this.p=d),u===this.h&&(this._=d),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return c.l}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return this.V(c),this.i}eraseElementByValue(l){let c=this.p;for(;c!==this.h;)c.l===l&&this.V(c),c=c.B;return this.i}eraseElementByIterator(l){let c=l.o;return c===this.h&&(0,r.throwIteratorAccessError)(),l=l.next(),this.V(c),l}pushBack(l){return this.G(l,this._),this.i}popBack(){if(this.i===0)return;let l=this._.l;return this.V(this._),l}pushFront(l){return this.G(l,this.h),this.i}popFront(){if(this.i===0)return;let l=this.p.l;return this.V(this.p),l}setElementByPos(l,c){if(l<0||l>this.i-1)throw new RangeError;let u=this.p;for(;l--;)u=u.B;u.l=c}insert(l,c,u=1){if(l<0||l>this.i)throw new RangeError;if(u<=0)return this.i;if(l===0)for(;u--;)this.pushFront(c);else if(l===this.i)for(;u--;)this.pushBack(c);else{let d=this.p;for(let g=1;g<l;++g)d=d.B;let p=d.B;for(this.i+=u;u--;)d.B={l:c,L:d},d.B.L=d,d=d.B;d.B=p,p.L=d}return this.i}find(l){let c=this.p;for(;c!==this.h;){if(c.l===l)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let l=this.p,c=this._,u=0;for(;u<<1<this.i;){let d=l.l;l.l=c.l,c.l=d,l=l.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let l=this.p;for(;l!==this.h;){let c=l;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;l.B=c.B,l.B.L=l,l=l.B}return this.i}sort(l){if(this.i<=1)return;let c=[];this.forEach(function(d){c.push(d)}),c.sort(l);let u=this.p;c.forEach(function(d){u.l=d,u=u.B})}merge(l){let c=this;if(this.i===0)l.forEach(function(u){c.pushBack(u)});else{let u=this.p;l.forEach(function(d){for(;u!==c.h&&u.l<=d;)u=u.B;c.G(d,u.L)})}return this.i}forEach(l){let c=this.p,u=0;for(;c!==this.h;)l(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let l=this.p;for(;l!==this.h;)yield l.l,l=l.B}).bind(this)()}},a=s;i.default=a}),Du=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(Oi()),t=js();function r(a){return a&&a.t?a:{default:a}}var o=class Bc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Bc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof a.length=="number")return a.length;if(typeof a.size=="number")return a.size;if(typeof a.size=="function")return a.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=l,this.P=Math.max(Math.ceil(c/this.F),1);for(let p=0;p<this.P;++p)this.A.push(new Array(this.F));let u=Math.ceil(c/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-c%this.F>>1;let d=this;a.forEach(function(p){d.pushBack(p)})}T(){let a=[],l=Math.max(this.P>>1,1);for(let c=0;c<l;++c)a[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)a[a.length]=this.A[c];for(let c=0;c<this.R;++c)a[a.length]=this.A[c];a[a.length]=[...this.A[this.R]],this.j=l,this.R=a.length-1;for(let c=0;c<l;++c)a[a.length]=new Array(this.F);this.A=a,this.P=a.length}O(a){let l=this.D+a+1,c=l%this.F,u=c-1,d=this.j+(l-c)/this.F;return c===0&&(d-=1),d%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:d,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new o(0,this)}end(){return new o(this.i,this)}rBegin(){return new o(this.i-1,this,1)}rEnd(){return new o(-1,this,1)}front(){if(this.i!==0)return this.A[this.j][this.D]}back(){if(this.i!==0)return this.A[this.R][this.N]}pushBack(a){return this.i&&(this.N<this.F-1?this.N+=1:this.R<this.P-1?(this.R+=1,this.N=0):(this.R=0,this.N=0),this.R===this.j&&this.N===this.D&&this.T()),this.i+=1,this.A[this.R][this.N]=a,this.i}popBack(){if(this.i===0)return;let a=this.A[this.R][this.N];return this.i!==1&&(this.N>0?this.N-=1:this.R>0?(this.R-=1,this.N=this.F-1):(this.R=this.P-1,this.N=this.F-1)),this.i-=1,a}pushFront(a){return this.i&&(this.D>0?this.D-=1:this.j>0?(this.j-=1,this.D=this.F-1):(this.j=this.P-1,this.D=this.F-1),this.j===this.R&&this.D===this.N&&this.T()),this.i+=1,this.A[this.j][this.D]=a,this.i}popFront(){if(this.i===0)return;let a=this.A[this.j][this.D];return this.i!==1&&(this.D<this.F-1?this.D+=1:this.j<this.P-1?(this.j+=1,this.D=0):(this.j=0,this.D=0)),this.i-=1,a}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.A[l][c]}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(a);this.A[c][u]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;if(a===0)for(;c--;)this.pushFront(l);else if(a===this.i)for(;c--;)this.pushBack(l);else{let u=[];for(let d=a;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(a-1);for(let d=0;d<c;++d)this.pushBack(l);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(a){if(a<0)return this.clear(),0;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.R=l,this.N=c,this.i=a+1,this.i}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;if(a===0)this.popFront();else if(a===this.i-1)this.popBack();else{let l=[];for(let u=a+1;u<this.i;++u)l.push(this.getElementByPos(u));this.cut(a),this.popBack();let c=this;l.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(a){if(this.i===0)return 0;let l=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==a&&l.push(d)}let c=l.length;for(let u=0;u<c;++u)this.setElementByPos(u,l[u]);return this.cut(c-1)}eraseElementByIterator(a){let l=a.o;return this.eraseElementByPos(l),a=a.next(),a}find(a){for(let l=0;l<this.i;++l)if(this.getElementByPos(l)===a)return new o(l,this);return this.end()}reverse(){let a=0,l=this.i-1;for(;a<l;){let c=this.getElementByPos(a);this.setElementByPos(a,this.getElementByPos(l)),this.setElementByPos(l,c),a+=1,l-=1}}unique(){if(this.i<=1)return this.i;let a=1,l=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==l&&(l=u,this.setElementByPos(a++,u))}for(;this.i>a;)this.popBack();return this.i}sort(a){let l=[];for(let c=0;c<this.i;++c)l.push(this.getElementByPos(c));l.sort(a);for(let c=0;c<this.i;++c)this.setElementByPos(c,l[c])}shrinkToFit(){if(this.i===0)return;let a=[];this.forEach(function(l){a.push(l)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let l=0;l<this.P;++l)this.A.push(new Array(this.F));for(let l=0;l<a.length;++l)this.pushBack(a[l])}forEach(a){for(let l=0;l<this.i;++l)a(this.getElementByPos(l),l,this)}[Symbol.iterator](){return(function*(){for(let a=0;a<this.i;++a)yield this.getElementByPos(a)}).bind(this)()}},s=n;i.default=s}),Uu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.TreeNodeEnableIndex=i.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}};i.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)}};i.TreeNodeEnableIndex=t}),$s=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Uu(),t=wt(),r=kt(),o=class extends t.Container{constructor(s=function(l,c){return l<c?-1:l>c?1:0},a=!1){super(),this.Y=void 0,this.v=s,a?(this.re=e.TreeNodeEnableIndex,this.M=function(l,c,u){let d=this.ne(l,c,u);if(d){let p=d.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let g=this.he(d);if(g){let{parentNode:h,grandParent:b,curNode:y}=g;h.ie(),b.ie(),y.ie()}}return this.i},this.V=function(l){let c=this.fe(l);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(l,c,u){let d=this.ne(l,c,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(s,a){let l=this.h;for(;s;){let c=this.v(s.u,a);if(c<0)s=s.W;else if(c>0)l=s,s=s.U;else return s}return l}Z(s,a){let l=this.h;for(;s;)this.v(s.u,a)<=0?s=s.W:(l=s,s=s.U);return l}$(s,a){let l=this.h;for(;s;){let c=this.v(s.u,a);if(c<0)l=s,s=s.W;else if(c>0)s=s.U;else return s}return l}rr(s,a){let l=this.h;for(;s;)this.v(s.u,a)<0?(l=s,s=s.W):s=s.U;return l}ue(s){for(;;){let a=s.tt;if(a===this.h)return;if(s.ee===1){s.ee=0;return}if(s===a.U){let l=a.W;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.te():a.te();else if(l.W&&l.W.ee===1){l.ee=a.ee,a.ee=0,l.W.ee=0,a===this.Y?this.Y=a.te():a.te();return}else l.U&&l.U.ee===1?(l.ee=1,l.U.ee=0,l.se()):(l.ee=1,s=a)}else{let l=a.U;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.se():a.se();else if(l.U&&l.U.ee===1){l.ee=a.ee,a.ee=0,l.U.ee=0,a===this.Y?this.Y=a.se():a.se();return}else l.W&&l.W.ee===1?(l.ee=1,l.W.ee=0,l.te()):(l.ee=1,s=a)}}}fe(s){if(this.i===1)return this.clear(),this.h;let a=s;for(;a.U||a.W;){if(a.W)for(a=a.W;a.U;)a=a.U;else a=a.U;[s.u,a.u]=[a.u,s.u],[s.l,a.l]=[a.l,s.l],s=a}this.h.U===a?this.h.U=a.tt:this.h.W===a&&(this.h.W=a.tt),this.ue(a);let l=a.tt;return a===l.U?l.U=void 0:l.W=void 0,this.i-=1,this.Y.ee=0,l}oe(s,a){return s===void 0?!1:this.oe(s.U,a)||a(s)?!0:this.oe(s.W,a)}he(s){for(;;){let a=s.tt;if(a.ee===0)return;let l=a.tt;if(a===l.U){let c=l.W;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,s=l;continue}else if(s===a.W){if(s.ee=0,s.U&&(s.U.tt=a),s.W&&(s.W.tt=l),a.W=s.U,l.U=s.W,s.U=a,s.W=l,l===this.Y)this.Y=s,this.h.tt=s;else{let u=l.tt;u.U===l?u.U=s:u.W=s}return s.tt=l.tt,a.tt=s,l.tt=s,l.ee=1,{parentNode:a,grandParent:l,curNode:s}}else a.ee=0,l===this.Y?this.Y=l.se():l.se(),l.ee=1}else{let c=l.U;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,s=l;continue}else if(s===a.U){if(s.ee=0,s.U&&(s.U.tt=l),s.W&&(s.W.tt=a),l.W=s.U,a.U=s.W,s.U=l,s.W=a,l===this.Y)this.Y=s,this.h.tt=s;else{let u=l.tt;u.U===l?u.U=s:u.W=s}return s.tt=l.tt,a.tt=s,l.tt=s,l.ee=1,{parentNode:a,grandParent:l,curNode:s}}else a.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(s,a,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(s,a),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let c,u=this.h.U,d=this.v(u.u,s);if(d===0){u.l=a;return}else if(d>0)u.U=new this.re(s,a),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,g=this.v(p.u,s);if(g===0){p.l=a;return}else if(g<0)p.W=new this.re(s,a),p.W.tt=p,c=p.W,this.h.W=c;else{if(l!==void 0){let h=l.o;if(h!==this.h){let b=this.v(h.u,s);if(b===0){h.l=a;return}else if(b>0){let y=h.L(),w=this.v(y.u,s);if(w===0){y.l=a;return}else w<0&&(c=new this.re(s,a),y.W===void 0?(y.W=c,c.tt=y):(h.U=c,c.tt=h))}}}if(c===void 0)for(c=this.Y;;){let h=this.v(c.u,s);if(h>0){if(c.U===void 0){c.U=new this.re(s,a),c.U.tt=c,c=c.U;break}c=c.U}else if(h<0){if(c.W===void 0){c.W=new this.re(s,a),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=a;return}}}}return this.i+=1,c}I(s,a){for(;s;){let l=this.v(s.u,a);if(l<0)s=s.W;else if(l>0)s=s.U;else return s}return s||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(s,a){let l=s.o;if(l===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return l.u=a,!0;if(l===this.h.U)return this.v(l.B().u,a)>0?(l.u=a,!0):!1;if(l===this.h.W)return this.v(l.L().u,a)<0?(l.u=a,!0):!1;let c=l.L().u;if(this.v(c,a)>=0)return!1;let u=l.B().u;return this.v(u,a)<=0?!1:(l.u=a,!0)}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a=0,l=this;return this.oe(this.Y,function(c){return s===a?(l.V(c),!0):(a+=1,!1)}),this.i}eraseElementByKey(s){if(this.i===0)return!1;let a=this.I(this.Y,s);return a===this.h?!1:(this.V(a),!0)}eraseElementByIterator(s){let a=s.o;a===this.h&&(0,r.throwIteratorAccessError)();let l=a.W===void 0;return s.iteratorType===0?l&&s.next():(!l||a.U===void 0)&&s.next(),this.V(a),s}forEach(s){let a=0;for(let l of this)s(l,a++,this)}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a,l=0;for(let c of this){if(l===s){a=c;break}l+=1}return a}getHeight(){if(this.i===0)return 0;let s=function(a){return a?Math.max(s(a.U),s(a.W))+1:0};return s(this.Y)}},n=o;i.default=n}),Ds=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=wt(),t=kt(),r=class extends e.ContainerIterator{constructor(n,s,a){super(a),this.o=n,this.h=s,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,s=this.h.tt;if(n===this.h)return s?s.rt-1:0;let a=0;for(n.U&&(a+=n.U.rt);n!==s;){let l=n.tt;n===l.W&&(a+=1,l.U&&(a+=l.U.rt)),n=l}return a}},o=r;i.default=o}),Bu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o($s()),t=o(Ds()),r=kt();function o(l){return l&&l.t?l:{default:l}}var n=class Fc 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 Fc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(p){d.insert(p)})}*K(l){l!==void 0&&(yield*this.K(l.U),yield l.u,yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(l,c){return this.M(l,void 0,c)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}union(l){let c=this;return l.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=s;i.default=a}),Fu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o($s()),t=o(Ds()),r=kt();function o(l){return l&&l.t?l:{default:l}}var n=class qc 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 qc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(p){d.setElement(p[0],p[1])})}*K(l){l!==void 0&&(yield*this.K(l.U),yield[l.u,l.l],yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i===0)return;let l=this.h.U;return[l.u,l.l]}back(){if(this.i===0)return;let l=this.h.W;return[l.u,l.l]}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}setElement(l,c,u){return this.M(l,c,u)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}getElementByKey(l){return this.I(this.Y,l).l}union(l){let c=this;return l.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=s;i.default=a}),Us=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),Bs=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.HashContainerIterator=i.HashContainer=void 0;var e=wt(),t=o(Us()),r=kt();function o(a){return a&&a.t?a:{default:a}}var n=class extends e.ContainerIterator{constructor(a,l,c){super(c),this.o=a,this.h=l,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}};i.HashContainerIterator=n;var s=class extends e.Container{constructor(){super(),this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(a){let{L:l,B:c}=a;l.B=c,c.L=l,a===this.p&&(this.p=c),a===this._&&(this._=l),this.i-=1}M(a,l,c){c===void 0&&(c=(0,t.default)(a));let u;if(c){let d=a[this.HASH_TAG];if(d!==void 0)return this.H[d].l=l,this.i;Object.defineProperty(a,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:a,l,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[a];if(d)return d.l=l,this.i;u={u:a,l,L:this._,B:this.h},this.g[a]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(a,l){if(l===void 0&&(l=(0,t.default)(a)),l){let c=a[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[a]||this.h}clear(){let a=this.HASH_TAG;this.H.forEach(function(l){delete l.u[a]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(a,l){let c;if(l===void 0&&(l=(0,t.default)(a)),l){let u=a[this.HASH_TAG];if(u===void 0)return!1;delete a[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[a],c===void 0)return!1;delete this.g[a]}return this.V(c),!0}eraseElementByIterator(a){let l=a.o;return l===this.h&&(0,r.throwIteratorAccessError)(),this.V(l),a.next()}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let l=this.p;for(;a--;)l=l.B;return this.V(l),this.i}};i.HashContainer=s}),qu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Bs(),t=kt(),r=class Hc extends e.HashContainerIterator{constructor(a,l,c,u){super(a,l,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new Hc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.HashContainer{constructor(s=[]){super();let a=this;s.forEach(function(l){a.insert(l)})}begin(){return new r(this.p,this.h,this)}end(){return new r(this.h,this.h,this)}rBegin(){return new r(this._,this.h,this,1)}rEnd(){return new r(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(s,a){return this.M(s,void 0,a)}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a=this.p;for(;s--;)a=a.B;return a.u}find(s,a){let l=this.I(s,a);return new r(l,this.h,this)}forEach(s){let a=0,l=this.p;for(;l!==this.h;)s(l.u,a++,this),l=l.B}[Symbol.iterator](){return(function*(){let s=this.p;for(;s!==this.h;)yield s.u,s=s.B}).bind(this)()}},n=o;i.default=n}),Hu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Bs(),t=o(Us()),r=kt();function o(l){return l&&l.t?l:{default:l}}var n=class Wc 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 Wc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.HashContainer{constructor(l=[]){super();let c=this;l.forEach(function(u){c.setElement(u[0],u[1])})}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i!==0)return[this.p.u,this.p.l]}back(){if(this.i!==0)return[this._.u,this._.l]}setElement(l,c,u){return this.M(l,c,u)}getElementByKey(l,c){if(c===void 0&&(c=(0,t.default)(l)),c){let d=l[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[l];return u?u.l:void 0}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return[c.u,c.l]}find(l,c){let u=this.I(l,c);return new n(u,this.h,this)}forEach(l){let c=0,u=this.p;for(;u!==this.h;)l([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let l=this.p;for(;l!==this.h;)yield[l.u,l.l],l=l.B}).bind(this)()}},a=s;i.default=a}),Wu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),Object.defineProperty(i,"Deque",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(i,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(i,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(i,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(i,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(i,"OrderedSet",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(i,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(i,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(i,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(i,"Vector",{enumerable:!0,get:function(){return o.default}});var e=d(Mu()),t=d(Nu()),r=d(Ru()),o=d(ju()),n=d($u()),s=d(Du()),a=d(Bu()),l=d(Fu()),c=d(qu()),u=d(Hu());function d(p){return p&&p.t?p:{default:p}}}),zu=me((i,e)=>{le(),ue(),ce();var t=Wu().OrderedSet,r=vt()("number-allocator:trace"),o=vt()("number-allocator:error");function n(a,l){this.low=a,this.high=l}n.prototype.equals=function(a){return this.low===a.low&&this.high===a.high},n.prototype.compare=function(a){return this.low<a.low&&this.high<a.low?-1:a.low<this.low&&a.high<this.low?1:0};function s(a,l){if(!(this instanceof s))return new s(a,l);this.min=a,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}s.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},s.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let a=this.ss.begin(),l=a.pointer.low,c=a.pointer.high,u=l;return u+1<=c?this.ss.updateKeyByIterator(a,new n(l+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},s.prototype.use=function(a){let l=new n(a,a),c=this.ss.lowerBound(l);if(!c.equals(this.ss.end())){let u=c.pointer.low,d=c.pointer.high;return c.pointer.equals(l)?(this.ss.eraseElementByIterator(c),r("use():"+a),!0):u>a?!1:u===a?(this.ss.updateKeyByIterator(c,new n(u+1,d)),r("use():"+a),!0):d===a?(this.ss.updateKeyByIterator(c,new n(u,d-1)),r("use():"+a),!0):(this.ss.updateKeyByIterator(c,new n(a+1,d)),this.ss.insert(new n(u,a-1)),r("use():"+a),!0)}return r("use():failed"),!1},s.prototype.free=function(a){if(a<this.min||a>this.max){o("free():"+a+" is out of range");return}let l=new n(a,a),c=this.ss.upperBound(l);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(l);return}c.pre();let u=c.pointer.high;c.pointer.high+1===a?this.ss.updateKeyByIterator(c,new n(u,a)):this.ss.insert(l)}else if(c.equals(this.ss.begin()))if(a+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(a,u))}else this.ss.insert(l);else{let u=c.pointer.low,d=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,d))):this.ss.updateKeyByIterator(c,new n(p,a)):a+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(a,d))):this.ss.insert(l)}r("free():"+a)},s.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},s.prototype.intervalCount=function(){return this.ss.size()},s.prototype.dump=function(){console.log("length:"+this.ss.size());for(let a of this.ss)console.log(a)},e.exports=s}),Fs=me((i,e)=>{le(),ue(),ce();var t=zu();e.exports.NumberAllocator=t}),Vu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Lu(),t=Fs(),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 s=this.aliasToTopic.get(n);return s&&delete this.topicToAlias[s],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]}};i.default=r}),Ku=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(i,"__esModule",{value:!0});var t=Pr(),r=e(Vu()),o=Kt(),n=(s,a)=>{s.log("_handleConnack");let{options:l}=s,c=l.protocolVersion===5?a.reasonCode:a.returnCode;if(clearTimeout(s.connackTimer),delete s.topicAliasSend,a.properties){if(a.properties.topicAliasMaximum){if(a.properties.topicAliasMaximum>65535){s.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}a.properties.topicAliasMaximum>0&&(s.topicAliasSend=new r.default(a.properties.topicAliasMaximum))}a.properties.serverKeepAlive&&l.keepalive&&(l.keepalive=a.properties.serverKeepAlive),a.properties.maximumPacketSize&&(l.properties||(l.properties={}),l.properties.maximumPacketSize=a.properties.maximumPacketSize)}if(c===0)s.reconnecting=!1,s._onConnect(a);else if(c>0){let u=new o.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);s.emit("error",u),s.options.reconnectOnConnackError&&s._cleanUp(!0)}};i.default=n}),Gu=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(t,r,o)=>{t.log("handling pubrel packet");let n=typeof o<"u"?o:t.noop,{messageId:s}=r,a={cmd:"pubcomp",messageId:s};t.incomingStore.get(r,(l,c)=>{l?t._sendPacket(a,n):(t.emit("message",c.topic,c.payload,c),t.handleMessage(c,u=>{if(u)return n(u);t.incomingStore.del(c,t.noop),t._sendPacket(a,n)}))})};i.default=e}),Yu=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(i,"__esModule",{value:!0});var t=e(Cu()),r=e(Ou()),o=e(Ku()),n=e(Pr()),s=e(Gu()),a=(l,c,u)=>{let{options:d}=l;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<c.length)return l.emit("error",new Error(`exceeding packets size ${c.cmd}`)),l.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),l;switch(l.log("_handlePacket :: emitting packetreceive"),l.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(l,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":l.reschedulePing(),(0,n.default)(l,c),u();break;case"pubrel":l.reschedulePing(),(0,s.default)(l,c,u);break;case"connack":(0,o.default)(l,c),u();break;case"auth":l.reschedulePing(),(0,r.default)(l,c),u();break;case"pingresp":l.log("_handlePacket :: received pingresp"),l.reschedulePing(!0),u();break;case"disconnect":l.emit("disconnect",c),u();break;default:l.log("_handlePacket :: unknown command"),u();break}};i.default=a}),qs=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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(){}};i.default=e}),Ju=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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={}}};i.default=e}),Qu=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(i,"__esModule",{value:!0}),i.TypedEventEmitter=void 0;var t=e((Rt(),je(At))),r=Kt(),o=class{};i.TypedEventEmitter=o,(0,r.applyMixin)(o,t.default)}),Or=me((i,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}),Xu=me((i,e)=>{le(),ue(),ce();var t=Or().default;function r(o,n){if(t(o)!="object"||!o)return o;var s=o[Symbol.toPrimitive];if(s!==void 0){var a=s.call(o,n||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(o)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Zu=me((i,e)=>{le(),ue(),ce();var t=Or().default,r=Xu();function o(n){var s=r(n,"string");return t(s)=="symbol"?s:s+""}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),ed=me((i,e)=>{le(),ue(),ce();var t=Zu();function r(o,n,s){return(n=t(n))in o?Object.defineProperty(o,n,{value:s,enumerable:!0,configurable:!0,writable:!0}):o[n]=s,o}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),td=me((i,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}),rd=me((i,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 s,a,l,c,u=[],d=!0,p=!1;try{if(l=(n=n.call(r)).next,o===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(s=l.call(n)).done)&&(u.push(s.value),u.length!==o);d=!0);}catch(g){p=!0,a=g}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),nd=me((i,e)=>{le(),ue(),ce();function t(r,o){(o==null||o>r.length)&&(o=r.length);for(var n=0,s=Array(o);n<o;n++)s[n]=r[n];return s}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),id=me((i,e)=>{le(),ue(),ce();var t=nd();function r(o,n){if(o){if(typeof o=="string")return t(o,n);var s={}.toString.call(o).slice(8,-1);return s==="Object"&&o.constructor&&(s=o.constructor.name),s==="Map"||s==="Set"?Array.from(o):s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(o,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),od=me((i,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}),sd=me((i,e)=>{le(),ue(),ce();var t=td(),r=rd(),o=id(),n=od();function s(a,l){return t(a)||r(a,l)||o(a,l)||n()}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Hs=me((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(i,function(t){var r=function(g){return function(h){var b=g(h);return h.add(b),b}},o=function(g){return function(h,b){return g.set(h,b),b}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,s=536870912,a=s*2,l=function(g,h){return function(b){var y=h.get(b),w=y===void 0?b.size:y<a?y+1:0;if(!b.has(w))return g(b,w);if(b.size<s){for(;b.has(w);)w=Math.floor(Math.random()*a);return g(b,w)}if(b.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;b.has(w);)w=Math.floor(Math.random()*n);return g(b,w)}},c=new WeakMap,u=o(c),d=l(u,c),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),ad=me((i,e)=>{le(),ue(),ce();function t(o,n,s,a,l,c,u){try{var d=o[c](u),p=d.value}catch(g){return void s(g)}d.done?n(p):Promise.resolve(p).then(a,l)}function r(o){return function(){var n=this,s=arguments;return new Promise(function(a,l){var c=o.apply(n,s);function u(p){t(c,a,l,u,d,"next",p)}function d(p){t(c,a,l,u,d,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ws=me((i,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}),zs=me((i,e)=>{le(),ue(),ce();function t(r,o,n,s){var a=Object.defineProperty;try{a({},"",{})}catch{a=0}e.exports=t=function(l,c,u,d){function p(g,h){t(l,g,function(b){return this._invoke(g,h,b)})}c?a?a(l,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):l[c]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,o,n,s)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Vs=me((i,e)=>{le(),ue(),ce();var t=zs();function r(){var o,n,s=typeof Symbol=="function"?Symbol:{},a=s.iterator||"@@iterator",l=s.toStringTag||"@@toStringTag";function c(w,m,k,x){var v=m&&m.prototype instanceof d?m:d,S=Object.create(v.prototype);return t(S,"_invoke",(function(E,I,P){var L,$,T,q=0,F=P||[],D=!1,oe={p:0,n:0,v:o,a:j,f:j.bind(o,4),d:function(W,re){return L=W,$=0,T=o,oe.n=re,u}};function j(W,re){for($=W,T=re,n=0;!D&&q&&!U&&n<F.length;n++){var U,Q=F[n],O=oe.p,J=Q[2];W>3?(U=J===re)&&(T=Q[($=Q[4])?5:($=3,3)],Q[4]=Q[5]=o):Q[0]<=O&&((U=W<2&&O<Q[1])?($=0,oe.v=re,oe.n=Q[1]):O<J&&(U=W<3||Q[0]>re||re>J)&&(Q[4]=W,Q[5]=re,oe.n=J,$=0))}if(U||W>1)return u;throw D=!0,re}return function(W,re,U){if(q>1)throw TypeError("Generator is already running");for(D&&re===1&&j(re,U),$=re,T=U;(n=$<2?o:T)||!D;){L||($?$<3?($>1&&(oe.n=-1),j($,T)):oe.n=T:oe.v=T);try{if(q=2,L){if($||(W="next"),n=L[W]){if(!(n=n.call(L,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,$<2&&($=0)}else $===1&&(n=L.return)&&n.call(L),$<2&&(T=TypeError("The iterator does not provide a '"+W+"' method"),$=1);L=o}else if((n=(D=oe.n<0)?T:E.call(I,oe))!==u)break}catch(Q){L=o,$=1,T=Q}finally{q=1}}return{value:n,done:D}}})(w,k,x),!0),S}var u={};function d(){}function p(){}function g(){}n=Object.getPrototypeOf;var h=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),b=g.prototype=d.prototype=Object.create(h);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,l,"GeneratorFunction")),w.prototype=Object.create(b),w}return p.prototype=g,t(b,"constructor",g),t(g,"constructor",p),p.displayName="GeneratorFunction",t(g,l,"GeneratorFunction"),t(b),t(b,l,"Generator"),t(b,a,function(){return this}),t(b,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ks=me((i,e)=>{le(),ue(),ce();var t=Ws(),r=zs();function o(n,s){function a(c,u,d,p){try{var g=n[c](u),h=g.value;return h instanceof t?s.resolve(h.v).then(function(b){a("next",b,d,p)},function(b){a("throw",b,d,p)}):s.resolve(h).then(function(b){g.value=b,d(g)},function(b){return a("throw",b,d,p)})}catch(b){p(b)}}var l;this.next||(r(o.prototype),r(o.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function p(){return new s(function(g,h){a(c,d,g,h)})}return l=l?l.then(p,p):p()},!0)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Gs=me((i,e)=>{le(),ue(),ce();var t=Vs(),r=Ks();function o(n,s,a,l,c){return new r(t().w(n,s,a,l),c||Promise)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),ld=me((i,e)=>{le(),ue(),ce();var t=Gs();function r(o,n,s,a,l){var c=t(o,n,s,a,l);return c.next().then(function(u){return u.done?u.value:c.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),cd=me((i,e)=>{le(),ue(),ce();function t(r){var o=Object(r),n=[];for(var s in o)n.unshift(s);return function a(){for(;n.length;)if((s=n.pop())in o)return a.value=s,a.done=!1,a;return a.done=!0,a}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ud=me((i,e)=>{le(),ue(),ce();var t=Or().default;function r(o){if(o!=null){var n=o[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],s=0;if(n)return n.call(o);if(typeof o.next=="function")return o;if(!isNaN(o.length))return{next:function(){return o&&s>=o.length&&(o=void 0),{value:o&&o[s++],done:!o}}}}throw new TypeError(t(o)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),dd=me((i,e)=>{le(),ue(),ce();var t=Ws(),r=Vs(),o=ld(),n=Gs(),s=Ks(),a=cd(),l=ud();function c(){var u=r(),d=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var h={throw:1,return:2,break:3,continue:3};function b(y){var w,m;return function(k){w||(w={stop:function(){return m(k.a,2)},catch:function(){return k.v},abrupt:function(x,v){return m(k.a,h[x],v)},delegateYield:function(x,v,S){return w.resultName=v,m(k.d,l(x),S)},finish:function(x){return m(k.f,x)}},m=function(x,v,S){k.p=w.prev,k.n=w.next;try{return x(v,S)}finally{w.next=k.n}}),w.resultName&&(w[w.resultName]=k.v,w.resultName=void 0),w.sent=k.v,w.next=k.n;try{return y.call(this,w)}finally{k.p=w.prev,k.n=w.next}}}return(e.exports=c=function(){return{wrap:function(y,w,m,k){return u.w(b(y),w,m,k&&k.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:s,async:function(y,w,m,k,x){return(g(w)?n:o)(b(y),w,m,k,x)},keys:a,values:l}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),hd=me((i,e)=>{le(),ue(),ce();var t=dd()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),pd=me((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,ed(),sd(),Hs(),ad(),hd()):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))})(i,function(t,r,o,n,s,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),x.push.apply(x,v)}return x}function d(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%2?u(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):u(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var p=function(m){return d(d({},m),{},{connect:function(k){var x=k.call;return s(a.mark(function v(){var S,E,I,P;return a.wrap(function(L){for(;;)switch(L.prev=L.next){case 0:return S=new MessageChannel,E=S.port1,I=S.port2,L.next=1,x("connect",{port:E},[E]);case 1:return P=L.sent,c.set(I,P),L.abrupt("return",I);case 2:case"end":return L.stop()}},v)}))},disconnect:function(k){var x=k.call;return(function(){var v=s(a.mark(function S(E){var I;return a.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:if(I=c.get(E),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()}},S)}));return function(S){return v.apply(this,arguments)}})()},isSupported:function(k){var x=k.call;return function(){return x("isSupported")}}})};function g(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),x.push.apply(x,v)}return x}function h(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%2?g(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):g(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var b=new WeakMap,y=function(m){if(b.has(m))return b.get(m);var k=new Map;return b.set(m,k),k},w=function(m){var k=p(m);return function(x){var v=y(x);x.addEventListener("message",function(F){var D=F.data,oe=D.id;if(oe!==null&&v.has(oe)){var j=v.get(oe),W=j.reject,re=j.resolve;v.delete(oe),D.error===void 0?re(D.result):W(new Error(D.error.message))}}),l(x)&&x.start();for(var S=function(F){var D=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(j,W){var re=n.generateUniqueNumber(v);v.set(re,{reject:W,resolve:j}),D===null?x.postMessage({id:re,method:F},oe):x.postMessage({id:re,method:F,params:D},oe)})},E=function(F,D){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:F,params:D},oe)},I={},P=0,L=Object.entries(k);P<L.length;P++){var $=o(L[P],2),T=$[0],q=$[1];I=h(h({},I),{},r({},T,q({call:S,notify:E})))}return h({},I)}};t.createBroker=w})}),fd=me((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Or(),pd(),Hs()):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))})(i,function(t,r,o,n){var s=new Map([[0,null]]),a=new Map([[0,null]]),l=o.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(s.get(p))==="symbol"&&(s.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){s.delete(p)}))}},clearTimeout:function(u){var d=u.call;return function(p){r(a.get(p))==="symbol"&&(a.set(p,null),d("clear",{timerId:p,timerType:"timeout"}).then(function(){a.delete(p)}))}},setInterval:function(u){var d=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length,b=new Array(h>2?h-2:0),y=2;y<h;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(s);s.set(m,w);var k=function(){return d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=s.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===w&&(p.apply(void 0,b),s.get(m)===w&&k())})};return k(),m}},setTimeout:function(u){var d=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length,b=new Array(h>2?h-2:0),y=2;y<h;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(a);return a.set(m,w),d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var k=a.get(m);if(k===void 0)throw new Error("The timer is in an undefined state.");k===w&&(a.delete(m),p.apply(void 0,b))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),md=me((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,fd()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(i,function(t,r){var o=function(d,p){var g=null;return function(){if(g!==null)return g;var h=new Blob([p],{type:"application/javascript; charset=utf-8"}),b=URL.createObjectURL(h);return g=d(b),setTimeout(function(){return URL.revokeObjectURL(b)}),g}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,s=o(r.load,n),a=function(d){return s().clearInterval(d)},l=function(d){return s().clearTimeout(d)},c=function(){var d;return(d=s()).setInterval.apply(d,arguments)},u=function(){var d;return(d=s()).setTimeout.apply(d,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Lr=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.isReactNativeBrowser=i.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&De?.versions?!Object.prototype.hasOwnProperty.call(De.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();i.isWebWorker=t(),i.isReactNativeBrowser=r(),i.default=o}),gd=me(i=>{le(),ue(),ce();var e=i&&i.__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=i&&i.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=i&&i.__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(i,"__esModule",{value:!0});var o=md(),n=r(Lr()),s={set:o.setInterval,clear:o.clearInterval},a={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return a;case"worker":return s;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?s:a}};i.default=l}),Ys=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(i,"__esModule",{value:!0});var t=e(gd()),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)}};i.default=r}),Li=me(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(v,S,E,I){I===void 0&&(I=E);var P=Object.getOwnPropertyDescriptor(S,E);(!P||("get"in P?!S.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return S[E]}}),Object.defineProperty(v,I,P)}:function(v,S,E,I){I===void 0&&(I=E),v[I]=S[E]}),t=i&&i.__setModuleDefault||(Object.create?function(v,S){Object.defineProperty(v,"default",{enumerable:!0,value:S})}:function(v,S){v.default=S}),r=i&&i.__importStar||(function(){var v=function(S){return v=Object.getOwnPropertyNames||function(E){var I=[];for(var P in E)Object.prototype.hasOwnProperty.call(E,P)&&(I[I.length]=P);return I},v(S)};return function(S){if(S&&S.__esModule)return S;var E={};if(S!=null)for(var I=v(S),P=0;P<I.length;P++)I[P]!=="default"&&e(E,S,I[P]);return t(E,S),E}})(),o=i&&i.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(i,"__esModule",{value:!0});var n=o(Au()),s=$t(),a=o(Tu()),l=o(vt()),c=r(Ns()),u=o(Rs()),d=o(Yu()),p=o(qs()),g=o(Ju()),h=Kt(),b=Qu(),y=o(Ys()),w=r(Lr()),m=globalThis.setImmediate||((...v)=>{let S=v.shift();(0,h.nextTick)(()=>{S(...v)})}),k={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},x=class Go extends b.TypedEventEmitter{static VERSION=h.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(S,E){super(),this.options=E||{};for(let I in k)typeof this.options[I]>"u"?this.options[I]=k[I]:this.options[I]=E[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",Go.VERSION),w.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",w.default?"browser":"node"),this.log("MqttClient :: options.protocol",E.protocol),this.log("MqttClient :: options.protocolVersion",E.protocolVersion),this.log("MqttClient :: options.username",E.username),this.log("MqttClient :: options.keepalive",E.keepalive),this.log("MqttClient :: options.reconnectPeriod",E.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",E.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",E.properties?E.properties.topicAliasMaximum:void 0),this.options.clientId=typeof E.clientId=="string"?E.clientId:Go.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=E.protocolVersion===5&&E.customHandleAcks?E.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=S,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new p.default:this.options.messageIdProvider,this.outgoingStore=E.outgoingStore||new u.default,this.incomingStore=E.incomingStore||new u.default,this.queueQoSZero=E.queueQoSZero===void 0?!0:E.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,E.properties&&E.properties.topicAliasMaximum>0&&(E.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new g.default(E.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,P=()=>{let L=I.shift();this.log("deliver :: entry %o",L);let $=null;if(!L){this._resubscribe();return}$=L.packet,this.log("deliver :: call _sendPacket for %o",$);let T=!0;$.messageId&&$.messageId!==0&&(this.messageIdProvider.register($.messageId)||(T=!1)),T?this._sendPacket($,q=>{L.cb&&L.cb(q),P()}):(this.log("messageId: %d has already used. The message is skipped and removed.",$.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(S,E){E()}handleMessage(S,E){E()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let S=new s.Writable,E=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),E.on("packet",F=>{this.log("parser :: on packet push to packets array."),P.push(F)});let L=()=>{this.log("work :: getting next packet in queue");let F=P.shift();if(F)this.log("work :: packet pulled from queue"),(0,d.default)(this,F,$);else{this.log("work :: no packets in queue");let D=I;I=null,this.log("work :: done flag is %s",!!D),D&&D()}},$=()=>{if(P.length)(0,h.nextTick)(L);else{let F=I;I=null,F()}};S._write=(F,D,oe)=>{I=oe,this.log("writable stream :: parsing buffer"),E.parse(F),L()};let T=F=>{this.log("streamErrorHandler :: error",F.message),F.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",F)):this.noop(F)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(S),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),E.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 F={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(F)}}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(S,E,I,P){this.log("publish :: message `%s` to topic `%s`",E,S);let{options:L}=this;typeof I=="function"&&(P=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:$,retain:T,dup:q,properties:F,cbStorePut:D}=I;if(this._checkDisconnecting(P))return this;let oe=()=>{let j=0;if(($===1||$===2)&&(j=this._nextId(),j===null))return this.log("No messageId left"),!1;let W={cmd:"publish",topic:S,payload:E,qos:$,retain:T,messageId:j,dup:q};switch(L.protocolVersion===5&&(W.properties=F),this.log("publish :: qos",$),$){case 1:case 2:this.outgoing[W.messageId]={volatile:!1,cb:P||this.noop},this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,void 0,D);break;default:this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,P,D);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!oe())&&this._storeProcessingQueue.push({invoke:oe,cbStorePut:I.cbStorePut,callback:P}),this}publishAsync(S,E,I){return new Promise((P,L)=>{this.publish(S,E,I,($,T)=>{$?L($):P(T)})})}subscribe(S,E,I){let P=this.options.protocolVersion;typeof E=="function"&&(I=E),I=I||this.noop;let L=!1,$=[];typeof S=="string"?(S=[S],$=S):Array.isArray(S)?$=S:typeof S=="object"&&(L=S.resubscribe,delete S.resubscribe,$=Object.keys(S));let T=c.validateTopics($);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),E={...q,...E};let{properties:F}=E,D=[],oe=(re,U)=>{if(U=U||E,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<U.qos||L){let Q={topic:re,qos:U.qos};P===5&&(Q.nl=U.nl,Q.rap=U.rap,Q.rh=U.rh,Q.properties=F),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",Q.topic,Q.qos),D.push(Q)}};if(Array.isArray(S)?S.forEach(re=>{this.log("subscribe: array topic %s",re),oe(re)}):Object.keys(S).forEach(re=>{this.log("subscribe: object topic %s, %o",re,S[re]),oe(re,S[re])}),!D.length)return I(null,[]),this;let j=(re,U)=>{let Q={cmd:"subscribe",subscriptions:re,messageId:U};if(F&&(Q.properties=F),this.options.resubscribe){this.log("subscribe :: resubscribe true");let J=[];re.forEach(pe=>{if(this.options.reconnectPeriod>0){let ee={qos:pe.qos};P===5&&(ee.nl=pe.nl||!1,ee.rap=pe.rap||!1,ee.rh=pe.rh||0,ee.properties=pe.properties),this._resubscribeTopics[pe.topic]=ee,J.push(pe.topic)}}),this.messageIdToTopic[Q.messageId]=J}let O=new Promise((J,pe)=>{this.outgoing[Q.messageId]={volatile:!0,cb(ee,ve){if(!ee){let{granted:G}=ve;for(let R=0;R<G.length;R+=1)re[R].qos=G[R]}ee?pe(new h.ErrorWithSubackPacket(ee.message,ve)):J(ve)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Q),O},W=()=>{let re=this.options.subscribeBatchSize??D.length,U=[];for(let Q=0;Q<D.length;Q+=re){let O=D.slice(Q,Q+re),J=this._nextId();if(J===null)return this.log("No messageId left"),!1;U.push(j(O,J))}return Promise.all(U).then(Q=>{I(null,D,Q.at(-1))}).catch(Q=>{I(Q,D,Q.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!W())&&this._storeProcessingQueue.push({invoke:W,callback:I}),this}subscribeAsync(S,E){return new Promise((I,P)=>{this.subscribe(S,E,(L,$)=>{L?P(L):I($)})})}unsubscribe(S,E,I){typeof S=="string"&&(S=[S]),typeof E=="function"&&(I=E),I=I||this.noop;let P=c.validateTopics(S);if(P!==null)return m(I,new Error(`Invalid topic ${P}`)),this;if(this._checkDisconnecting(I))return this;let L=()=>{let $=this._nextId();if($===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:$,unsubscriptions:[]};return typeof S=="string"?T.unsubscriptions=[S]:Array.isArray(S)&&(T.unsubscriptions=S),this.options.resubscribe&&T.unsubscriptions.forEach(q=>{delete this._resubscribeTopics[q]}),typeof E=="object"&&E.properties&&(T.properties=E.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||!L())&&this._storeProcessingQueue.push({invoke:L,callback:I}),this}unsubscribeAsync(S,E){return new Promise((I,P)=>{this.unsubscribe(S,E,(L,$)=>{L?P(L):I($)})})}end(S,E,I){this.log("end :: (%s)",this.options.clientId),(S==null||typeof S!="boolean")&&(I=I||E,E=S,S=!1),typeof E!="object"&&(I=I||E,E=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($=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let q=$||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)},L=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,S),this._cleanUp(S,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,h.nextTick)(P)},E)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!S&&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,L,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),L()),this)}endAsync(S,E){return new Promise((I,P)=>{this.end(S,E,L=>{L?P(L):I()})})}removeOutgoingMessage(S){if(this.outgoing[S]){let{cb:E}=this.outgoing[S];this._removeOutgoingAndStoreMessage(S,()=>{E(new Error("Message removed"))})}return this}reconnect(S){this.log("client reconnect");let E=()=>{S?(this.options.incomingStore=S.incomingStore,this.options.outgoingStore=S.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=E:E(),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(S=>{this.outgoing[S].volatile&&typeof this.outgoing[S].cb=="function"&&(this.outgoing[S].cb(new Error("Connection closed")),delete this.outgoing[S])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(S=>{typeof this.outgoing[S].cb=="function"&&(this.outgoing[S].cb(new Error("Connection closed")),delete this.outgoing[S])}))}_removeTopicAliasAndRecoverTopicName(S){let E;S.properties&&(E=S.properties.topicAlias);let I=S.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",E,I),I.length===0){if(typeof E>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(E),typeof I>"u")return new Error("Unregistered Topic Alias");S.topic=I}E&&delete S.properties.topicAlias}_checkDisconnecting(S){return this.disconnecting&&(S&&S!==this.noop?S(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(S,E,I={}){if(E&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",E)),this.log("_cleanUp :: forced? %s",S),S)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(),E&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",E),E())}_storeAndSend(S,E,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",S.cmd);let P=S,L;if(P.cmd==="publish"&&(P=(0,a.default)(S),L=this._removeTopicAliasAndRecoverTopicName(P),L))return E&&E(L);this.outgoingStore.put(P,$=>{if($)return E&&E($);I(),this._writePacket(S,E)})}_applyTopicAlias(S){if(this.options.protocolVersion===5&&S.cmd==="publish"){let E;S.properties&&(E=S.properties.topicAlias);let I=S.topic.toString();if(this.topicAliasSend)if(E){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,E),!this.topicAliasSend.put(I,E)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,E),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(E=this.topicAliasSend.getAliasByTopic(I),E?(S.topic="",S.properties={...S.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,E)):(E=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,E),S.properties={...S.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,E))):this.options.autoUseTopicAlias&&(E=this.topicAliasSend.getAliasByTopic(I),E&&(S.topic="",S.properties={...S.properties,topicAlias:E},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,E))));else if(E)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,E),new Error("Sending Topic Alias out of range")}}_noop(S){this.log("noop ::",S)}_writePacket(S,E){this.log("_writePacket :: packet: %O",S),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",S),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(S,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&E&&E!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",E)):E&&(this.log("_writePacket :: invoking cb"),E())}_sendPacket(S,E,I,P){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,E=E||this.noop;let L=this._applyTopicAlias(S);if(L){E(L);return}if(!this.connected){if(S.cmd==="auth"){this._writePacket(S,E);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(S,E,I);return}if(P){this._writePacket(S,E);return}switch(S.cmd){case"publish":break;case"pubrel":this._storeAndSend(S,E,I);return;default:this._writePacket(S,E);return}switch(S.qos){case 2:case 1:this._storeAndSend(S,E,I);break;default:this._writePacket(S,E);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(S,E,I){this.log("_storePacket :: packet: %o",S),this.log("_storePacket :: cb? %s",!!E),I=I||this.noop;let P=S;if(P.cmd==="publish"){P=(0,a.default)(S);let $=this._removeTopicAliasAndRecoverTopicName(P);if($)return E&&E($)}let L=P.qos||0;L===0&&this.queueQoSZero||P.cmd!=="publish"?this.queue.push({packet:P,cb:E}):L>0?(E=this.outgoing[P.messageId]?this.outgoing[P.messageId].cb:null,this.outgoingStore.put(P,$=>{if($)return E&&E($);I()})):E&&E(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(S=!1){this.keepaliveManager&&this.options.keepalive&&(S||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 S=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&S.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let E=0;E<S.length;E++){let I={};I[S[E]]=this._resubscribeTopics[S[E]],I.resubscribe=!0,this.subscribe(I,{properties:I[S[E]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(S){if(this.disconnected){this.emit("connect",S);return}this.connackPacket=S,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let E=()=>{let I=this.outgoingStore.createStream(),P=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),L()},L=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",P),I.on("error",T=>{L(),this._flushStoreProcessingQueue(),this.removeListener("close",P),this.emit("error",T)});let $=()=>{if(!I)return;let T=I.read(1),q;if(!T){I.once("readable",$);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){$();return}!this.disconnecting&&!this.reconnectTimer?(q=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(F,D){q&&q(F,D),$()}},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?(L(),this._invokeAllStoreProcessingQueue(),this.emit("connect",S)):E()}),$()};E()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let S=this._storeProcessingQueue[0];if(S&&S.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let S of this._storeProcessingQueue)S.cbStorePut&&S.cbStorePut(new Error("Connection closed")),S.callback&&S.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(S,E){delete this.outgoing[S],this.outgoingStore.del({messageId:S},(I,P)=>{E(I,P),this.messageIdProvider.deallocate(S),this._invokeStoreProcessingQueue()})}};i.default=x}),bd=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Fs(),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()}};i.default=t});function yd(){if(Mi)return Mr;Mi=!0;let i=2147483647,e=36,t=1,r=26,o=38,n=700,s=72,a=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},g=e-t,h=Math.floor,b=String.fromCharCode;function y(L){throw new RangeError(p[L])}function w(L,$){let T=[],q=L.length;for(;q--;)T[q]=$(L[q]);return T}function m(L,$){let T=L.split("@"),q="";T.length>1&&(q=T[0]+"@",L=T[1]),L=L.replace(d,".");let F=L.split("."),D=w(F,$).join(".");return q+D}function k(L){let $=[],T=0,q=L.length;for(;T<q;){let F=L.charCodeAt(T++);if(F>=55296&&F<=56319&&T<q){let D=L.charCodeAt(T++);(D&64512)==56320?$.push(((F&1023)<<10)+(D&1023)+65536):($.push(F),T--)}else $.push(F)}return $}let x=L=>String.fromCodePoint(...L),v=function(L){return L>=48&&L<58?26+(L-48):L>=65&&L<91?L-65:L>=97&&L<123?L-97:e},S=function(L,$){return L+22+75*(L<26)-(($!=0)<<5)},E=function(L,$,T){let q=0;for(L=T?h(L/n):L>>1,L+=h(L/$);L>g*r>>1;q+=e)L=h(L/g);return h(q+(g+1)*L/(L+o))},I=function(L){let $=[],T=L.length,q=0,F=a,D=s,oe=L.lastIndexOf(l);oe<0&&(oe=0);for(let j=0;j<oe;++j)L.charCodeAt(j)>=128&&y("not-basic"),$.push(L.charCodeAt(j));for(let j=oe>0?oe+1:0;j<T;){let W=q;for(let U=1,Q=e;;Q+=e){j>=T&&y("invalid-input");let O=v(L.charCodeAt(j++));O>=e&&y("invalid-input"),O>h((i-q)/U)&&y("overflow"),q+=O*U;let J=Q<=D?t:Q>=D+r?r:Q-D;if(O<J)break;let pe=e-J;U>h(i/pe)&&y("overflow"),U*=pe}let re=$.length+1;D=E(q-W,re,W==0),h(q/re)>i-F&&y("overflow"),F+=h(q/re),q%=re,$.splice(q++,0,F)}return String.fromCodePoint(...$)},P=function(L){let $=[];L=k(L);let T=L.length,q=a,F=0,D=s;for(let W of L)W<128&&$.push(b(W));let oe=$.length,j=oe;for(oe&&$.push(l);j<T;){let W=i;for(let U of L)U>=q&&U<W&&(W=U);let re=j+1;W-q>h((i-F)/re)&&y("overflow"),F+=(W-q)*re,q=W;for(let U of L)if(U<q&&++F>i&&y("overflow"),U===q){let Q=F;for(let O=e;;O+=e){let J=O<=D?t:O>=D+r?r:O-D;if(Q<J)break;let pe=Q-J,ee=e-J;$.push(b(S(J+pe%ee,0))),Q=h(pe/ee)}$.push(b(S(Q,0))),D=E(F,re,j===oe),F=0,++j}++F,++q}return $.join("")};return Mr={version:"2.3.1",ucs2:{decode:k,encode:x},decode:I,encode:P,toASCII:function(L){return m(L,function($){return u.test($)?"xn--"+P($):$})},toUnicode:function(L){return m(L,function($){return c.test($)?I($.slice(4).toLowerCase()):$})}},Mr}var Mr,Mi,Tt,vd=Qe(()=>{le(),ue(),ce(),Mr={},Mi=!1,Tt=yd(),Tt.decode,Tt.encode,Tt.toASCII,Tt.toUnicode,Tt.ucs2,Tt.version});function wd(){return $i||($i=!0,ji=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var i={},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;i[e]=r;for(e in i)return!1;if(typeof Object.keys=="function"&&Object.keys(i).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(i).length!==0)return!1;var o=Object.getOwnPropertySymbols(i);if(o.length!==1||o[0]!==e||!Object.prototype.propertyIsEnumerable.call(i,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(i,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),ji}function kd(){return Ui||(Ui=!0,Di=Error),Di}function _d(){return Fi||(Fi=!0,Bi=EvalError),Bi}function xd(){return Hi||(Hi=!0,qi=RangeError),qi}function Sd(){return zi||(zi=!0,Wi=ReferenceError),Wi}function Js(){return Ki||(Ki=!0,Vi=SyntaxError),Vi}function cr(){return Yi||(Yi=!0,Gi=TypeError),Gi}function Ed(){return Qi||(Qi=!0,Ji=URIError),Ji}function Ad(){if(Xi)return Nr;Xi=!0;var i=typeof Symbol<"u"&&Symbol,e=wd();return Nr=function(){return typeof i!="function"||typeof Symbol!="function"||typeof i("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Nr}function Id(){if(Zi)return Rr;Zi=!0;var i={__proto__:null,foo:{}},e=Object;return Rr=function(){return{__proto__:i}.foo===i.foo&&!(i instanceof e)},Rr}function Td(){if(eo)return jr;eo=!0;var i="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",o=function(a,l){for(var c=[],u=0;u<a.length;u+=1)c[u]=a[u];for(var d=0;d<l.length;d+=1)c[d+a.length]=l[d];return c},n=function(a,l){for(var c=[],u=l,d=0;u<a.length;u+=1,d+=1)c[d]=a[u];return c},s=function(a,l){for(var c="",u=0;u<a.length;u+=1)c+=a[u],u+1<a.length&&(c+=l);return c};return jr=function(a){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(i+l);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var y=l.apply(this,o(c,arguments));return Object(y)===y?y:this}return l.apply(a,o(c,arguments))},p=t(0,l.length-c.length),g=[],h=0;h<p;h++)g[h]="$"+h;if(u=Function("binder","return function ("+s(g,",")+"){ return binder.apply(this,arguments); }")(d),l.prototype){var b=function(){};b.prototype=l.prototype,u.prototype=new b,b.prototype=null}return u},jr}function Ni(){if(to)return $r;to=!0;var i=Td();return $r=Function.prototype.bind||i,$r}function Cd(){if(ro)return Dr;ro=!0;var i=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=Ni();return Dr=t.call(i,e),Dr}function Gt(){if(no)return Ur;no=!0;var i,e=kd(),t=_d(),r=xd(),o=Sd(),n=Js(),s=cr(),a=Ed(),l=Function,c=function(j){try{return l('"use strict"; return ('+j+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new s},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=Ad()(),h=Id()(),b=Object.getPrototypeOf||(h?function(j){return j.__proto__}:null),y={},w=typeof Uint8Array>"u"||!b?i:b(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?i:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?i:ArrayBuffer,"%ArrayIteratorPrototype%":g&&b?b([][Symbol.iterator]()):i,"%AsyncFromSyncIteratorPrototype%":i,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":typeof Atomics>"u"?i:Atomics,"%BigInt%":typeof BigInt>"u"?i:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?i:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?i:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?i:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?i:Float32Array,"%Float64Array%":typeof Float64Array>"u"?i:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?i:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":y,"%Int8Array%":typeof Int8Array>"u"?i:Int8Array,"%Int16Array%":typeof Int16Array>"u"?i:Int16Array,"%Int32Array%":typeof Int32Array>"u"?i:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&b?b(b([][Symbol.iterator]())):i,"%JSON%":typeof JSON=="object"?JSON:i,"%Map%":typeof Map>"u"?i:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!b?i:b(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?i:Promise,"%Proxy%":typeof Proxy>"u"?i:Proxy,"%RangeError%":r,"%ReferenceError%":o,"%Reflect%":typeof Reflect>"u"?i:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?i:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!b?i:b(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?i:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&b?b(""[Symbol.iterator]()):i,"%Symbol%":g?Symbol:i,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":w,"%TypeError%":s,"%Uint8Array%":typeof Uint8Array>"u"?i:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?i:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?i:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?i:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?i:WeakMap,"%WeakRef%":typeof WeakRef>"u"?i:WeakRef,"%WeakSet%":typeof WeakSet>"u"?i:WeakSet};if(b)try{null.error}catch(j){var k=b(b(j));m["%Error.prototype%"]=k}var x=function j(W){var re;if(W==="%AsyncFunction%")re=c("async function () {}");else if(W==="%GeneratorFunction%")re=c("function* () {}");else if(W==="%AsyncGeneratorFunction%")re=c("async function* () {}");else if(W==="%AsyncGenerator%"){var U=j("%AsyncGeneratorFunction%");U&&(re=U.prototype)}else if(W==="%AsyncIteratorPrototype%"){var Q=j("%AsyncGenerator%");Q&&b&&(re=b(Q.prototype))}return m[W]=re,re},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},S=Ni(),E=Cd(),I=S.call(Function.call,Array.prototype.concat),P=S.call(Function.apply,Array.prototype.splice),L=S.call(Function.call,String.prototype.replace),$=S.call(Function.call,String.prototype.slice),T=S.call(Function.call,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,F=/\\(\\)?/g,D=function(j){var W=$(j,0,1),re=$(j,-1);if(W==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&W!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var U=[];return L(j,q,function(Q,O,J,pe){U[U.length]=J?L(pe,F,"$1"):O||Q}),U},oe=function(j,W){var re=j,U;if(E(v,re)&&(U=v[re],re="%"+U[0]+"%"),E(m,re)){var Q=m[re];if(Q===y&&(Q=x(re)),typeof Q>"u"&&!W)throw new s("intrinsic "+j+" exists, but is not available. Please file an issue!");return{alias:U,name:re,value:Q}}throw new n("intrinsic "+j+" does not exist!")};return Ur=function(j,W){if(typeof j!="string"||j.length===0)throw new s("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof W!="boolean")throw new s('"allowMissing" argument must be a boolean');if(T(/^%?[^%]*%?$/,j)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var re=D(j),U=re.length>0?re[0]:"",Q=oe("%"+U+"%",W),O=Q.name,J=Q.value,pe=!1,ee=Q.alias;ee&&(U=ee[0],P(re,I([0,1],ee)));for(var ve=1,G=!0;ve<re.length;ve+=1){var R=re[ve],ne=$(R,0,1),V=$(R,-1);if((ne==='"'||ne==="'"||ne==="`"||V==='"'||V==="'"||V==="`")&&ne!==V)throw new n("property names with quotes must have matching quotes");if((R==="constructor"||!G)&&(pe=!0),U+="."+R,O="%"+U+"%",E(m,O))J=m[O];else if(J!=null){if(!(R in J)){if(!W)throw new s("base intrinsic for "+j+" exists, but the property is not available.");return}if(u&&ve+1>=re.length){var Y=u(J,R);G=!!Y,G&&"get"in Y&&!("originalValue"in Y.get)?J=Y.get:J=J[R]}else G=E(J,R),J=J[R];G&&!pe&&(m[O]=J)}}return J},Ur}function Ri(){if(io)return Br;io=!0;var i=Gt(),e=i("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Br=e,Br}function Qs(){if(oo)return Fr;oo=!0;var i=Gt(),e=i("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Fr=e,Fr}function Pd(){if(so)return qr;so=!0;var i=Ri(),e=Js(),t=cr(),r=Qs();return qr=function(o,n,s){if(!o||typeof o!="object"&&typeof o!="function")throw new t("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new t("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new t("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new t("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new t("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new t("`loose`, if provided, must be a boolean");var a=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(o,n);if(i)i(o,n,{configurable:c===null&&d?d.configurable:!c,enumerable:a===null&&d?d.enumerable:!a,value:s,writable:l===null&&d?d.writable:!l});else if(u||!a&&!l&&!c)o[n]=s;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},qr}function Od(){if(ao)return Hr;ao=!0;var i=Ri(),e=function(){return!!i};return e.hasArrayLengthDefineBug=function(){if(!i)return null;try{return i([],"length",{value:1}).length!==1}catch{return!0}},Hr=e,Hr}function Ld(){if(lo)return Wr;lo=!0;var i=Gt(),e=Pd(),t=Od()(),r=Qs(),o=cr(),n=i("%Math.floor%");return Wr=function(s,a){if(typeof s!="function")throw new o("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new o("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in s&&r){var d=r(s,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!l)&&(t?e(s,"length",a,!0,!0):e(s,"length",a)),s},Wr}function Md(){if(co)return Yt;co=!0;var i=Ni(),e=Gt(),t=Ld(),r=cr(),o=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),s=e("%Reflect.apply%",!0)||i.call(n,o),a=Ri(),l=e("%Math.max%");Yt=function(u){if(typeof u!="function")throw new r("a function is required");var d=s(i,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return s(i,o,arguments)};return a?a(Yt,"apply",{value:c}):Yt.apply=c,Yt}function Nd(){if(uo)return zr;uo=!0;var i=Gt(),e=Md(),t=e(i("String.prototype.indexOf"));return zr=function(r,o){var n=i(r,!!o);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},zr}var ji,$i,Di,Ui,Bi,Fi,qi,Hi,Wi,zi,Vi,Ki,Gi,Yi,Ji,Qi,Nr,Xi,Rr,Zi,jr,eo,$r,to,Dr,ro,Ur,no,Br,io,Fr,oo,qr,so,Hr,ao,Wr,lo,Yt,co,zr,uo,Rd=Qe(()=>{le(),ue(),ce(),ji={},$i=!1,Di={},Ui=!1,Bi={},Fi=!1,qi={},Hi=!1,Wi={},zi=!1,Vi={},Ki=!1,Gi={},Yi=!1,Ji={},Qi=!1,Nr={},Xi=!1,Rr={},Zi=!1,jr={},eo=!1,$r={},to=!1,Dr={},ro=!1,Ur={},no=!1,Br={},io=!1,Fr={},oo=!1,qr={},so=!1,Hr={},ao=!1,Wr={},lo=!1,Yt={},co=!1,zr={},uo=!1});function ho(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function jd(){!Dt||!Ut||(Dt=!1,Ut.length?st=Ut.concat(st):ur=-1,st.length&&Xs())}function Xs(){if(!Dt){var i=setTimeout(jd,0);Dt=!0;for(var e=st.length;e;){for(Ut=st,st=[];++ur<e;)Ut&&Ut[ur].run();ur=-1,e=st.length}Ut=null,Dt=!1,clearTimeout(i)}}function $d(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];st.push(new Zs(i,e)),st.length===1&&!Dt&&setTimeout(Xs,0)}function Zs(i,e){this.fun=i,this.array=e}function ze(){}function Dd(i){ho("_linkedBinding")}function Ud(i){ho("dlopen")}function Bd(){return[]}function Fd(){return[]}function qd(i,e){if(!i)throw new Error(e||"assertion error")}function Hd(){return!1}function Wd(){return _t.now()/1e3}function po(i){var e=Math.floor((Date.now()-_t.now())*.001),t=_t.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return i&&(r=r-i[0],o=o-i[1],o<0&&(r--,o+=Kr)),[r,o]}function Ct(){return mo}function zd(i){return[]}var st,Dt,Ut,ur,ea,ta,ra,na,ia,oa,sa,aa,la,ca,ua,da,ha,pa,fa,ma,ga,ba,ya,va,wa,Vr,ka,_a,xa,Sa,Ea,Aa,Ia,Ta,Ca,Pa,Oa,La,Ma,Na,Ra,ja,$a,Da,Ua,Ba,Fa,qa,Ha,Wa,za,_t,fo,Kr,Va,Ka,Ga,Ya,Ja,Qa,Xa,Za,el,tl,rl,mo,nl=Qe(()=>{le(),ue(),ce(),st=[],Dt=!1,ur=-1,Zs.prototype.run=function(){this.fun.apply(null,this.array)},ea="browser",ta="x64",ra="browser",na={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},ia=["/usr/bin/node"],oa=[],sa="v16.8.0",aa={},la=function(i,e){console.warn((e?e+": ":"")+i)},ca=function(i){ho("binding")},ua=function(i){return 0},da=function(){return"/"},ha=function(i){},pa={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},fa=ze,ma=[],ga={},ba=!1,ya={},va=ze,wa=ze,Vr=function(){return{}},ka=Vr,_a=Vr,xa=ze,Sa=ze,Ea=ze,Aa={},Ia={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Ta=ze,Ca=ze,Pa=ze,Oa=ze,La=ze,Ma=ze,Na=ze,Ra=void 0,ja=void 0,$a=void 0,Da=ze,Ua=2,Ba=1,Fa="/bin/usr/node",qa=9229,Ha="node",Wa=[],za=ze,_t={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},_t.now===void 0&&(fo=Date.now(),_t.timing&&_t.timing.navigationStart&&(fo=_t.timing.navigationStart),_t.now=()=>Date.now()-fo),Kr=1e9,po.bigint=function(i){var e=po(i);return typeof BigInt>"u"?e[0]*Kr+e[1]:BigInt(e[0]*Kr)+BigInt(e[1])},Va=10,Ka={},Ga=0,Ya=Ct,Ja=Ct,Qa=Ct,Xa=Ct,Za=Ct,el=ze,tl=Ct,rl=Ct,mo={version:sa,versions:aa,arch:ta,platform:ra,release:pa,_rawDebug:fa,moduleLoadList:ma,binding:ca,_linkedBinding:Dd,_events:Ka,_eventsCount:Ga,_maxListeners:Va,on:Ct,addListener:Ya,once:Ja,off:Qa,removeListener:Xa,removeAllListeners:Za,emit:el,prependListener:tl,prependOnceListener:rl,listeners:zd,domain:ga,_exiting:ba,config:ya,dlopen:Ud,uptime:Wd,_getActiveRequests:Bd,_getActiveHandles:Fd,reallyExit:va,_kill:wa,cpuUsage:Vr,resourceUsage:ka,memoryUsage:_a,kill:xa,exit:Sa,openStdin:Ea,allowedNodeEnvironmentFlags:Aa,assert:qd,features:Ia,_fatalExceptions:Ta,setUncaughtExceptionCaptureCallback:Ca,hasUncaughtExceptionCaptureCallback:Hd,emitWarning:la,nextTick:$d,_tickCallback:Pa,_debugProcess:Oa,_debugEnd:La,_startProfilerIdleNotifier:Ma,_stopProfilerIdleNotifier:Na,stdout:Ra,stdin:$a,stderr:ja,abort:Da,umask:ua,chdir:ha,cwd:da,env:na,title:ea,argv:ia,execArgv:oa,pid:Ua,ppid:Ba,execPath:Fa,debugPort:qa,hrtime:po,argv0:Ha,_preload_modules:Wa,setSourceMapsEnabled:za}});function Vd(){if(go)return Gr;go=!0;var i=mo;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,s){for(var a="",l=0,c=-1,u=0,d,p=0;p<=n.length;++p){if(p<n.length)d=n.charCodeAt(p);else{if(d===47)break;d=47}if(d===47){if(!(c===p-1||u===1))if(c!==p-1&&u===2){if(a.length<2||l!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var g=a.lastIndexOf("/");if(g!==a.length-1){g===-1?(a="",l=0):(a=a.slice(0,g),l=a.length-1-a.lastIndexOf("/")),c=p,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=p,u=0;continue}}s&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,p):a=n.slice(c+1,p),l=p-c-1;c=p,u=0}else d===46&&u!==-1?++u:u=-1}return a}function r(n,s){var a=s.dir||s.root,l=s.base||(s.name||"")+(s.ext||"");return a?a===s.root?a+l:a+n+l:l}var o={resolve:function(){for(var n="",s=!1,a,l=arguments.length-1;l>=-1&&!s;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=i.cwd()),c=a),e(c),c.length!==0&&(n=c+"/"+n,s=c.charCodeAt(0)===47)}return n=t(n,!s),s?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var s=n.charCodeAt(0)===47,a=n.charCodeAt(n.length-1)===47;return n=t(n,!s),n.length===0&&!s&&(n="."),n.length>0&&a&&(n+="/"),s?"/"+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,s=0;s<arguments.length;++s){var a=arguments[s];e(a),a.length>0&&(n===void 0?n=a:n+="/"+a)}return n===void 0?".":o.normalize(n)},relative:function(n,s){if(e(n),e(s),n===s||(n=o.resolve(n),s=o.resolve(s),n===s))return"";for(var a=1;a<n.length&&n.charCodeAt(a)===47;++a);for(var l=n.length,c=l-a,u=1;u<s.length&&s.charCodeAt(u)===47;++u);for(var d=s.length,p=d-u,g=c<p?c:p,h=-1,b=0;b<=g;++b){if(b===g){if(p>g){if(s.charCodeAt(u+b)===47)return s.slice(u+b+1);if(b===0)return s.slice(u+b)}else c>g&&(n.charCodeAt(a+b)===47?h=b:b===0&&(h=0));break}var y=n.charCodeAt(a+b),w=s.charCodeAt(u+b);if(y!==w)break;y===47&&(h=b)}var m="";for(b=a+h+1;b<=l;++b)(b===l||n.charCodeAt(b)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+s.slice(u+h):(u+=h,s.charCodeAt(u)===47&&++u,s.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var s=n.charCodeAt(0),a=s===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(s=n.charCodeAt(u),s===47){if(!c){l=u;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":n.slice(0,l)},basename:function(n,s){if(s!==void 0&&typeof s!="string")throw new TypeError('"ext" argument must be a string');e(n);var a=0,l=-1,c=!0,u;if(s!==void 0&&s.length>0&&s.length<=n.length){if(s.length===n.length&&s===n)return"";var d=s.length-1,p=-1;for(u=n.length-1;u>=0;--u){var g=n.charCodeAt(u);if(g===47){if(!c){a=u+1;break}}else p===-1&&(c=!1,p=u+1),d>=0&&(g===s.charCodeAt(d)?--d===-1&&(l=u):(d=-1,l=p))}return a===l?l=p:l===-1&&(l=n.length),n.slice(a,l)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){a=u+1;break}}else l===-1&&(c=!1,l=u+1);return l===-1?"":n.slice(a,l)}},extname:function(n){e(n);for(var s=-1,a=0,l=-1,c=!0,u=0,d=n.length-1;d>=0;--d){var p=n.charCodeAt(d);if(p===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),p===46?s===-1?s=d:u!==1&&(u=1):s!==-1&&(u=-1)}return s===-1||l===-1||u===0||u===1&&s===l-1&&s===a+1?"":n.slice(s,l)},format:function(n){if(n===null||typeof n!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof n);return r("/",n)},parse:function(n){e(n);var s={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return s;var a=n.charCodeAt(0),l=a===47,c;l?(s.root="/",c=1):c=0;for(var u=-1,d=0,p=-1,g=!0,h=n.length-1,b=0;h>=c;--h){if(a=n.charCodeAt(h),a===47){if(!g){d=h+1;break}continue}p===-1&&(g=!1,p=h+1),a===46?u===-1?u=h:b!==1&&(b=1):u!==-1&&(b=-1)}return u===-1||p===-1||b===0||b===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&l?s.base=s.name=n.slice(1,p):s.base=s.name=n.slice(d,p)):(d===0&&l?(s.name=n.slice(1,u),s.base=n.slice(1,p)):(s.name=n.slice(d,u),s.base=n.slice(d,p)),s.ext=n.slice(u,p)),d>0?s.dir=n.slice(0,d-1):l&&(s.dir="/"),s},sep:"/",delimiter:":",win32:null,posix:null};return o.posix=o,Gr=o,Gr}var Gr,go,bo,Kd=Qe(()=>{le(),ue(),ce(),nl(),Gr={},go=!1,bo=Vd()}),il={};Ht(il,{URL:()=>ml,Url:()=>ul,default:()=>Ve,fileURLToPath:()=>sl,format:()=>dl,parse:()=>fl,pathToFileURL:()=>al,resolve:()=>hl,resolveObject:()=>pl});function Gd(){if(vo)return Yr;vo=!0;var i=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=i&&e&&typeof e.get=="function"?e.get:null,r=i&&Map.prototype.forEach,o=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&o?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,s=o&&n&&typeof n.get=="function"?n.get:null,a=o&&Set.prototype.forEach,l=typeof WeakMap=="function"&&WeakMap.prototype,c=l?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,g=p?WeakRef.prototype.deref:null,h=Boolean.prototype.valueOf,b=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,k=String.prototype.replace,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,S=RegExp.prototype.test,E=Array.prototype.concat,I=Array.prototype.join,P=Array.prototype.slice,L=Math.floor,$=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,q=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,F=typeof Symbol=="function"&&typeof Symbol.iterator=="object",D=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===F||!0)?Symbol.toStringTag:null,oe=Object.prototype.propertyIsEnumerable,j=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(K){return K.__proto__}:null);function W(K,ie){if(K===1/0||K===-1/0||K!==K||K&&K>-1e3&&K<1e3||S.call(/e/,ie))return ie;var Te=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof K=="number"){var Ce=K<0?-L(-K):L(K);if(Ce!==K){var Le=String(Ce),Re=m.call(ie,Le.length+1);return k.call(Le,Te,"$&_")+"."+k.call(k.call(Re,/([0-9]{3})/g,"$&_"),/_$/,"")}}return k.call(ie,Te,"$&_")}var re=ll,U=re.custom,Q=Y(U)?U:null;Yr=function K(ie,Te,Ce,Le){var Re=Te||{};if(se(Re,"quoteStyle")&&Re.quoteStyle!=="single"&&Re.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(se(Re,"maxStringLength")&&(typeof Re.maxStringLength=="number"?Re.maxStringLength<0&&Re.maxStringLength!==1/0:Re.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var lt=se(Re,"customInspect")?Re.customInspect:!0;if(typeof lt!="boolean"&<!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(se(Re,"indent")&&Re.indent!==null&&Re.indent!==" "&&!(parseInt(Re.indent,10)===Re.indent&&Re.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(se(Re,"numericSeparator")&&typeof Re.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var ct=Re.numericSeparator;if(typeof ie>"u")return"undefined";if(ie===null)return"null";if(typeof ie=="boolean")return ie?"true":"false";if(typeof ie=="string")return ae(ie,Re);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var Ge=String(ie);return ct?W(ie,Ge):Ge}if(typeof ie=="bigint"){var ut=String(ie)+"n";return ct?W(ie,ut):ut}var tr=typeof Re.depth>"u"?5:Re.depth;if(typeof Ce>"u"&&(Ce=0),Ce>=tr&&tr>0&&typeof ie=="object")return pe(ie)?"[Array]":"[Object]";var dt=Z(Re,Ce);if(typeof Le>"u")Le=[];else if(te(Le,ie)>=0)return"[Circular]";function et(ht,Lt,qt){if(Lt&&(Le=P.call(Le),Le.push(Lt)),qt){var pt={depth:Re.depth};return se(Re,"quoteStyle")&&(pt.quoteStyle=Re.quoteStyle),K(ht,pt,Ce+1,Le)}return K(ht,Re,Ce+1,Le)}if(typeof ie=="function"&&!ve(ie)){var hn=H(ie),rr=_e(ie,et);return"[Function"+(hn?": "+hn:" (anonymous)")+"]"+(rr.length>0?" { "+I.call(rr,", ")+" }":"")}if(Y(ie)){var br=F?k.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):q.call(ie);return typeof ie=="object"&&!F?f(br):br}if(we(ie)){for(var C="<"+v.call(String(ie.nodeName)),N=ie.attributes||[],ke=0;ke<N.length;ke++)C+=" "+N[ke].name+"="+O(J(N[ke].value),"double",Re);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(pe(ie)){if(ie.length===0)return"[]";var Se=_e(ie,et);return dt&&!B(Se)?"["+de(Se,dt)+"]":"[ "+I.call(Se,", ")+" ]"}if(G(ie)){var Ae=_e(ie,et);return!("cause"in Error.prototype)&&"cause"in ie&&!oe.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(E.call("[cause]: "+et(ie.cause),Ae),", ")+" }":Ae.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ae,", ")+" }"}if(typeof ie=="object"&<){if(Q&&typeof ie[Q]=="function"&&re)return re(ie,{depth:tr-Ce});if(lt!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var Fe=[];return r&&r.call(ie,function(ht,Lt){Fe.push(et(Lt,ie,!0)+" => "+et(ht,ie))}),A("Map",t.call(ie),Fe,dt)}if(z(ie)){var Je=[];return a&&a.call(ie,function(ht){Je.push(et(ht,ie))}),A("Set",s.call(ie),Je,dt)}if(fe(ie))return _("WeakMap");if(ge(ie))return _("WeakSet");if(ye(ie))return _("WeakRef");if(ne(ie))return f(et(Number(ie)));if(X(ie))return f(et($.call(ie)));if(V(ie))return f(h.call(ie));if(R(ie))return f(et(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Jr<"u"&&ie===Jr)return"{ [object globalThis] }";if(!ee(ie)&&!ve(ie)){var it=_e(ie,et),yr=j?j(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,vr=ie instanceof Object?"":"null prototype",wr=!yr&&D&&Object(ie)===ie&&D in ie?m.call(M(ie),8,-1):vr?"Object":"",pn=yr||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Ft=pn+(wr||vr?"["+I.call(E.call([],wr||[],vr||[]),": ")+"] ":"");return it.length===0?Ft+"{}":dt?Ft+"{"+de(it,dt)+"}":Ft+"{ "+I.call(it,", ")+" }"}return String(ie)};function O(K,ie,Te){var Ce=(Te.quoteStyle||ie)==="double"?'"':"'";return Ce+K+Ce}function J(K){return k.call(String(K),/"/g,""")}function pe(K){return M(K)==="[object Array]"&&(!D||!(typeof K=="object"&&D in K))}function ee(K){return M(K)==="[object Date]"&&(!D||!(typeof K=="object"&&D in K))}function ve(K){return M(K)==="[object RegExp]"&&(!D||!(typeof K=="object"&&D in K))}function G(K){return M(K)==="[object Error]"&&(!D||!(typeof K=="object"&&D in K))}function R(K){return M(K)==="[object String]"&&(!D||!(typeof K=="object"&&D in K))}function ne(K){return M(K)==="[object Number]"&&(!D||!(typeof K=="object"&&D in K))}function V(K){return M(K)==="[object Boolean]"&&(!D||!(typeof K=="object"&&D in K))}function Y(K){if(F)return K&&typeof K=="object"&&K instanceof Symbol;if(typeof K=="symbol")return!0;if(!K||typeof K!="object"||!q)return!1;try{return q.call(K),!0}catch{}return!1}function X(K){if(!K||typeof K!="object"||!$)return!1;try{return $.call(K),!0}catch{}return!1}var be=Object.prototype.hasOwnProperty||function(K){return K in(this||Jr)};function se(K,ie){return be.call(K,ie)}function M(K){return b.call(K)}function H(K){if(K.name)return K.name;var ie=w.call(y.call(K),/^function\s*([\w$]+)/);return ie?ie[1]:null}function te(K,ie){if(K.indexOf)return K.indexOf(ie);for(var Te=0,Ce=K.length;Te<Ce;Te++)if(K[Te]===ie)return Te;return-1}function he(K){if(!t||!K||typeof K!="object")return!1;try{t.call(K);try{s.call(K)}catch{return!0}return K instanceof Map}catch{}return!1}function fe(K){if(!c||!K||typeof K!="object")return!1;try{c.call(K,c);try{d.call(K,d)}catch{return!0}return K instanceof WeakMap}catch{}return!1}function ye(K){if(!g||!K||typeof K!="object")return!1;try{return g.call(K),!0}catch{}return!1}function z(K){if(!s||!K||typeof K!="object")return!1;try{s.call(K);try{t.call(K)}catch{return!0}return K instanceof Set}catch{}return!1}function ge(K){if(!d||!K||typeof K!="object")return!1;try{d.call(K,d);try{c.call(K,c)}catch{return!0}return K instanceof WeakSet}catch{}return!1}function we(K){return!K||typeof K!="object"?!1:typeof HTMLElement<"u"&&K instanceof HTMLElement?!0:typeof K.nodeName=="string"&&typeof K.getAttribute=="function"}function ae(K,ie){if(K.length>ie.maxStringLength){var Te=K.length-ie.maxStringLength,Ce="... "+Te+" more character"+(Te>1?"s":"");return ae(m.call(K,0,ie.maxStringLength),ie)+Ce}var Le=k.call(k.call(K,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Me);return O(Le,"single",ie)}function Me(K){var ie=K.charCodeAt(0),Te={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Te?"\\"+Te:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function f(K){return"Object("+K+")"}function _(K){return K+" { ? }"}function A(K,ie,Te,Ce){var Le=Ce?de(Te,Ce):I.call(Te,", ");return K+" ("+ie+") {"+Le+"}"}function B(K){for(var ie=0;ie<K.length;ie++)if(te(K[ie],`
|
|
4
4
|
`)>=0)return!1;return!0}function Z(K,ie){var Te;if(K.indent===" ")Te=" ";else if(typeof K.indent=="number"&&K.indent>0)Te=I.call(Array(K.indent+1)," ");else return null;return{base:Te,prev:I.call(Array(ie+1),Te)}}function de(K,ie){if(K.length===0)return"";var Te=`
|
|
5
5
|
`+ie.prev+ie.base;return Te+I.call(K,","+Te)+`
|
|
6
|
-
`+ie.prev}function _e(K,ie){var Te=pe(K),Ce=[];if(Te){Ce.length=K.length;for(var Le=0;Le<K.length;Le++)Ce[Le]=se(K,Le)?ie(K[Le],K):""}var Re=typeof T=="function"?T(K):[],lt;if(F){lt={};for(var ct=0;ct<Re.length;ct++)lt["$"+Re[ct]]=Re[ct]}for(var Ge in K)se(K,Ge)&&(Te&&String(Number(Ge))===Ge&&Ge<K.length||F&<["$"+Ge]instanceof Symbol||(S.call(/[^\w$]/,Ge)?Ce.push(ie(Ge,K)+": "+ie(K[Ge],K)):Ce.push(Ge+": "+ie(K[Ge],K))));if(typeof T=="function")for(var ut=0;ut<Re.length;ut++)oe.call(K,Re[ut])&&Ce.push("["+ie(Re[ut])+"]: "+ie(K[Re[ut]],K));return Ce}return Yr}function Gd(){if(wo)return Qr;wo=!0;var i=Gt(),e=Md(),t=Kd(),r=cr(),o=i("%WeakMap%",!0),n=i("%Map%",!0),s=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),f=function(y,w){for(var m=y,k;(k=m.next)!==null;m=k)if(k.key===w)return m.next=k.next,k.next=y.next,y.next=k,k},g=function(y,w){var m=f(y,w);return m&&m.value},h=function(y,w,m){var k=f(y,w);k?k.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!f(y,w)};return Qr=function(){var y,w,m,k={assert:function(x){if(!k.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return s(y,x)}else if(n){if(w)return c(w,x)}else if(m)return g(m,x)},has:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return l(y,x)}else if(n){if(w)return d(w,x)}else if(m)return b(m,x);return!1},set:function(x,v){o&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new o),a(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),h(m,x,v))}};return k},Qr}function yo(){if(ko)return Xr;ko=!0;var i=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Xr={default:t.RFC3986,formatters:{RFC1738:function(r){return i.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Xr}function ol(){if(_o)return Zr;_o=!0;var i=yo(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),o=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var k=[],x=0;x<m.length;++x)typeof m[x]<"u"&&k.push(m[x]);w.obj[w.prop]=k}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},k=0;k<y.length;++k)typeof y[k]<"u"&&(m[k]=y[k]);return m},s=function y(w,m,k){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(k&&(k.plainObjects||k.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var x=w;return t(w)&&!t(m)&&(x=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,S){if(e.call(w,S)){var E=w[S];E&&typeof E=="object"&&v&&typeof v=="object"?w[S]=y(E,v,k):w.push(v)}else w[S]=v}),w):Object.keys(m).reduce(function(v,S){var E=m[S];return e.call(v,S)?v[S]=y(v[S],E,k):v[S]=E,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,k){return m[k]=w[k],m},y)},l=function(y,w,m){var k=y.replace(/\+/g," ");if(m==="iso-8859-1")return k.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(k)}catch{return k}},c=1024,u=function(y,w,m,k,x){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var S="",E=0;E<v.length;E+=c){for(var I=v.length>=c?v.slice(E,E+c):v,P=[],L=0;L<I.length;++L){var $=I.charCodeAt(L);if($===45||$===46||$===95||$===126||$>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||x===i.RFC1738&&($===40||$===41)){P[P.length]=I.charAt(L);continue}if($<128){P[P.length]=r[$];continue}if($<2048){P[P.length]=r[192|$>>6]+r[128|$&63];continue}if($<55296||$>=57344){P[P.length]=r[224|$>>12]+r[128|$>>6&63]+r[128|$&63];continue}L+=1,$=65536+(($&1023)<<10|I.charCodeAt(L)&1023),P[P.length]=r[240|$>>18]+r[128|$>>12&63]+r[128|$>>6&63]+r[128|$&63]}S+=P.join("")}return S},d=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],k=0;k<w.length;++k)for(var x=w[k],v=x.obj[x.prop],S=Object.keys(v),E=0;E<S.length;++E){var I=S[E],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(w.push({obj:v,prop:I}),m.push(P))}return o(w),y},f=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},g=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},h=function(y,w){return[].concat(y,w)},b=function(y,w){if(t(y)){for(var m=[],k=0;k<y.length;k+=1)m.push(w(y[k]));return m}return w(y)};return Zr={arrayToObject:n,assign:a,combine:h,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:f,maybeMap:b,merge:s},Zr}function Yd(){if(xo)return en;xo=!0;var i=Gd(),e=ol(),t=yo(),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,s=Array.prototype.push,a=function(b,y){s.apply(b,n(y)?y:[y])},l=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(b){return l.call(b)},skipNulls:!1,strictNullHandling:!1},d=function(b){return typeof b=="string"||typeof b=="number"||typeof b=="boolean"||typeof b=="symbol"||typeof b=="bigint"},f={},g=function b(y,w,m,k,x,v,S,E,I,P,L,$,T,q,F,D,oe,j){for(var W=y,re=j,U=0,Q=!1;(re=re.get(f))!==void 0&&!Q;){var O=re.get(y);if(U+=1,typeof O<"u"){if(O===U)throw new RangeError("Cyclic object value");Q=!0}typeof re.get(f)>"u"&&(U=0)}if(typeof P=="function"?W=P(w,W):W instanceof Date?W=T(W):m==="comma"&&n(W)&&(W=e.maybeMap(W,function(M){return M instanceof Date?T(M):M})),W===null){if(v)return I&&!D?I(w,u.encoder,oe,"key",q):w;W=""}if(d(W)||e.isBuffer(W)){if(I){var J=D?w:I(w,u.encoder,oe,"key",q);return[F(J)+"="+F(I(W,u.encoder,oe,"value",q))]}return[F(w)+"="+F(String(W))]}var pe=[];if(typeof W>"u")return pe;var ee;if(m==="comma"&&n(W))D&&I&&(W=e.maybeMap(W,I)),ee=[{value:W.length>0?W.join(",")||null:void 0}];else if(n(P))ee=P;else{var ve=Object.keys(W);ee=L?ve.sort(L):ve}var G=E?w.replace(/\./g,"%2E"):w,R=k&&n(W)&&W.length===1?G+"[]":G;if(x&&n(W)&&W.length===0)return R+"[]";for(var ne=0;ne<ee.length;++ne){var V=ee[ne],Y=typeof V=="object"&&typeof V.value<"u"?V.value:W[V];if(!(S&&Y===null)){var X=$&&E?V.replace(/\./g,"%2E"):V,be=n(W)?typeof m=="function"?m(R,X):R:R+($?"."+X:"["+X+"]");j.set(y,U);var se=i();se.set(f,j),a(pe,b(Y,be,m,k,x,v,S,E,m==="comma"&&D&&n(W)?null:I,P,L,$,T,q,F,D,oe,se))}}return pe},h=function(b){if(!b)return u;if(typeof b.allowEmptyArrays<"u"&&typeof b.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof b.encodeDotInKeys<"u"&&typeof b.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(b.encoder!==null&&typeof b.encoder<"u"&&typeof b.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=b.charset||u.charset;if(typeof b.charset<"u"&&b.charset!=="utf-8"&&b.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof b.format<"u"){if(!r.call(t.formatters,b.format))throw new TypeError("Unknown format option provided.");w=b.format}var m=t.formatters[w],k=u.filter;(typeof b.filter=="function"||n(b.filter))&&(k=b.filter);var x;if(b.arrayFormat in o?x=b.arrayFormat:"indices"in b?x=b.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in b&&typeof b.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof b.allowDots>"u"?b.encodeDotInKeys===!0?!0:u.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:u.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?u.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:u.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:u.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:u.encodeValuesOnly,filter:k,format:w,formatter:m,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:u.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:u.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:u.strictNullHandling}};return en=function(b,y){var w=b,m=h(y),k,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,k=x);var v=[];if(typeof w!="object"||w===null)return"";var S=o[m.arrayFormat],E=S==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var I=i(),P=0;P<k.length;++P){var L=k[P];m.skipNulls&&w[L]===null||a(v,g(w[L],L,S,E,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 $=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&"),$.length>0?T+$:""},en}function Jd(){if(So)return tn;So=!0;var i=ol(),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:i.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},o=function(f){return f.replace(/&#(\d+);/g,function(g,h){return String.fromCharCode(parseInt(h,10))})},n=function(f,g){return f&&typeof f=="string"&&g.comma&&f.indexOf(",")>-1?f.split(","):f},s="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(f,g){var h={__proto__:null},b=g.ignoreQueryPrefix?f.replace(/^\?/,""):f;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=g.parameterLimit===1/0?void 0:g.parameterLimit,w=b.split(g.delimiter,y),m=-1,k,x=g.charset;if(g.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?x="utf-8":w[k]===s&&(x="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],S=v.indexOf("]="),E=S===-1?v.indexOf("="):S+1,I,P;E===-1?(I=g.decoder(v,r.decoder,x,"key"),P=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,E),r.decoder,x,"key"),P=i.maybeMap(n(v.slice(E+1),g),function($){return g.decoder($,r.decoder,x,"value")})),P&&g.interpretNumericEntities&&x==="iso-8859-1"&&(P=o(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var L=e.call(h,I);L&&g.duplicates==="combine"?h[I]=i.combine(h[I],P):(!L||g.duplicates==="last")&&(h[I]=P)}return h},c=function(f,g,h,b){for(var y=b?g:n(g,h),w=f.length-1;w>=0;--w){var m,k=f[w];if(k==="[]"&&h.parseArrays)m=h.allowEmptyArrays&&(y===""||h.strictNullHandling&&y===null)?[]:[].concat(y);else{m=h.plainObjects?Object.create(null):{};var x=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=h.decodeDotInKeys?x.replace(/%2E/g,"."):x,S=parseInt(v,10);!h.parseArrays&&v===""?m={0:y}:!isNaN(S)&&k!==v&&String(S)===v&&S>=0&&h.parseArrays&&S<=h.arrayLimit?(m=[],m[S]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(f,g,h,b){if(f){var y=h.allowDots?f.replace(/\.([^.[]+)/g,"[$1]"):f,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=h.depth>0&&w.exec(y),x=k?y.slice(0,k.index):y,v=[];if(x){if(!h.plainObjects&&e.call(Object.prototype,x)&&!h.allowPrototypes)return;v.push(x)}for(var S=0;h.depth>0&&(k=m.exec(y))!==null&&S<h.depth;){if(S+=1,!h.plainObjects&&e.call(Object.prototype,k[1].slice(1,-1))&&!h.allowPrototypes)return;v.push(k[1])}if(k){if(h.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+h.depth+" and strictDepth is true");v.push("["+y.slice(k.index)+"]")}return c(v,g,h,b)}},d=function(f){if(!f)return r;if(typeof f.allowEmptyArrays<"u"&&typeof f.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof f.decodeDotInKeys<"u"&&typeof f.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(f.decoder!==null&&typeof f.decoder<"u"&&typeof f.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof f.charset<"u"&&f.charset!=="utf-8"&&f.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var g=typeof f.charset>"u"?r.charset:f.charset,h=typeof f.duplicates>"u"?r.duplicates:f.duplicates;if(h!=="combine"&&h!=="first"&&h!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var b=typeof f.allowDots>"u"?f.decodeDotInKeys===!0?!0:r.allowDots:!!f.allowDots;return{allowDots:b,allowEmptyArrays:typeof f.allowEmptyArrays=="boolean"?!!f.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof f.allowPrototypes=="boolean"?f.allowPrototypes:r.allowPrototypes,allowSparse:typeof f.allowSparse=="boolean"?f.allowSparse:r.allowSparse,arrayLimit:typeof f.arrayLimit=="number"?f.arrayLimit:r.arrayLimit,charset:g,charsetSentinel:typeof f.charsetSentinel=="boolean"?f.charsetSentinel:r.charsetSentinel,comma:typeof f.comma=="boolean"?f.comma:r.comma,decodeDotInKeys:typeof f.decodeDotInKeys=="boolean"?f.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof f.decoder=="function"?f.decoder:r.decoder,delimiter:typeof f.delimiter=="string"||i.isRegExp(f.delimiter)?f.delimiter:r.delimiter,depth:typeof f.depth=="number"||f.depth===!1?+f.depth:r.depth,duplicates:h,ignoreQueryPrefix:f.ignoreQueryPrefix===!0,interpretNumericEntities:typeof f.interpretNumericEntities=="boolean"?f.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof f.parameterLimit=="number"?f.parameterLimit:r.parameterLimit,parseArrays:f.parseArrays!==!1,plainObjects:typeof f.plainObjects=="boolean"?f.plainObjects:r.plainObjects,strictDepth:typeof f.strictDepth=="boolean"?!!f.strictDepth:r.strictDepth,strictNullHandling:typeof f.strictNullHandling=="boolean"?f.strictNullHandling:r.strictNullHandling}};return tn=function(f,g){var h=d(g);if(f===""||f===null||typeof f>"u")return h.plainObjects?Object.create(null):{};for(var b=typeof f=="string"?l(f,h):f,y=h.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var k=w[m],x=u(k,b[k],h,typeof f=="string");y=i.merge(y,x,h)}return h.allowSparse===!0?y:i.compact(y)},tn}function Qd(){if(Eo)return rn;Eo=!0;var i=Yd(),e=Jd(),t=yo();return rn={formats:t,parse:e,stringify:i},rn}function Xd(){if(Ao)return Pt;Ao=!0;var i=Tt;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
|
-
`," "],s=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(s),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,
|
|
8
|
-
`)&&(e=e.replace(xl,"%0A")),e.includes("\r")&&(e=e.replace(Sl,"%0D")),e.includes(" ")&&(e=e.replace(El,"%09")),r.pathname=e,r}var ll,Yr,vo,Jr,Qr,wo,Xr,ko,Zr,_o,en,xo,tn,So,rn,Eo,Pt,Ao,Ve,cl,ul,dl,hl,pl,fl,ml,gl,bl,yl,vl,nn,wl,kl,_l,xl,Sl,El,th=Qe(()=>{le(),ue(),ce(),yd(),Nd(),Vd(),nl(),ll=Object.freeze(Object.create(null)),Yr={},vo=!1,Jr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Qr={},wo=!1,Xr={},ko=!1,Zr={},_o=!1,en={},xo=!1,tn={},So=!1,rn={},Eo=!1,Pt={},Ao=!1,Ve=Xd(),Ve.parse,Ve.resolve,Ve.resolveObject,Ve.format,Ve.Url,cl=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Ve.URL=typeof URL<"u"?URL:null,Ve.pathToFileURL=al,Ve.fileURLToPath=sl,ul=Ve.Url,dl=Ve.format,hl=Ve.resolve,pl=Ve.resolveObject,fl=Ve.parse,ml=Ve.URL,gl=92,bl=47,yl=97,vl=122,nn=cl==="win32",wl=/\//g,kl=/%/g,_l=/\\/g,xl=/\n/g,Sl=/\r/g,El=/\t/g}),rh=me((i,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),Io=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.BufferedDuplex=void 0,i.writev=r;var e=$t(),t=(He(),je(qe));function r(n,s){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",s)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,s,a){super({objectMode:!0}),this.proxy=s,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,s,a){this.isSocketOpen?this.writeToProxy(n,s,a):this.writeQueue.push({chunk:n,encoding:s,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,s){this.writeQueue=[],this.proxy.destroy(),s(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,s,a){this.proxy.write(n,s)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:s,cb:a}=this.writeQueue.shift();this.writeToProxy(n,s,a)}}};i.BufferedDuplex=o}),on=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(i,"__esModule",{value:!0}),i.streamBuilder=i.browserStreamBuilder=void 0;var t=(He(),je(qe)),r=e(rh()),o=e(vt()),n=$t(),s=e(Lr()),a=Io(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!s.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(k=>{Object.prototype.hasOwnProperty.call(w,k)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,k)&&(m.wsOptions[k]=w[k])}),m}function f(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let x=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[x],k):v=new r.default(m,[x],k.wsOptions),v}function h(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[k],m):v=new WebSocket(x,[k]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let x=u(k,w),v=g(w,x,k),S=r.default.createWebSocketStream(v,k.wsOptions);return S.url=x,v.on("close",()=>{S.destroy()}),S};i.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let k,x=f(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,S=!m.objectMode,E=h(w,m),I=L(m,D,oe);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{E.close()});let P=typeof E.addEventListener<"u";E.readyState===E.OPEN?(k=I,k.socket=E):(k=new a.BufferedDuplex(m,I,E),P?E.addEventListener("open",$):E.onopen=$),P?(E.addEventListener("close",T),E.addEventListener("error",q),E.addEventListener("message",F)):(E.onclose=T,E.onerror=q,E.onmessage=F);function L(j,W,re){let U=new n.Transform({objectMode:j.objectMode});return U._write=W,U._flush=re,U}function $(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(j){l("WebSocket onClose",j),k.end(),k.destroy()}function q(j){l("WebSocket onError",j);let W=new Error("WebSocket error");W.event=j,k.destroy(W)}async function F(j){if(!I||!I.readable||!I.writable)return;let{data:W}=j;W instanceof ArrayBuffer?W=t.Buffer.from(W):W instanceof Blob?W=t.Buffer.from(await new Response(W).arrayBuffer()):W=t.Buffer.from(W,"utf8"),I.push(W)}function D(j,W,re){if(E.bufferedAmount>x){setTimeout(D,v,j,W,re);return}S&&typeof j=="string"&&(j=t.Buffer.from(j,"utf8"));try{E.send(j)}catch(U){return re(U)}re()}function oe(j){E.close(),j()}return k};i.browserStreamBuilder=y}),To={};Ht(To,{Server:()=>Ue,Socket:()=>Ue,Stream:()=>Ue,_createServerHandle:()=>Ue,_normalizeArgs:()=>Ue,_setSimultaneousAccepts:()=>Ue,connect:()=>Ue,createConnection:()=>Ue,createServer:()=>Ue,default:()=>Al,isIP:()=>Ue,isIPv4:()=>Ue,isIPv6:()=>Ue});function Ue(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Al,Il=Qe(()=>{le(),ue(),ce(),Al={_createServerHandle:Ue,_normalizeArgs:Ue,_setSimultaneousAccepts:Ue,connect:Ue,createConnection:Ue,createServer:Ue,isIP:Ue,isIPv4:Ue,isIPv6:Ue,Server:Ue,Socket:Ue,Stream:Ue}}),Tl=me((i,e)=>{le(),ue(),ce(),e.exports={}}),Cl=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(i,"__esModule",{value:!0});var t=e((Il(),je(To))),r=e(vt()),o=e(Tl()),n=(0,r.default)("mqttjs:tcp"),s=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};i.default=s}),Pl={};Ht(Pl,{default:()=>Ol});var Ol,nh=Qe(()=>{le(),ue(),ce(),Ol={}}),Ll=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(i,"__esModule",{value:!0});var t=(nh(),je(Pl)),r=e((Il(),je(To))),o=e(vt()),n=e(Tl()),s=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:f,...g}=c;if(f!==void 0){let h=(0,n.default)(u,d,f,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:h})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,s("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=a(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",f)});function f(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",f),d};i.default=l}),Ml=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(He(),je(qe)),t=$t(),r=Io(),o,n,s;function a(){let f=new t.Transform;return f._write=(g,h,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},f._flush=g=>{o.close({success(){g()}})},f}function l(f){f.hostname||(f.hostname="localhost"),f.path||(f.path="/"),f.wsOptions||(f.wsOptions={})}function c(f,g){let h=f.protocol==="wxs"?"wss":"ws",b=`${h}://${f.hostname}${f.path}`;return f.port&&f.port!==80&&f.port!==443&&(b=`${h}://${f.hostname}:${f.port}${f.path}`),typeof f.transformWsUrl=="function"&&(b=f.transformWsUrl(b,f,g)),b}function u(){o.onOpen(()=>{s.socketReady()}),o.onMessage(f=>{let{data:g}=f;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),o.onClose(()=>{s.emit("close"),s.end(),s.destroy()}),o.onError(f=>{let g=new Error(f.errMsg);s.destroy(g)})}var d=(f,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let h=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let b=c(g,f);o=wx.connectSocket({url:b,protocols:[h]}),n=a(),s=new r.BufferedDuplex(g,n,o),s._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=s.destroy;return s.destroy=(w,m)=>(s.destroy=y,setTimeout(()=>{o.close({fail(){s._destroy(w,m)}})},0),s),u(),s};i.default=d}),Nl=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(He(),je(qe)),t=$t(),r=Io(),o,n,s,a=!1;function l(){let g=new t.Transform;return g._write=(h,b,y)=>{o.sendSocketMessage({data:h.buffer,success(){y()},fail(){y(new Error)}})},g._flush=h=>{o.closeSocket({success(){h()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,h){let b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,h)),y}function d(){a||(a=!0,o.onSocketOpen(()=>{s.socketReady()}),o.onSocketMessage(g=>{if(typeof g.data=="string"){let h=e.Buffer.from(g.data,"base64");n.push(h)}else{let h=new FileReader;h.addEventListener("load",()=>{if(h.result instanceof ArrayBuffer){n.push(e.Buffer.from(h.result));return}n.push(e.Buffer.from(h.result,"utf-8"))}),h.readAsArrayBuffer(g.data)}}),o.onSocketClose(()=>{s.end(),s.destroy()}),o.onSocketError(g=>{s.destroy(g)}))}var f=(g,h)=>{if(h.hostname=h.hostname||h.host,!h.hostname)throw new Error("Could not determine host. Specify host manually.");let b=h.protocolId==="MQIsdp"&&h.protocolVersion===3?"mqttv3.1":"mqtt";c(h);let y=u(h,g);return o=h.my,o.connectSocket({url:y,protocols:b}),n=l(),s=new r.BufferedDuplex(h,n,o),d(),s};i.default=f}),ih=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(i,"__esModule",{value:!0}),i.connectAsync=u;var t=e(vt()),r=e((th(),je(il))),o=e(Li()),n=e(Lr());typeof De?.nextTick!="function"&&(De.nextTick=setImmediate);var s=(0,t.default)("mqttjs"),a=null;function l(d){let f;if(d.auth)if(f=d.auth.match(/^(.+):(.+)$/),f){let[,g,h]=f;d.username=g,d.password=h}else d.username=d.auth}function c(d,f){if(s("connecting to an MQTT broker..."),typeof d=="object"&&!f&&(f=d,d=""),f=f||{},d&&typeof d=="string"){let b=r.default.parse(d,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,f={...y,...f},!f.protocol)throw new Error("Missing protocol");f.protocol=f.protocol.replace(/:$/,"")}if(f.unixSocket=f.unixSocket||f.protocol?.includes("+unix"),f.unixSocket?f.protocol=f.protocol.replace("+unix",""):!f.protocol?.startsWith("ws")&&!f.protocol?.startsWith("wx")&&delete f.path,l(f),f.query&&typeof f.query.clientId=="string"&&(f.clientId=f.query.clientId),n.default||f.unixSocket?f.socksProxy=void 0:f.socksProxy===void 0&&typeof De<"u"&&(f.socksProxy=De.env.MQTTJS_SOCKS_PROXY),f.cert&&f.key)if(f.protocol){if(["mqtts","wss","wxs","alis"].indexOf(f.protocol)===-1)switch(f.protocol){case"mqtt":f.protocol="mqtts";break;case"ws":f.protocol="wss";break;case"wx":f.protocol="wxs";break;case"ali":f.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${f.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!f.forceNativeWebSocket?(a.ws=on().streamBuilder,a.wss=on().streamBuilder,a.mqtt=Cl().default,a.tcp=Cl().default,a.ssl=Ll().default,a.tls=a.ssl,a.mqtts=Ll().default):(a.ws=on().browserStreamBuilder,a.wss=on().browserStreamBuilder,a.wx=Ml().default,a.wxs=Ml().default,a.ali=Nl().default,a.alis=Nl().default)),!a[f.protocol]){let b=["mqtts","wss"].indexOf(f.protocol)!==-1;f.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(f.clean===!1&&!f.clientId)throw new Error("Missing clientId for unclean clients");f.protocol&&(f.defaultProtocol=f.protocol);function g(b){return f.servers&&((!b._reconnectCount||b._reconnectCount===f.servers.length)&&(b._reconnectCount=0),f.host=f.servers[b._reconnectCount].host,f.port=f.servers[b._reconnectCount].port,f.protocol=f.servers[b._reconnectCount].protocol?f.servers[b._reconnectCount].protocol:f.defaultProtocol,f.hostname=f.host,b._reconnectCount++),s("calling streambuilder for",f.protocol),a[f.protocol](b,f)}let h=new o.default(g,f);return h.on("error",()=>{}),h}function u(d,f,g=!0){return new Promise((h,b)=>{let y=c(d,f),w={connect:k=>{m(),h(y)},end:()=>{m(),h(y)},error:k=>{m(),y.end(),b(k)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(k=>{y.off(k,w[k])})}Object.keys(w).forEach(k=>{y.on(k,w[k])})})}i.default=c}),Rl=me(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(g,h,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(h,b);(!w||("get"in w?!h.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return h[b]}}),Object.defineProperty(g,y,w)}:function(g,h,b,y){y===void 0&&(y=b),g[y]=h[b]}),t=i&&i.__setModuleDefault||(Object.create?function(g,h){Object.defineProperty(g,"default",{enumerable:!0,value:h})}:function(g,h){g.default=h}),r=i&&i.__importStar||(function(){var g=function(h){return g=Object.getOwnPropertyNames||function(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(h)};return function(h){if(h&&h.__esModule)return h;var b={};if(h!=null)for(var y=g(h),w=0;w<y.length;w++)y[w]!=="default"&&e(b,h,y[w]);return t(b,h),b}})(),o=i&&i.__exportStar||function(g,h){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(h,b)&&e(h,g,b)},n=i&&i.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=i.KeepaliveManager=i.UniqueMessageIdProvider=i.DefaultMessageIdProvider=i.Store=i.MqttClient=i.connectAsync=i.connect=i.Client=void 0;var s=n(Li());i.MqttClient=s.default;var a=n(qs());i.DefaultMessageIdProvider=a.default;var l=n(gd());i.UniqueMessageIdProvider=l.default;var c=n(Rs());i.Store=c.default;var u=r(ih());i.connect=u.default,Object.defineProperty(i,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Ys());i.KeepaliveManager=d.default,i.Client=s.default,o(Li(),i),o(Kt(),i),o(Ns(),i);var f=Pr();Object.defineProperty(i,"ReasonCodes",{enumerable:!0,get:function(){return f.ReasonCodes}})}),oh=me(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(s,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(s,c,u)}:function(s,a,l,c){c===void 0&&(c=l),s[c]=a[l]}),t=i&&i.__setModuleDefault||(Object.create?function(s,a){Object.defineProperty(s,"default",{enumerable:!0,value:a})}:function(s,a){s.default=a}),r=i&&i.__importStar||(function(){var s=function(a){return s=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},s(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=s(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=i&&i.__exportStar||function(s,a){for(var l in s)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,s,l)};Object.defineProperty(i,"__esModule",{value:!0});var n=r(Rl());i.default=n,o(Rl(),i)});const sh=oh();const ah={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}/#"},lh=300,ch={templateId:"7",type:"link",isDeepLink:!0},uh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class jl{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={...ah,...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,s)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,f)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:f?.message}),l(()=>s(f??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=sh.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,f)=>{this.dispatchInbound(d,f)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[o,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[o]=`${n.slice(0,200)}…(${n.length})`:r[o]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const o=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,o)}publishFileMessage(e,t){if(!this.client)return;const r={...ch,...this.config.fileTemplate??{},...dh(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??{}},s=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,s)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=lh){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof o.status=="number"?o.status:Number(o.status??0),f={conversationId:c,messageId:u,status:d,raw:o};this.statusUpdateHandlers.forEach(g=>g(f)),this.messageHandlers.forEach(g=>g(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const s=e.match(this.inboundRegex),a=s?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:s?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...uh,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),s={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:s}}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 s={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=s[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function dh(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(e[t]=r);return e}function $l(i,e){return(i.sender??"").toString()===e}function Dl(i,e){const t=(i.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function Co(i){const e={raw:i},t=i.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 i.text=="string"&&i.text.trim().startsWith("{"))try{const o=i.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const s=n.metadata;s&&typeof s=="object"&&(typeof s.contentType=="string"&&(e.contentType=s.contentType),typeof s.templateId=="string"&&(e.templateId=s.templateId),s.payload!==void 0&&(e.payload=s.payload))}catch{}const r=i.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 Ul(i){const e=Co(i);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,s=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=i.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!s&&!a?null:{fileName:a,fileUrl:s,cloudFileId:c,templateId:e.templateId}}function Bl(i,e,t){const r=Dl(i,t),o=Co(i),n=Ul(i);let s="";o.innerMessage?s=o.innerMessage:typeof i.text=="string"&&(i.text.trim().startsWith("{")?o.contentType!=="300"&&(s=i.text):s=i.text);const a=typeof i.message_id=="string"?i.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof i.timestamp=="number"?new Date(i.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof i.status=="number"?hh(i.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:s,createdAt:l,status:u,metadata:{sender:i.sender,sender_fullname:i.sender_fullname??i.senderFullname,app_id:i.app_id,attributes:i.attributes}};return o.contentType&&(d.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:o}}function hh(i){return i<0?"error":i>=250?"read":i>=150?"delivered":"sent"}class Fl extends _r{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 Zo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new es,this.conversationManager=new os(e.conversationId),this.usesAikaara()&&(this.connection=new Xo(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 jl({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const o=r.map(l=>Bl(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),s=this.messageStore.messages,a=[...n,...s.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:o.fileName,fileUrl:o.url,cloudFileId:o.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:s,template:a}=Bl(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&s.role==="assistant")return;if($l(e,n)){const u=this.messageStore.reconcileOptimistic(s);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(s);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:o,role:s.role==="tool"?"system":s.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class ph extends _r{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 ql={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 fh(i){const e=i.lastIndexOf(".");return e<0||e===i.length-1?"":i.slice(e+1).toLowerCase()}function mh(i,e,t){const r=fh(i.name||"");if(r&&e&&e[r])return e[r];const o=i.type;return o&&o.trim().length>0?o:r&&ql[r]?ql[r]:t}function dr(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function gh(i,e){const t=e.split(".");let r=i;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function Hl(i){const e=i.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=mh(t,i.contentTypeMap,i.contentTypeFallback??"application/octet-stream"),s={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=i.authHeader?await i.authHeader():void 0,l={accept:"application/json",...i.extraHeaders??{},...a?{authorization:a}:{}};let c,u;if(i.signBody){c=dr(i.signEndpoint,s);const w=dr(JSON.stringify(i.signBody),s);u={method:i.signMethod??"POST",headers:{...l,"content-type":"application/json"},body:w}}else{let w=i.signEndpoint.includes("{")?i.signEndpoint:`${i.signEndpoint}?fileName={fileName}`;if(!w.includes("{contentType}")){const m=w.includes("?")?"&":"?";w=`${w}${m}contentType={contentType}`}c=dr(w,s),u={method:i.signMethod??"GET",headers:l}}const d=await fetch(c,u);if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const f=await d.json().catch(()=>({})),g=gh(f,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const h=i.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,i.s3HostRewrite):g,b=await fetch(h,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(i.registerEndpoint){const w=JSON.parse(dr(JSON.stringify(i.registerBody??{}),s)),m=await fetch(i.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:i.viewerTemplate?dr(i.viewerTemplate,s):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Po(i){return{async upload(e,t){const r=new FormData,o=i.fieldName??"file";r.append(o,e,e.name);const n=typeof i.extraFields=="function"?i.extraFields(t):i.extraFields;if(n)for(const[f,g]of Object.entries(n))r.append(f,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const s=typeof i.headers=="function"?await i.headers():i.headers??{},a=await fetch(i.endpoint,{method:i.method??"POST",body:r,headers:s,credentials:i.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(i.parseResponse)return i.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const bh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Wl(i){const e=i.apiBase.replace(/\/$/,""),t=i.pageSize??200,r=i.pathTemplate??bh;return{async fetchMessages(o,n){const s=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=s.startsWith("http")?s:`${e}${s.startsWith("/")?s:`/${s}`}`,l={accept:"application/json","content-type":"application/json",...i.extraHeaders??{}};if(i.getToken){const f=await i.getToken();f&&(l.authorization=f)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(i.parseResponse&&u)return i.parseResponse(u);if(Array.isArray(u))return u;const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const yh="^[A-Z]{4}[0-9]{5}[A-Z]$",vh="^\\S{12}$",zl="^[A-Z]{4}0[A-Z0-9]{6}$",Vl="^[0-9]{6}$",wh=[{id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:yh,uppercase:!0,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"rentalIncome",type:"number",label:"Rental Income",currency:"₹",min:0},{id:"propertyTax",type:"number",label:"Municipal Taxes",currency:"₹",min:0},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",fields:[{id:"lenderName",type:"text",label:"Bank / Institute Name"},{id:"sanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"loanAccountNumber",type:"text",label:"Loan Account No."},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"outstandingAmount",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"Amount",currency:"₹",min:0,max:15e4},{id:"us80cSubType",type:"text",label:"Investment Type",placeholder:"e.g. LIC, PPF, ELSS, NSC"},{id:"us80cPolicyNumber",type:"text",label:"Policy Number"}]},{id:"section80ccd1b",type:"group",title:"Section 80CCD(1B)",fields:[{id:"us80ccd1bAmount",type:"number",label:"Amount",currency:"₹",min:0},{id:"us80ccd1bPanNo",type:"text",label:"PRAN No.",pattern:vh,maxLength:12}]},{id:"section80ccd2",type:"group",title:"Section 80CCD(2)",fields:[{id:"us80ccd2Amount",type:"number",label:"Amount",currency:"₹",min:0}]},{id:"section80g",type:"group",title:"Section 80G — Donations",fields:[{id:"us80gDonationInCash",type:"number",label:"Donation In Cash",currency:"₹",min:0},{id:"us80gDonationOnline",type:"number",label:"Donation Through Online Mode",currency:"₹",min:0},{id:"us80gTransactionRefNo",type:"text",label:"Transaction Reference No.",required:!0,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gIfscCode",type:"text",label:"IFSC Code",required:!0,uppercase:!0,pattern:zl,maxLength:11,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gNameOfCharity",type:"text",label:"Name of Charity / Trust"},{id:"us80gCharityPan",type:"text",label:"Charity / Trust PAN",uppercase:!0},{id:"us80gTrustAddress",type:"text",label:"Trust / Charity Address"},{id:"us80gPincode",type:"text",label:"Pincode",maxLength:6,pattern:Vl}]},{id:"section80e",type:"group",title:"Section 80E — Education Loan Interest",fields:[{id:"us80eLoanTakenFrom",type:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{id:"us80eBankName",type:"text",label:"Bank Name"},{id:"us80eLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]},{id:"section80ee",type:"group",title:"Section 80EEB — Electric Vehicle Loan Interest",fields:[{id:"us80eeLoanTakenFrom",type:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{id:"us80eeBankName",type:"text",label:"Bank Name"},{id:"us80eeLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eeLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eeLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eeOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eeVehicleRegistrationNumber",type:"text",label:"Vehicle Registration Number"},{id:"us80eeInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Self — Amount",currency:"₹",min:0,max:25e3},{id:"us80dForSelfAndFamilyPolicyCompany",type:"text",label:"Self — Policy Company Name"},{id:"us80dForSelfAndFamilyPolicyNumber",type:"text",label:"Self — Policy Number"},{id:"hasParentOverSixty",type:"yes-no",label:"Parent Senior Citizen"},{id:"us80dForParentsAmount",type:"number",label:"Parents — Amount",currency:"₹",min:0,max:5e4},{id:"us80dForParentsPolicyCompany",type:"text",label:"Parents — Policy Company Name"},{id:"us80dForParentsPolicyNumber",type:"text",label:"Parents — Policy Number"}]}],submitLabel:"Save"},{id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureExpenditure",type:"number",label:"Expenditure on Agriculture",currency:"₹",min:0},{id:"agricultureLandGroup",type:"group",title:"Land Details",hint:"Optional - leave blank if you only need to report income",fields:[{id:"agricultureLandInAcre",type:"number",label:"Land Area (Acres)",min:0},{id:"agricultureLandDistrict",type:"text",label:"District"},{id:"agricultureLandPincode",type:"text",label:"Pincode",maxLength:6,pattern:Vl},{id:"agricultureLandOwner",type:"radio",label:"Ownership",options:[{value:"Owned",label:"Owned"},{value:"Held on lease",label:"Held on lease"}]},{id:"agricultureLandType",type:"radio",label:"Type of Land",options:[{value:"Irrigated",label:"Irrigated"},{value:"Rain-fed",label:"Rain-fed"}]}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:zl,maxLength:11}]}],submitLabel:"Save"}];function kh(i,e){const t=i||{},r={userId:tt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Ee(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:Rh()};r.us80cAmount=xe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=xe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=xe(t.us80dForParentsAmount),r.hasParentOverSixty=hr(t.hasParentOverSixty),r.preventiveHealthCheckUp=xe(t.preventiveHealthCheckUp),r.medicalExpenditure=xe(t.medicalExpenditure),r.savingBankInterest=xe(t.savingBankInterest),r.fdInterest=xe(t.fdInterest),r.dividend=xe(t.dividend),r.anyOtherIncome=xe(t.anyOtherIncome),r.familyPension=xe(t.familyPension),r.cryptoSellValue=xe(t.cryptoSellPrice),r.cryptoPurchaseAmount=xe(t.cryptoPurchasePrice),r.vdaPurchaseCost=xe(t.cryptoPurchasePrice);const o=(xe(t.bizReceiptsBank)??0)+(xe(t.bizReceiptsCash)??0),n=(xe(t.profReceiptsBank)??0)+(xe(t.profReceiptsCash)??0),s=Ee(t.bizName)!==void 0||o>0;r.businessName=Ee(s?t.bizName:t.profName),r.businessAnnualTurnOver=s?o||void 0:n||void 0,r.agricultureDetails=Gl(t),r.exemptIncomeAmount=xe(t.exemptIncome),r.exemptIncomeNature=Ee(t.exemptIncomeNature),xe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Ee(t.exemptIncomeNature)??"Exempt income",value:String(xe(t.exemptIncome))}]),r.bankAccountNumber=Ee(t.bankAccountNumber),r.bankIfscCode=Ee(t.bankIfscCode),(Ee(t.bankAccountNumber)||Ee(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Ee(t.bankAccountNumber),bankIfscCode:Ee(t.bankIfscCode)}]);const a={description:Ee(t.immovableAssetDescription),flatNo:Ee(t.immovableAssetFlatNo),area:Ee(t.immovableAssetArea),pinCode:Ee(t.immovableAssetPincode),amount:xe(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=Oo(t.hpDetails,_h);l.length&&(r.hpDetails=l);const c=Oo(t.salaryDetails,xh);if(c.length){r.salaryIncome=c;const u=Oo(t.salaryDetails,f=>({grossSalary:xe(f.grossSalary),employerName:Ee(f.employerName)}));u.length&&(r.salary=u);const d=an(t.salaryDetails)[0]??{};r.hraAmount=xe(d.hraReceived),r.leaveTravelAllowanceAmount=xe(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=xe(d.leaveEncashment),r.anyOtherAllowanceAmount=xe(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return rt(r)}function _h(i){const e={loanType:"HOME_LOAN",loanTakenFrom:Ee(i.loanTakenFrom),bankOrInstituteName:Ee(i.lenderName),loanAccountNo:Ee(i.loanAccountNumber),loanSanctionDate:sn(i.sanctionDate),totalLoanAmount:xe(i.totalLoanAmount),loanOutstandingAmount:xe(i.outstandingAmount),interest:xe(i.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Ee(i.typeOfHouseProperty),hasRentalIncome:i.typeOfHouseProperty==="LOP"?!0:hr(i.hasRentalIncome),homeLoanInterest:xe(i.homeLoanInterest),homeLoanPrinciple:xe(i.homeLoanPrinciple),housePropertyAddress:Ee(i.housePropertyAddress),housePropertyPincode:Ee(i.housePropertyPincode),rentalIncome:xe(i.rentalIncome),nameOfTenant:Ee(i.nameOfTenant),propertyTax:xe(i.propertyTax),hasCoOwnedProperty:hr(i.hasCoOwnedProperty),coOwnerName:Ee(i.coOwnerName),coOwnerPan:Ee(i.coOwnerPan),coOwnerShare:Ee(i.coOwnerShare),loanDetails:t?[e]:void 0}}function xh(i){return{grossSalaryIncome:xe(i.grossSalary),salary:xe(i.basicSalary),totalTdsDeposited:xe(i.totalTdsDeposited),employer:{employerName:Ee(i.employerName),employerTan:Ee(i.employerTan)},allowance:{hraAmount:xe(i.hraReceived),leaveTravelAllowanceAmount:xe(i.leaveTravelAllowance),leaveEncashmentAllowanceAmount:xe(i.leaveEncashment),anyOtherAllowanceAmount:xe(i.anyOtherAllowance)}}}function Sh(i,e){const t=[];for(const r of i){const o=Ee(r.employerName),n=Ee(r.employerTan),s=xe(r.grossSalary),a=xe(r.basicSalary),l=xe(r.totalTdsDeposited);o===void 0&&n===void 0&&s===void 0&&a===void 0&&l===void 0||t.push({grossSalary:s??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function Eh(i,e){const t=Ee(i.aadhaarNumber),r=Ee(i.bankAccountNumber),o=Ee(i.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:tt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function Ah(i,e){return{userId:tt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:xe(i.savingBankInterest)??0,fdInterest:xe(i.fdInterest)??0,dividend:xe(i.dividend)??0,anyOtherIncome:xe(i.anyOtherIncome)??0,familyPension:xe(i.familyPension)??0}}function Ih(i,e){const t=xe(i.cryptoSellPrice),r=xe(i.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:tt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function Th(i,e){const t=(o,n,s,a)=>{const l=Ee(i[n]),c=xe(i[s]),u=xe(i[a]);return l===void 0&&c===void 0&&u===void 0?null:{businessType:o,businessCode:l??"",cashAmount:u??0,bankAmount:c??0}},r=[t("BUSINESS","bizNature","bizReceiptsBank","bizReceiptsCash"),t("PROFESSIONAL","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Ch(i){return Ee(i.lenderName)!==void 0||Ee(i.loanAccountNumber)!==void 0||xe(i.totalLoanAmount)!==void 0||xe(i.outstandingAmount)!==void 0||xe(i.homeLoanInterest)!==void 0}function Kl(i){const e=Ee(i.typeOfHouseProperty)?.toUpperCase();return xe(i.rentalIncome)!==void 0||Ee(i.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function Ph(i,e){const t=an(i.hpDetails).filter(Ch).map(r=>{const o=rt({loanType:"HOMELOAN",bankOrInstituteName:Ee(r.lenderName),loanAccountNo:Ee(r.loanAccountNumber),loanSanctionDate:sn(r.sanctionDate),totalLoanAmount:xe(r.totalLoanAmount),loanOutstandingAmount:xe(r.outstandingAmount),interest:xe(r.homeLoanInterest)});return rt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),homeLoanInterest:xe(r.homeLoanInterest),homeLoanPrinciple:xe(r.homeLoanPrinciple),propertyTax:xe(r.propertyTax),eligible80EEAAmount:xe(r.eligible80EEAAmount),eligible80EEAmount:xe(r.eligible80EEAmount),hasCoOwnedProperty:hr(r.hasCoOwnedProperty)??!1,hasRentalIncome:Kl(r),loanDetails:[o]})});return t.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Oh(i,e){const t=an(i.hpDetails).filter(Kl).map(r=>rt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),rentalIncome:xe(r.rentalIncome),propertyTax:xe(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Ee(r.nameOfTenant),tenantPanNumber:Ee(r.tenantPanNumber),homeLoanInterest:xe(r.homeLoanInterest)}));return t.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Lh(i,e){const t=i||{},r=g=>({userId:tt(e.userId),assessmentYear:e.assessmentYear,deductions:rt(g)}),o=[],n=xe(t.us80cAmount);if(n!==void 0){const g=Ee(t.us80cSubType);g?o.push(r({deductionSection:"80C",subType:g,amount:n,accountNo:Ee(t.us80cPolicyNumber)})):console.warn("[smart-edit] 80C skipped — Investment Type is required by the API")}const s=Ee(t.us80ccd1bPanNo),a=xe(t.us80ccd1bAmount);a!==void 0&&o.push(r({deductionSection:"80CCD(1B)",subType:"NPS",amount:a,accountNo:s}));const l=xe(t.us80ccd2Amount);l!==void 0&&o.push(r({deductionSection:"80CCD(2)",subType:"EMPLOYER_NPS",amount:l,accountNo:s}));const c=xe(t.us80eInterest);c!==void 0&&o.push(r({deductionSection:"80E",subType:"EDUCATION_LOAN",interest:c,loanTakenFrom:Ee(t.us80eLoanTakenFrom),bankOrInstituteName:Ee(t.us80eBankName),loanAccountNo:Ee(t.us80eLoanAccountNumber),loanSanctionDate:sn(t.us80eLoanSanctionDate),totalLoanAmount:xe(t.us80eLoanAmount),loanOutstandingAmount:xe(t.us80eOutstandingLoan)}));const u=xe(t.us80eeInterest);u!==void 0&&o.push(r({deductionSection:"80EEB",interest:u,loanTakenFrom:Ee(t.us80eeLoanTakenFrom),bankOrInstituteName:Ee(t.us80eeBankName),loanAccountNo:Ee(t.us80eeLoanAccountNumber),loanSanctionDate:sn(t.us80eeLoanSanctionDate),totalLoanAmount:xe(t.us80eeLoanAmount),loanOutstandingAmount:xe(t.us80eeOutstandingLoan),vehicleRegistrationNo:Ee(t.us80eeVehicleRegistrationNumber)}));const d=xe(t.us80dForSelfAndFamilyAmount);d!==void 0&&o.push(r({deductionSection:"80D",subType:"selfFamilyPremium80D",amount:d,insurerName:Ee(t.us80dForSelfAndFamilyPolicyCompany),accountNo:Ee(t.us80dForSelfAndFamilyPolicyNumber)}));const f=xe(t.us80dForParentsAmount);return f!==void 0&&o.push(r({deductionSection:"80D",subType:"parentsPremium80D",amount:f,insurerName:Ee(t.us80dForParentsPolicyCompany),accountNo:Ee(t.us80dForParentsPolicyNumber),parentSeniorCitizen:hr(t.hasParentOverSixty)??!1})),o}function Mh(i,e){const t=i||{},r=xe(t.us80gDonationInCash),o=xe(t.us80gDonationOnline),n=Ee(t.us80gNameOfCharity);if(r===void 0&&o===void 0&&n===void 0)return null;const s=(o??0)>0;return{userId:tt(e.userId),assessmentYear:e.assessmentYear,donations80g:[rt({name:n,panNumber:Ee(t.us80gCharityPan),amountInCash:r,amountOtherThanCash:o,address:Ee(t.us80gTrustAddress),pinCode:Ee(t.us80gPincode),transactionRefNum:s?Ee(t.us80gTransactionRefNo):void 0,ifscCode:s?Ee(t.us80gIfscCode):void 0})]}}function Gl(i){const e=i||{},t=xe(e.agricultureIncome),r=xe(e.agricultureExpenditure),o=rt({landInAcre:xe(e.agricultureLandInAcre),nameOfDistrict:Ee(e.agricultureLandDistrict),pinCode:Ee(e.agricultureLandPincode),owner:Ee(e.agricultureLandOwner),typeOfLand:Ee(e.agricultureLandType)})??{},n=Object.keys(o).length>0;if(!(t===void 0&&r===void 0&&!n))return rt({income:t,expenditure:r??0,agricultureLandDetails:n?[o]:void 0})}function Nh(i,e){const t=Gl(i);return t?{userId:tt(e.userId),assessmentYear:e.assessmentYear,agricultureDetails:t}:null}function tt(i){if(i===void 0||i==="")return;const e=Number(i);return Number.isFinite(e)&&String(e)===String(i)?e:i}function xe(i){if(i==null||i==="")return;const e=typeof i=="number"?i:Number(i);return Number.isFinite(e)?e:void 0}function Ee(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function hr(i){return i===!0||i===!1?i:void 0}function Rh(){const i=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${i.getFullYear()}-${e(i.getMonth()+1)}-${e(i.getDate())}T${e(i.getHours())}:${e(i.getMinutes())}:${e(i.getSeconds())}.${e(i.getMilliseconds(),3)}`}function sn(i){const e=Ee(i);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function an(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Oo(i,e){return an(i).map(t=>rt(e(t))).filter(t=>t!==void 0)}function rt(i){if(Array.isArray(i)){const e=i.map(rt).filter(t=>t!==void 0);return e.length?e:void 0}if(i&&typeof i=="object"){const e={};for(const[t,r]of Object.entries(i)){const o=rt(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return i}function jh(i){const e=i&&typeof i=="object"?i:{},t={},r=$e(e.employers),o=$e(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(j=>{const W=Mo(j.salary),re=Mo(j.perquisites),U=Mo(j.profitsInLieuOfSalaryType),Q=W+re+U,O=qh(j.allowance);return{employerName:Ie(j.employerName),employerTan:Ie(j.employerTAN),basicSalary:W||void 0,grossSalary:Q||void 0,hraReceived:O.hra,leaveTravelAllowance:O.lta,leaveEncashment:O.leaveEncashment,anyOtherAllowance:O.other,totalTdsDeposited:Fh(j,o,r)??Oe(j.totalTdsDeposited)}}));const n=$e(e.houseProperties);n.length&&(t.hpDetails=n.map(j=>{const W=$e(j.loanDetails),re=W.length?W[0]:void 0,U=Oe(j.grossAnnualRentReceived),Q=W.length?W.reduce((ve,G)=>ve+(Oe(G.interest)??0),0):void 0,O=$e(j.tenant),J=$e(j.coOwners),pe=O[0],ee=J[0];return{typeOfHouseProperty:Ie(j.propertyType),loanTakenFrom:Ie(re?.loanTakenFrom),lenderName:Ie(re?.bankOrInstituteName),loanAccountNumber:Ie(re?.loanAccountNo),sanctionDate:Lo(re?.loanSanctionDate),totalLoanAmount:Oe(re?.totalLoanAmount),outstandingAmount:Oe(re?.loanOutstandingAmount),homeLoanInterest:Q,homeLoanPrinciple:void 0,housePropertyAddress:Ie(j.address),housePropertyPincode:Ie(j.pinCode),rentalIncome:U,nameOfTenant:Ie(pe?.name),tenantPanNumber:Ie(pe?.panNumber),eligible80EEAmount:Oe(j.eligible80EEAmount),eligible80EEAAmount:Oe(j.eligible80EEAAmount),propertyTax:Oe(j.propertyTax),hasCoOwnedProperty:J.length>0,coOwnerName:Ie(ee?.name),coOwnerPan:Ie(ee?.panNumber),coOwnerShare:Oe(ee?.share)?.toString()}}));const s=$e(e.deductionUS80CDetails),a=Ot(s.map(j=>Oe(j.amount))),l=s.find(j=>Ie(j.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ie(l?.identificationNo);const c=$e(e.investments),u=c.find(j=>!Dh(Ie(j.investmentType))),d=Array.isArray(u?.bifurcation)?u.bifurcation[0]:void 0;t.us80cSubType=Ie(d?.subType??u?.investmentType);const f=$e(e.deductionUS80DDetails),g=f.find(j=>Ie(j.policyFor)?.toUpperCase()==="DEPENDANT")??$e(e.insurances).find(j=>Ie(j.policyFor)?.toUpperCase()==="DEPENDANT"),h=f.find(j=>Ie(j.policyFor)?.toUpperCase()==="PARENTS")??$e(e.insurances).find(j=>Ie(j.policyFor)?.toUpperCase()==="PARENTS"),b=Array.isArray(g?.bifurcation)?g.bifurcation[0]:void 0,y=Array.isArray(h?.bifurcation)?h.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Oe(g?.healthInsuranceAmount??g?.premium),t.us80dForSelfAndFamilyPolicyCompany=Ie(g?.insurerName??b?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Ie(g?.policyNo??b?.accountNo),t.us80dForParentsAmount=Oe(h?.healthInsuranceAmount??h?.premium),t.us80dForParentsPolicyCompany=Ie(h?.insurerName??y?.insurerName),t.us80dForParentsPolicyNumber=Ie(h?.policyNo??y?.accountNo),t.hasParentOverSixty=Hh(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=Oe(e.us80ccd1bAmount)??Yl(c,"PENSION_SCHEME"),t.us80ccd1bPanNo=Ie(e.pranNumber)??Ie(e.us80ccd1bPanNo),t.us80ccd2Amount=Oe(e.us80ccd2Amount)??Yl(c,"PS_EMPLOYER");const m=$e(e.donations)[0];t.us80gDonationInCash=Oe(m?.amountInCash??m?.donationInCash),t.us80gDonationOnline=Oe(m?.amountOtherThanCash??m?.amount??m?.donationAmount),t.us80gNameOfCharity=Ie(m?.name??m?.nameOfCharity??m?.donorName??m?.trustName),t.us80gCharityPan=Ie(m?.panNumber??m?.charityPan),t.us80gTrustAddress=Ie(m?.address??m?.charityAddress),t.us80gPincode=Ie(m?.pinCode??m?.pincode),t.us80gTransactionRefNo=Ie(m?.transactionRefNum??m?.transactionReferenceNo??m?.transactionRefNo),t.us80gIfscCode=Ie(m?.ifscCode??m?.ifsCode);const k=$e(e.loanDetails),x=j=>k.find(W=>Ie(W.loanType)?.toUpperCase()===j),v=x("EDUCATION"),S=x("ELECTRIC_VEHICLE");t.us80eLoanTakenFrom=Ie(v?.loanTakenFrom),t.us80eBankName=Ie(v?.bankOrInstituteName),t.us80eLoanAccountNumber=Ie(v?.loanAccountNo),t.us80eLoanSanctionDate=Lo(v?.loanSanctionDate),t.us80eLoanAmount=Oe(v?.totalLoanAmount),t.us80eOutstandingLoan=Oe(v?.loanOutstandingAmount),t.us80eInterest=Oe(v?.interest),t.us80eeLoanTakenFrom=Ie(S?.loanTakenFrom),t.us80eeBankName=Ie(S?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ie(S?.loanAccountNo),t.us80eeLoanSanctionDate=Lo(S?.loanSanctionDate),t.us80eeLoanAmount=Oe(S?.totalLoanAmount),t.us80eeOutstandingLoan=Oe(S?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ie(S?.vehicleRegistrationNo),t.us80eeInterest=Oe(S?.interest);const E=$e(e.insurances);t.preventiveHealthCheckUp=Ot(E.map(j=>Oe(j.preventiveCheckUp))),t.medicalExpenditure=Ot(E.map(j=>Oe(j.medicalExpenditure)));const I=$e(e.incomes),P=j=>Ot(I.filter(W=>Ie(W.incomeType)===j).map(W=>Oe(W.amount)));t.savingBankInterest=P("SAVING_INTEREST"),t.fdInterest=P("FD_RD_INTEREST"),t.anyOtherIncome=P("ANY_OTHER"),t.familyPension=P("FAMILY_PENSION"),t.dividend=Ot($e(e.dividendIncomes).map(j=>Oe(j.income)));const L=e.business;if(L){const j=$e(L.presumptiveIncomes),W=Q=>{const O=Ie(Q.businessType)?.trim().toUpperCase()??"";if(O.includes("PROFESSION")||O==="44ADA")return!0;if(O.includes("BUSINESS")||O==="44AD"||O==="PRESUMPTIVE")return!1;const J=$e(Q.incomes),pe=ee=>Oe(J.find(ve=>Ie(ve.incomeType)===ee)?.receipts)??0;return pe("ANY_OTHER")>0?!0:(pe("BANK")>0||pe("CASH")>0,!1)},re=Q=>j.find(O=>W(O)===Q),U=(Q,O)=>{if(!Q)return;const J=$e(Q.incomes),pe=ve=>Oe(J.find(G=>Ie(G.incomeType)===ve)?.receipts),ee=pe("BANK")||pe("ANY_OTHER");t[O.nature]=Ie(Q.natureOfBusiness),t[O.bank]=ee||void 0,t[O.cash]=pe("CASH")||void 0,t[O.net]=Ot(J.map(ve=>Oe(ve.presumptiveIncome)))||void 0};U(re(!1),{nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),U(re(!0),{nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const $=$e(e.capitalGain).filter(j=>Ie(j.assetType)?.toUpperCase()==="VDA").flatMap(j=>$e(j.assetDetails));$.length&&(t.cryptoSellPrice=Ot($.map(j=>Oe(j.sellValue))),t.cryptoPurchasePrice=Ot($.map(j=>Oe(j.purchaseCost))));const T=e.agriculturalDetails,q=e.agriculturalIncome;t.agricultureIncome=Oe(q?.grossAgriculturalReceipts)??Oe(q?.netAgriculturalIncome)??Oe(T?.income),t.agricultureExpenditure=Oe(q?.expenditureIncurredOnAgriculture)??Oe(T?.expenditure);const D=([$e(e.agriculturalLandDetails),$e(T?.agricultureLandDetails),$e(T?.agriculturalLandDetails)].find(j=>j.length>0)??[])[0];D&&(t.agricultureLandInAcre=Oe(D.landInAcre),t.agricultureLandDistrict=Ie(D.nameOfDistrict),t.agricultureLandPincode=Ie(D.pinCode),t.agricultureLandOwner=Uh(D.owner),t.agricultureLandType=Bh(D.typeOfLand)),t.aadhaarNumber=Ie(e.aadharNumber);const oe=$e(e.bankDetails)[0];return oe&&(t.bankAccountNumber=Ie(oe.accountNumber),t.bankIfscCode=Ie(oe.ifsCode)),Jl(t)}const $h=["PENSION_SCHEME","PS_EMPLOYER","PS_EMPLOYEE","PENSION_FUND"];function Dh(i){const e=i?.trim().toUpperCase();return!!e&&$h.includes(e)}function Yl(i,e){const t=i.find(r=>Ie(r.investmentType)?.toUpperCase()===e);return Oe(t?.amount)}function Uh(i){const e=Ie(i)?.trim();if(!e)return;const t=e.toUpperCase();return t==="O"||t==="OWNED"?"Owned":t==="H"||t.startsWith("HELD")?"Held on lease":e}function Bh(i){const e=Ie(i)?.trim();if(!e)return;const t=e.toUpperCase();return t==="IRG"||t==="IRRIGATED"?"Irrigated":t==="RF"||t.startsWith("RAIN")?"Rain-fed":e}function Lo(i){const e=Ie(i);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function Mo(i){return $e(i).reduce((e,t)=>e+(Oe(t.taxableAmount)??0),0)}function Fh(i,e,t){if(!e.length)return;const r=Ie(i.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ie(n.deductorTAN)?.trim().toUpperCase()===r)return Oe(n.totalTdsDeposited)}const o=Ie(i.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Ie(n.deductorName)?.trim().toLowerCase()===o)return Oe(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Oe(e[0].totalTdsDeposited)}function qh(i){const e=$e(i);if(!e.length)return{};let t,r,o,n;for(const s of e){const a=Oe(s.exemptAmount)??Oe(s.allowanceAmount);switch(Ie(s.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Oe(s.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Ot(i){let e=0,t=!1;for(const r of i)r!=null&&(e+=r,t=!0);return t?e:void 0}function $e(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Oe(i){if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"&&i.trim()!==""&&Number.isFinite(Number(i)))return Number(i)}function Ie(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function Hh(i){if(typeof i=="boolean")return i;if(typeof i=="string"){const e=i.trim().toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="y")return!0;if(e==="false"||e==="0"||e==="no"||e==="n")return!1}if(typeof i=="number")return i===1?!0:i===0?!1:void 0}function Jl(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?Jl(o):o):e[t]=r);return e}function No(){if(typeof window>"u")return null;const i=window,e=i.__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=i.__aikaara_descriptor__??{},r=ep(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=tp(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",s=e.getChatJwt,a=async()=>n||await s(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):np(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:rp(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||ip(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function Wh(i){const e=await i.getToken(),t=i.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${i.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...i.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 jh(Ro(await r.json().catch(()=>({}))))}async function zh(i,e){const t=await i.getToken(),r=i.userId,o={...kh(e,{userId:r,assessmentYear:i.assessmentYear,isRevised:i.isRevised}),sendSummary:!0},n=i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...i.headers};i.txbdyApiKey&&(s["txbdy-api-key"]=i.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:s,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Ro(await a.json().catch(()=>({})))}async function Vh(i,e){return xt(i,`${i.baseUrl}/itr/v1/automation/salary`,e)}async function Kh(i,e){return xt(i,`${i.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Ql(i,e){return xt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Gh(i,e){return xt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Yh(i,e){return xt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Jh(i,e){return xt(i,`${i.baseUrl}/itr/v1/automation/deductions`,e)}async function Qh(i,e){return xt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Xh(i,e){return xt(i,`${i.baseUrl}/itr/v1/automation/hp-income`,e)}async function Zh(i,e){return xt(i,`${i.baseUrl}/itr/v1/automation/vda`,e)}async function xt(i,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await i.getToken()}`,...i.headers};i.txbdyApiKey&&(o["txbdy-api-key"]=i.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 s=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${s.slice(0,200)}`)}return Ro(await n.json().catch(()=>({})))}function ep(i){const e=[i.cloud?.listEndpoint,i.cloud?.downloadEndpoint,i.upload?.signEndpoint,i.login?.pan?.basicPanEndpoint,i.login?.pan?.panDetailEndpoint,i.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 tp(i){if(!i||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${i}`);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 rp(i){const e={};if(!i)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(i))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function np(i){if(!i)return;const e=i.userId??i.id??i.ext_uid??i.extUid;return e==null||e===""?void 0:String(e)}function Ro(i){if(i&&typeof i=="object"){const e=i;return e.data&&typeof e.data=="object"?e.data:e}return{}}function ip(){const i=new Date,e=i.getMonth()>=3?i.getFullYear():i.getFullYear()-1;return`${e}-${e+1}`}const op=["No, I have concerns","No, I have a concerns"];function ln(i){const e=window.__aikaara_descriptor__?.smartEdit?.openOnMessages,t=Array.isArray(e)?e:op;if(t.length===0)return!1;const r=n=>n.trim().toLowerCase(),o=r(i);return t.some(n=>typeof n=="string"&&r(n)===o)}function jo(i){return!Array.isArray(i)||i.length===0||!i.every(t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!("type"in t)&&!("data"in t)&&typeof t.message=="string")?!1:i.some(t=>{const{message:r,title:o}=t;return ln(r)||typeof o=="string"&&ln(o)})}class sp{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Fl(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(ln(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)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:wh,data:{}});const t=No();if(!(!t||!t.baseUrl))try{const r=await Wh(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=No();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],s=Sh(n,o);s&&await Vh(r,s)}else if(e==="bank-details"){const n=Eh(t,o);n&&await Kh(r,n)}else if(e==="other-sources")await Ql(r,Ah(t,o));else if(e==="business-profession"){const n=Th(t,o);n&&await Gh(r,n)}else if(e==="crypto-income"){const n=Ih(t,o);n&&await Zh(r,n)}else if(e==="agricultural-income"){const n=Nh(t,o);n&&await Yh(r,n)}else if(e==="deductions"){for(const s of Lh(t,o))await Jh(r,s);const n=Mh(t,o);n&&await Ql(r,n)}else if(e==="house-property"){const n=Ph(t,o);n&&await Qh(r,n);const s=Oh(t,o);s&&await Xh(r,s)}}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=No();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await zh(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 Xl 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||Qc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Jo,position:this.getAttribute("position")||this._config.position||Jc,width:Number(this.getAttribute("width"))||this._config.width||Vc,height:Number(this.getAttribute("height"))||this._config.height||Kc,fontFamily:this._config.fontFamily||Yc,borderRadius:this._config.borderRadius??Gc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Qo,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||Xc,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,s=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};s("primary",e?.primary??t),s("primary-hover",e?.primaryHover),s("primary-contrast",e?.primaryContrast),s("surface",e?.surface),s("surface-muted",e?.surfaceMuted),s("border",e?.border),s("text",e?.text),s("text-muted",e?.textMuted),s("font",e?.font??o),s("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),s("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),s("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),s("user-bubble-bg",e?.userBubbleBg),s("user-bubble-text",e?.userBubbleText),s("bot-bubble-bg",e?.botBubbleBg),s("bot-bubble-text",e?.botBubbleText),s("modal-width",e?.modalWidth),s("modal-height",e?.modalHeight),s("modal-max-width",e?.modalMaxWidth),s("modal-max-height",e?.modalMaxHeight),s("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
|
|
6
|
+
`+ie.prev}function _e(K,ie){var Te=pe(K),Ce=[];if(Te){Ce.length=K.length;for(var Le=0;Le<K.length;Le++)Ce[Le]=se(K,Le)?ie(K[Le],K):""}var Re=typeof T=="function"?T(K):[],lt;if(F){lt={};for(var ct=0;ct<Re.length;ct++)lt["$"+Re[ct]]=Re[ct]}for(var Ge in K)se(K,Ge)&&(Te&&String(Number(Ge))===Ge&&Ge<K.length||F&<["$"+Ge]instanceof Symbol||(S.call(/[^\w$]/,Ge)?Ce.push(ie(Ge,K)+": "+ie(K[Ge],K)):Ce.push(Ge+": "+ie(K[Ge],K))));if(typeof T=="function")for(var ut=0;ut<Re.length;ut++)oe.call(K,Re[ut])&&Ce.push("["+ie(Re[ut])+"]: "+ie(K[Re[ut]],K));return Ce}return Yr}function Yd(){if(wo)return Qr;wo=!0;var i=Gt(),e=Nd(),t=Gd(),r=cr(),o=i("%WeakMap%",!0),n=i("%Map%",!0),s=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(y,w){for(var m=y,k;(k=m.next)!==null;m=k)if(k.key===w)return m.next=k.next,k.next=y.next,y.next=k,k},g=function(y,w){var m=p(y,w);return m&&m.value},h=function(y,w,m){var k=p(y,w);k?k.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!p(y,w)};return Qr=function(){var y,w,m,k={assert:function(x){if(!k.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return s(y,x)}else if(n){if(w)return c(w,x)}else if(m)return g(m,x)},has:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return l(y,x)}else if(n){if(w)return d(w,x)}else if(m)return b(m,x);return!1},set:function(x,v){o&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new o),a(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),h(m,x,v))}};return k},Qr}function yo(){if(ko)return Xr;ko=!0;var i=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Xr={default:t.RFC3986,formatters:{RFC1738:function(r){return i.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Xr}function ol(){if(_o)return Zr;_o=!0;var i=yo(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),o=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var k=[],x=0;x<m.length;++x)typeof m[x]<"u"&&k.push(m[x]);w.obj[w.prop]=k}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},k=0;k<y.length;++k)typeof y[k]<"u"&&(m[k]=y[k]);return m},s=function y(w,m,k){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(k&&(k.plainObjects||k.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var x=w;return t(w)&&!t(m)&&(x=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,S){if(e.call(w,S)){var E=w[S];E&&typeof E=="object"&&v&&typeof v=="object"?w[S]=y(E,v,k):w.push(v)}else w[S]=v}),w):Object.keys(m).reduce(function(v,S){var E=m[S];return e.call(v,S)?v[S]=y(v[S],E,k):v[S]=E,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,k){return m[k]=w[k],m},y)},l=function(y,w,m){var k=y.replace(/\+/g," ");if(m==="iso-8859-1")return k.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(k)}catch{return k}},c=1024,u=function(y,w,m,k,x){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var S="",E=0;E<v.length;E+=c){for(var I=v.length>=c?v.slice(E,E+c):v,P=[],L=0;L<I.length;++L){var $=I.charCodeAt(L);if($===45||$===46||$===95||$===126||$>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||x===i.RFC1738&&($===40||$===41)){P[P.length]=I.charAt(L);continue}if($<128){P[P.length]=r[$];continue}if($<2048){P[P.length]=r[192|$>>6]+r[128|$&63];continue}if($<55296||$>=57344){P[P.length]=r[224|$>>12]+r[128|$>>6&63]+r[128|$&63];continue}L+=1,$=65536+(($&1023)<<10|I.charCodeAt(L)&1023),P[P.length]=r[240|$>>18]+r[128|$>>12&63]+r[128|$>>6&63]+r[128|$&63]}S+=P.join("")}return S},d=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],k=0;k<w.length;++k)for(var x=w[k],v=x.obj[x.prop],S=Object.keys(v),E=0;E<S.length;++E){var I=S[E],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(w.push({obj:v,prop:I}),m.push(P))}return o(w),y},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))},h=function(y,w){return[].concat(y,w)},b=function(y,w){if(t(y)){for(var m=[],k=0;k<y.length;k+=1)m.push(w(y[k]));return m}return w(y)};return Zr={arrayToObject:n,assign:a,combine:h,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:p,maybeMap:b,merge:s},Zr}function Jd(){if(xo)return en;xo=!0;var i=Yd(),e=ol(),t=yo(),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,s=Array.prototype.push,a=function(b,y){s.apply(b,n(y)?y:[y])},l=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(b){return l.call(b)},skipNulls:!1,strictNullHandling:!1},d=function(b){return typeof b=="string"||typeof b=="number"||typeof b=="boolean"||typeof b=="symbol"||typeof b=="bigint"},p={},g=function b(y,w,m,k,x,v,S,E,I,P,L,$,T,q,F,D,oe,j){for(var W=y,re=j,U=0,Q=!1;(re=re.get(p))!==void 0&&!Q;){var O=re.get(y);if(U+=1,typeof O<"u"){if(O===U)throw new RangeError("Cyclic object value");Q=!0}typeof re.get(p)>"u"&&(U=0)}if(typeof P=="function"?W=P(w,W):W instanceof Date?W=T(W):m==="comma"&&n(W)&&(W=e.maybeMap(W,function(M){return M instanceof Date?T(M):M})),W===null){if(v)return I&&!D?I(w,u.encoder,oe,"key",q):w;W=""}if(d(W)||e.isBuffer(W)){if(I){var J=D?w:I(w,u.encoder,oe,"key",q);return[F(J)+"="+F(I(W,u.encoder,oe,"value",q))]}return[F(w)+"="+F(String(W))]}var pe=[];if(typeof W>"u")return pe;var ee;if(m==="comma"&&n(W))D&&I&&(W=e.maybeMap(W,I)),ee=[{value:W.length>0?W.join(",")||null:void 0}];else if(n(P))ee=P;else{var ve=Object.keys(W);ee=L?ve.sort(L):ve}var G=E?w.replace(/\./g,"%2E"):w,R=k&&n(W)&&W.length===1?G+"[]":G;if(x&&n(W)&&W.length===0)return R+"[]";for(var ne=0;ne<ee.length;++ne){var V=ee[ne],Y=typeof V=="object"&&typeof V.value<"u"?V.value:W[V];if(!(S&&Y===null)){var X=$&&E?V.replace(/\./g,"%2E"):V,be=n(W)?typeof m=="function"?m(R,X):R:R+($?"."+X:"["+X+"]");j.set(y,U);var se=i();se.set(p,j),a(pe,b(Y,be,m,k,x,v,S,E,m==="comma"&&D&&n(W)?null:I,P,L,$,T,q,F,D,oe,se))}}return pe},h=function(b){if(!b)return u;if(typeof b.allowEmptyArrays<"u"&&typeof b.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof b.encodeDotInKeys<"u"&&typeof b.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(b.encoder!==null&&typeof b.encoder<"u"&&typeof b.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=b.charset||u.charset;if(typeof b.charset<"u"&&b.charset!=="utf-8"&&b.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof b.format<"u"){if(!r.call(t.formatters,b.format))throw new TypeError("Unknown format option provided.");w=b.format}var m=t.formatters[w],k=u.filter;(typeof b.filter=="function"||n(b.filter))&&(k=b.filter);var x;if(b.arrayFormat in o?x=b.arrayFormat:"indices"in b?x=b.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in b&&typeof b.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof b.allowDots>"u"?b.encodeDotInKeys===!0?!0:u.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:u.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?u.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:u.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:u.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:u.encodeValuesOnly,filter:k,format:w,formatter:m,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:u.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:u.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:u.strictNullHandling}};return en=function(b,y){var w=b,m=h(y),k,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,k=x);var v=[];if(typeof w!="object"||w===null)return"";var S=o[m.arrayFormat],E=S==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var I=i(),P=0;P<k.length;++P){var L=k[P];m.skipNulls&&w[L]===null||a(v,g(w[L],L,S,E,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 $=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&"),$.length>0?T+$:""},en}function Qd(){if(So)return tn;So=!0;var i=ol(),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:i.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,h){return String.fromCharCode(parseInt(h,10))})},n=function(p,g){return p&&typeof p=="string"&&g.comma&&p.indexOf(",")>-1?p.split(","):p},s="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,g){var h={__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,k,x=g.charset;if(g.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?x="utf-8":w[k]===s&&(x="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],S=v.indexOf("]="),E=S===-1?v.indexOf("="):S+1,I,P;E===-1?(I=g.decoder(v,r.decoder,x,"key"),P=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,E),r.decoder,x,"key"),P=i.maybeMap(n(v.slice(E+1),g),function($){return g.decoder($,r.decoder,x,"value")})),P&&g.interpretNumericEntities&&x==="iso-8859-1"&&(P=o(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var L=e.call(h,I);L&&g.duplicates==="combine"?h[I]=i.combine(h[I],P):(!L||g.duplicates==="last")&&(h[I]=P)}return h},c=function(p,g,h,b){for(var y=b?g:n(g,h),w=p.length-1;w>=0;--w){var m,k=p[w];if(k==="[]"&&h.parseArrays)m=h.allowEmptyArrays&&(y===""||h.strictNullHandling&&y===null)?[]:[].concat(y);else{m=h.plainObjects?Object.create(null):{};var x=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=h.decodeDotInKeys?x.replace(/%2E/g,"."):x,S=parseInt(v,10);!h.parseArrays&&v===""?m={0:y}:!isNaN(S)&&k!==v&&String(S)===v&&S>=0&&h.parseArrays&&S<=h.arrayLimit?(m=[],m[S]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,g,h,b){if(p){var y=h.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=h.depth>0&&w.exec(y),x=k?y.slice(0,k.index):y,v=[];if(x){if(!h.plainObjects&&e.call(Object.prototype,x)&&!h.allowPrototypes)return;v.push(x)}for(var S=0;h.depth>0&&(k=m.exec(y))!==null&&S<h.depth;){if(S+=1,!h.plainObjects&&e.call(Object.prototype,k[1].slice(1,-1))&&!h.allowPrototypes)return;v.push(k[1])}if(k){if(h.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+h.depth+" and strictDepth is true");v.push("["+y.slice(k.index)+"]")}return c(v,g,h,b)}},d=function(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,h=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(h!=="combine"&&h!=="first"&&h!=="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"||i.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:h,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 tn=function(p,g){var h=d(g);if(p===""||p===null||typeof p>"u")return h.plainObjects?Object.create(null):{};for(var b=typeof p=="string"?l(p,h):p,y=h.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var k=w[m],x=u(k,b[k],h,typeof p=="string");y=i.merge(y,x,h)}return h.allowSparse===!0?y:i.compact(y)},tn}function Xd(){if(Eo)return rn;Eo=!0;var i=Jd(),e=Qd(),t=yo();return rn={formats:t,parse:e,stringify:i},rn}function Zd(){if(Ao)return Pt;Ao=!0;var i=Tt;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
|
+
`," "],s=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(s),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},h={javascript:!0,"javascript:":!0},b={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=Xd();function w(v,S,E){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,S,E),I}e.prototype.parse=function(v,S,E){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("#")?"?":"#",L=v.split(P),$=/\\/g;L[0]=L[0].replace($,"/"),v=L.join(P);var T=v;if(T=T.trim(),!E&&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],S?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):S&&(this.search="",this.query={}),this}var F=t.exec(T);if(F){F=F[0];var D=F.toLowerCase();this.protocol=D,T=T.substr(F.length)}if(E||F||T.match(/^\/\/[^@/]+@[^@/]+/)){var oe=T.substr(0,2)==="//";oe&&!(F&&h[F])&&(T=T.substr(2),this.slashes=!0)}if(!h[F]&&(oe||F&&!b[F])){for(var j=-1,W=0;W<c.length;W++){var re=T.indexOf(c[W]);re!==-1&&(j===-1||re<j)&&(j=re)}var U,Q;j===-1?Q=T.lastIndexOf("@"):Q=T.lastIndexOf("@",j),Q!==-1&&(U=T.slice(0,Q),T=T.slice(Q+1),this.auth=decodeURIComponent(U)),j=-1;for(var W=0;W<l.length;W++){var re=T.indexOf(l[W]);re!==-1&&(j===-1||re<j)&&(j=re)}j===-1&&(j=T.length),this.host=T.slice(0,j),T=T.slice(j),this.parseHost(),this.hostname=this.hostname||"";var O=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!O)for(var J=this.hostname.split(/\./),W=0,pe=J.length;W<pe;W++){var ee=J[W];if(ee&&!ee.match(d)){for(var ve="",G=0,R=ee.length;G<R;G++)ee.charCodeAt(G)>127?ve+="x":ve+=ee[G];if(!ve.match(d)){var ne=J.slice(0,W),V=J.slice(W+1),Y=ee.match(p);Y&&(ne.push(Y[1]),V.unshift(Y[2])),V.length&&(T="/"+V.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),O||(this.hostname=i.toASCII(this.hostname));var X=this.port?":"+this.port:"",be=this.hostname||"";this.host=be+X,this.href+=this.host,O&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!g[D])for(var W=0,pe=a.length;W<pe;W++){var se=a[W];if(T.indexOf(se)!==-1){var M=encodeURIComponent(se);M===se&&(M=escape(se)),T=T.split(se).join(M)}}var H=T.indexOf("#");H!==-1&&(this.hash=T.substr(H),T=T.slice(0,H));var te=T.indexOf("?");if(te!==-1?(this.search=T.substr(te),this.query=T.substr(te+1),S&&(this.query=y.parse(this.query)),T=T.slice(0,te)):S&&(this.search="",this.query={}),T&&(this.pathname=T),b[D]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var X=this.pathname||"",he=this.search||"";this.path=X+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 S=this.protocol||"",E=this.pathname||"",I=this.hash||"",P=!1,L="";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&&(L=y.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var $=this.search||L&&"?"+L||"";return S&&S.substr(-1)!==":"&&(S+=":"),this.slashes||(!S||b[S])&&P!==!1?(P="//"+(P||""),E&&E.charAt(0)!=="/"&&(E="/"+E)):P||(P=""),I&&I.charAt(0)!=="#"&&(I="#"+I),$&&$.charAt(0)!=="?"&&($="?"+$),E=E.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),$=$.replace("#","%23"),S+P+E+$+I};function k(v,S){return w(v,!1,!0).resolve(S)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function x(v,S){return v?w(v,!1,!0).resolveObject(S):S}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var S=new e;S.parse(v,!1,!0),v=S}for(var E=new e,I=Object.keys(this),P=0;P<I.length;P++){var L=I[P];E[L]=this[L]}if(E.hash=v.hash,v.href==="")return E.href=E.format(),E;if(v.slashes&&!v.protocol){for(var $=Object.keys(v),T=0;T<$.length;T++){var q=$[T];q!=="protocol"&&(E[q]=v[q])}return b[E.protocol]&&E.hostname&&!E.pathname&&(E.pathname="/",E.path=E.pathname),E.href=E.format(),E}if(v.protocol&&v.protocol!==E.protocol){if(!b[v.protocol]){for(var F=Object.keys(v),D=0;D<F.length;D++){var oe=F[D];E[oe]=v[oe]}return E.href=E.format(),E}if(E.protocol=v.protocol,!v.host&&!h[v.protocol]){for(var pe=(v.pathname||"").split("/");pe.length&&!(v.host=pe.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),pe[0]!==""&&pe.unshift(""),pe.length<2&&pe.unshift(""),E.pathname=pe.join("/")}else E.pathname=v.pathname;if(E.search=v.search,E.query=v.query,E.host=v.host||"",E.auth=v.auth,E.hostname=v.hostname||v.host,E.port=v.port,E.pathname||E.search){var j=E.pathname||"",W=E.search||"";E.path=j+W}return E.slashes=E.slashes||v.slashes,E.href=E.format(),E}var re=E.pathname&&E.pathname.charAt(0)==="/",U=v.host||v.pathname&&v.pathname.charAt(0)==="/",Q=U||re||E.host&&v.pathname,O=Q,J=E.pathname&&E.pathname.split("/")||[],pe=v.pathname&&v.pathname.split("/")||[],ee=E.protocol&&!b[E.protocol];if(ee&&(E.hostname="",E.port=null,E.host&&(J[0]===""?J[0]=E.host:J.unshift(E.host)),E.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(pe[0]===""?pe[0]=v.host:pe.unshift(v.host)),v.host=null),Q=Q&&(pe[0]===""||J[0]==="")),U)E.host=v.host||v.host===""?v.host:E.host,E.hostname=v.hostname||v.hostname===""?v.hostname:E.hostname,E.search=v.search,E.query=v.query,J=pe;else if(pe.length)J||(J=[]),J.pop(),J=J.concat(pe),E.search=v.search,E.query=v.query;else if(v.search!=null){if(ee){E.host=J.shift(),E.hostname=E.host;var ve=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;ve&&(E.auth=ve.shift(),E.hostname=ve.shift(),E.host=E.hostname)}return E.search=v.search,E.query=v.query,(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.href=E.format(),E}if(!J.length)return E.pathname=null,E.search?E.path="/"+E.search:E.path=null,E.href=E.format(),E;for(var G=J.slice(-1)[0],R=(E.host||v.host||J.length>1)&&(G==="."||G==="..")||G==="",ne=0,V=J.length;V>=0;V--)G=J[V],G==="."?J.splice(V,1):G===".."?(J.splice(V,1),ne++):ne&&(J.splice(V,1),ne--);if(!Q&&!O)for(;ne--;ne)J.unshift("..");Q&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),R&&J.join("/").substr(-1)!=="/"&&J.push("");var Y=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(ee){E.hostname=Y?"":J.length?J.shift():"",E.host=E.hostname;var ve=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;ve&&(E.auth=ve.shift(),E.hostname=ve.shift(),E.host=E.hostname)}return Q=Q||E.host&&J.length,Q&&!Y&&J.unshift(""),J.length>0?E.pathname=J.join("/"):(E.pathname=null,E.path=null),(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.auth=v.auth||E.auth,E.slashes=E.slashes||v.slashes,E.href=E.format(),E},e.prototype.parseHost=function(){var v=this.host,S=r.exec(v);S&&(S=S[0],S!==":"&&(this.port=S.substr(1)),v=v.substr(0,v.length-S.length)),v&&(this.hostname=v)},Pt.parse=w,Pt.resolve=k,Pt.resolveObject=x,Pt.format=m,Pt.Url=e,Pt}function sl(i){if(typeof i=="string")i=new URL(i);else if(!(i instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(i.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return nn?eh(i):th(i)}function eh(i){let e=i.hostname,t=i.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(wl,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,o=t[2];if(r<yl||r>vl||o!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function th(i){if(i.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=i.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 al(i){let e=bo.resolve(i),t=i.charCodeAt(i.length-1);(t===bl||nn&&t===gl)&&e[e.length-1]!==bo.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(kl,"%25")),!nn&&e.includes("\\")&&(e=e.replace(_l,"%5C")),e.includes(`
|
|
8
|
+
`)&&(e=e.replace(xl,"%0A")),e.includes("\r")&&(e=e.replace(Sl,"%0D")),e.includes(" ")&&(e=e.replace(El,"%09")),r.pathname=e,r}var ll,Yr,vo,Jr,Qr,wo,Xr,ko,Zr,_o,en,xo,tn,So,rn,Eo,Pt,Ao,Ve,cl,ul,dl,hl,pl,fl,ml,gl,bl,yl,vl,nn,wl,kl,_l,xl,Sl,El,rh=Qe(()=>{le(),ue(),ce(),vd(),Rd(),Kd(),nl(),ll=Object.freeze(Object.create(null)),Yr={},vo=!1,Jr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Qr={},wo=!1,Xr={},ko=!1,Zr={},_o=!1,en={},xo=!1,tn={},So=!1,rn={},Eo=!1,Pt={},Ao=!1,Ve=Zd(),Ve.parse,Ve.resolve,Ve.resolveObject,Ve.format,Ve.Url,cl=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Ve.URL=typeof URL<"u"?URL:null,Ve.pathToFileURL=al,Ve.fileURLToPath=sl,ul=Ve.Url,dl=Ve.format,hl=Ve.resolve,pl=Ve.resolveObject,fl=Ve.parse,ml=Ve.URL,gl=92,bl=47,yl=97,vl=122,nn=cl==="win32",wl=/\//g,kl=/%/g,_l=/\\/g,xl=/\n/g,Sl=/\r/g,El=/\t/g}),nh=me((i,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),Io=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.BufferedDuplex=void 0,i.writev=r;var e=$t(),t=(He(),je(qe));function r(n,s){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",s)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,s,a){super({objectMode:!0}),this.proxy=s,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,s,a){this.isSocketOpen?this.writeToProxy(n,s,a):this.writeQueue.push({chunk:n,encoding:s,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,s){this.writeQueue=[],this.proxy.destroy(),s(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,s,a){this.proxy.write(n,s)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:s,cb:a}=this.writeQueue.shift();this.writeToProxy(n,s,a)}}};i.BufferedDuplex=o}),on=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(i,"__esModule",{value:!0}),i.streamBuilder=i.browserStreamBuilder=void 0;var t=(He(),je(qe)),r=e(nh()),o=e(vt()),n=$t(),s=e(Lr()),a=Io(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!s.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(k=>{Object.prototype.hasOwnProperty.call(w,k)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,k)&&(m.wsOptions[k]=w[k])}),m}function 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 k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let x=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[x],k):v=new r.default(m,[x],k.wsOptions),v}function h(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[k],m):v=new WebSocket(x,[k]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let x=u(k,w),v=g(w,x,k),S=r.default.createWebSocketStream(v,k.wsOptions);return S.url=x,v.on("close",()=>{S.destroy()}),S};i.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let k,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,S=!m.objectMode,E=h(w,m),I=L(m,D,oe);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{E.close()});let P=typeof E.addEventListener<"u";E.readyState===E.OPEN?(k=I,k.socket=E):(k=new a.BufferedDuplex(m,I,E),P?E.addEventListener("open",$):E.onopen=$),P?(E.addEventListener("close",T),E.addEventListener("error",q),E.addEventListener("message",F)):(E.onclose=T,E.onerror=q,E.onmessage=F);function L(j,W,re){let U=new n.Transform({objectMode:j.objectMode});return U._write=W,U._flush=re,U}function $(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(j){l("WebSocket onClose",j),k.end(),k.destroy()}function q(j){l("WebSocket onError",j);let W=new Error("WebSocket error");W.event=j,k.destroy(W)}async function F(j){if(!I||!I.readable||!I.writable)return;let{data:W}=j;W instanceof ArrayBuffer?W=t.Buffer.from(W):W instanceof Blob?W=t.Buffer.from(await new Response(W).arrayBuffer()):W=t.Buffer.from(W,"utf8"),I.push(W)}function D(j,W,re){if(E.bufferedAmount>x){setTimeout(D,v,j,W,re);return}S&&typeof j=="string"&&(j=t.Buffer.from(j,"utf8"));try{E.send(j)}catch(U){return re(U)}re()}function oe(j){E.close(),j()}return k};i.browserStreamBuilder=y}),To={};Ht(To,{Server:()=>Ue,Socket:()=>Ue,Stream:()=>Ue,_createServerHandle:()=>Ue,_normalizeArgs:()=>Ue,_setSimultaneousAccepts:()=>Ue,connect:()=>Ue,createConnection:()=>Ue,createServer:()=>Ue,default:()=>Al,isIP:()=>Ue,isIPv4:()=>Ue,isIPv6:()=>Ue});function Ue(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Al,Il=Qe(()=>{le(),ue(),ce(),Al={_createServerHandle:Ue,_normalizeArgs:Ue,_setSimultaneousAccepts:Ue,connect:Ue,createConnection:Ue,createServer:Ue,isIP:Ue,isIPv4:Ue,isIPv6:Ue,Server:Ue,Socket:Ue,Stream:Ue}}),Tl=me((i,e)=>{le(),ue(),ce(),e.exports={}}),Cl=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(i,"__esModule",{value:!0});var t=e((Il(),je(To))),r=e(vt()),o=e(Tl()),n=(0,r.default)("mqttjs:tcp"),s=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};i.default=s}),Pl={};Ht(Pl,{default:()=>Ol});var Ol,ih=Qe(()=>{le(),ue(),ce(),Ol={}}),Ll=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(i,"__esModule",{value:!0});var t=(ih(),je(Pl)),r=e((Il(),je(To))),o=e(vt()),n=e(Tl()),s=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:p,...g}=c;if(p!==void 0){let h=(0,n.default)(u,d,p,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:h})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,s("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=a(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",p),d};i.default=l}),Ml=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(He(),je(qe)),t=$t(),r=Io(),o,n,s;function a(){let p=new t.Transform;return p._write=(g,h,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},p._flush=g=>{o.close({success(){g()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,g){let h=p.protocol==="wxs"?"wss":"ws",b=`${h}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(b=`${h}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(b=p.transformWsUrl(b,p,g)),b}function u(){o.onOpen(()=>{s.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(()=>{s.emit("close"),s.end(),s.destroy()}),o.onError(p=>{let g=new Error(p.errMsg);s.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 h=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let b=c(g,p);o=wx.connectSocket({url:b,protocols:[h]}),n=a(),s=new r.BufferedDuplex(g,n,o),s._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=s.destroy;return s.destroy=(w,m)=>(s.destroy=y,setTimeout(()=>{o.close({fail(){s._destroy(w,m)}})},0),s),u(),s};i.default=d}),Nl=me(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(He(),je(qe)),t=$t(),r=Io(),o,n,s,a=!1;function l(){let g=new t.Transform;return g._write=(h,b,y)=>{o.sendSocketMessage({data:h.buffer,success(){y()},fail(){y(new Error)}})},g._flush=h=>{o.closeSocket({success(){h()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,h){let b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,h)),y}function d(){a||(a=!0,o.onSocketOpen(()=>{s.socketReady()}),o.onSocketMessage(g=>{if(typeof g.data=="string"){let h=e.Buffer.from(g.data,"base64");n.push(h)}else{let h=new FileReader;h.addEventListener("load",()=>{if(h.result instanceof ArrayBuffer){n.push(e.Buffer.from(h.result));return}n.push(e.Buffer.from(h.result,"utf-8"))}),h.readAsArrayBuffer(g.data)}}),o.onSocketClose(()=>{s.end(),s.destroy()}),o.onSocketError(g=>{s.destroy(g)}))}var p=(g,h)=>{if(h.hostname=h.hostname||h.host,!h.hostname)throw new Error("Could not determine host. Specify host manually.");let b=h.protocolId==="MQIsdp"&&h.protocolVersion===3?"mqttv3.1":"mqtt";c(h);let y=u(h,g);return o=h.my,o.connectSocket({url:y,protocols:b}),n=l(),s=new r.BufferedDuplex(h,n,o),d(),s};i.default=p}),oh=me(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(i,"__esModule",{value:!0}),i.connectAsync=u;var t=e(vt()),r=e((rh(),je(il))),o=e(Li()),n=e(Lr());typeof De?.nextTick!="function"&&(De.nextTick=setImmediate);var s=(0,t.default)("mqttjs"),a=null;function l(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,g,h]=p;d.username=g,d.password=h}else d.username=d.auth}function c(d,p){if(s("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let b=r.default.parse(d,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof De<"u"&&(p.socksProxy=De.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=on().streamBuilder,a.wss=on().streamBuilder,a.mqtt=Cl().default,a.tcp=Cl().default,a.ssl=Ll().default,a.tls=a.ssl,a.mqtts=Ll().default):(a.ws=on().browserStreamBuilder,a.wss=on().browserStreamBuilder,a.wx=Ml().default,a.wxs=Ml().default,a.ali=Nl().default,a.alis=Nl().default)),!a[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 a[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function 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++),s("calling streambuilder for",p.protocol),a[p.protocol](b,p)}let h=new o.default(g,p);return h.on("error",()=>{}),h}function u(d,p,g=!0){return new Promise((h,b)=>{let y=c(d,p),w={connect:k=>{m(),h(y)},end:()=>{m(),h(y)},error:k=>{m(),y.end(),b(k)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(k=>{y.off(k,w[k])})}Object.keys(w).forEach(k=>{y.on(k,w[k])})})}i.default=c}),Rl=me(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(g,h,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(h,b);(!w||("get"in w?!h.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return h[b]}}),Object.defineProperty(g,y,w)}:function(g,h,b,y){y===void 0&&(y=b),g[y]=h[b]}),t=i&&i.__setModuleDefault||(Object.create?function(g,h){Object.defineProperty(g,"default",{enumerable:!0,value:h})}:function(g,h){g.default=h}),r=i&&i.__importStar||(function(){var g=function(h){return g=Object.getOwnPropertyNames||function(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(h)};return function(h){if(h&&h.__esModule)return h;var b={};if(h!=null)for(var y=g(h),w=0;w<y.length;w++)y[w]!=="default"&&e(b,h,y[w]);return t(b,h),b}})(),o=i&&i.__exportStar||function(g,h){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(h,b)&&e(h,g,b)},n=i&&i.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=i.KeepaliveManager=i.UniqueMessageIdProvider=i.DefaultMessageIdProvider=i.Store=i.MqttClient=i.connectAsync=i.connect=i.Client=void 0;var s=n(Li());i.MqttClient=s.default;var a=n(qs());i.DefaultMessageIdProvider=a.default;var l=n(bd());i.UniqueMessageIdProvider=l.default;var c=n(Rs());i.Store=c.default;var u=r(oh());i.connect=u.default,Object.defineProperty(i,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Ys());i.KeepaliveManager=d.default,i.Client=s.default,o(Li(),i),o(Kt(),i),o(Ns(),i);var p=Pr();Object.defineProperty(i,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),sh=me(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(s,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(s,c,u)}:function(s,a,l,c){c===void 0&&(c=l),s[c]=a[l]}),t=i&&i.__setModuleDefault||(Object.create?function(s,a){Object.defineProperty(s,"default",{enumerable:!0,value:a})}:function(s,a){s.default=a}),r=i&&i.__importStar||(function(){var s=function(a){return s=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},s(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=s(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=i&&i.__exportStar||function(s,a){for(var l in s)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,s,l)};Object.defineProperty(i,"__esModule",{value:!0});var n=r(Rl());i.default=n,o(Rl(),i)});const ah=sh();const lh={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}/#"},ch=300,uh={templateId:"7",type:"link",isDeepLink:!0},dh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class jl{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={...lh,...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,s)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:p?.message}),l(()=>s(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=ah.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,p)=>{this.dispatchInbound(d,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[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={...uh,...this.config.fileTemplate??{},...hh(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??{}},s=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,s)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=ch){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof o.status=="number"?o.status:Number(o.status??0),p={conversationId:c,messageId:u,status:d,raw:o};this.statusUpdateHandlers.forEach(g=>g(p)),this.messageHandlers.forEach(g=>g(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const s=e.match(this.inboundRegex),a=s?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:s?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...dh,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),s={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:s}}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 s={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=s[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function hh(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(e[t]=r);return e}function $l(i,e){return(i.sender??"").toString()===e}function Dl(i,e){const t=(i.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function Co(i){const e={raw:i},t=i.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 i.text=="string"&&i.text.trim().startsWith("{"))try{const o=i.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const s=n.metadata;s&&typeof s=="object"&&(typeof s.contentType=="string"&&(e.contentType=s.contentType),typeof s.templateId=="string"&&(e.templateId=s.templateId),s.payload!==void 0&&(e.payload=s.payload))}catch{}const r=i.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 Ul(i){const e=Co(i);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,s=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=i.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!s&&!a?null:{fileName:a,fileUrl:s,cloudFileId:c,templateId:e.templateId}}function Bl(i,e,t){const r=Dl(i,t),o=Co(i),n=Ul(i);let s="";o.innerMessage?s=o.innerMessage:typeof i.text=="string"&&(i.text.trim().startsWith("{")?o.contentType!=="300"&&(s=i.text):s=i.text);const a=typeof i.message_id=="string"?i.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof i.timestamp=="number"?new Date(i.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof i.status=="number"?ph(i.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:s,createdAt:l,status:u,metadata:{sender:i.sender,sender_fullname:i.sender_fullname??i.senderFullname,app_id:i.app_id,attributes:i.attributes}};return o.contentType&&(d.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:o}}function ph(i){return i<0?"error":i>=250?"read":i>=150?"delivered":"sent"}class Fl extends _r{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 Zo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new es,this.conversationManager=new os(e.conversationId),this.usesAikaara()&&(this.connection=new Xo(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 jl({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const o=r.map(l=>Bl(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),s=this.messageStore.messages,a=[...n,...s.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:o.fileName,fileUrl:o.url,cloudFileId:o.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:s,template:a}=Bl(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&s.role==="assistant")return;if($l(e,n)){const u=this.messageStore.reconcileOptimistic(s);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(s);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:o,role:s.role==="tool"?"system":s.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class fh extends _r{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 ql={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 mh(i){const e=i.lastIndexOf(".");return e<0||e===i.length-1?"":i.slice(e+1).toLowerCase()}function gh(i,e,t){const r=mh(i.name||"");if(r&&e&&e[r])return e[r];const o=i.type;return o&&o.trim().length>0?o:r&&ql[r]?ql[r]:t}function dr(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function bh(i,e){const t=e.split(".");let r=i;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function Hl(i){const e=i.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=gh(t,i.contentTypeMap,i.contentTypeFallback??"application/octet-stream"),s={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=i.authHeader?await i.authHeader():void 0,l={accept:"application/json",...i.extraHeaders??{},...a?{authorization:a}:{}};let c,u;if(i.signBody){c=dr(i.signEndpoint,s);const w=dr(JSON.stringify(i.signBody),s);u={method:i.signMethod??"POST",headers:{...l,"content-type":"application/json"},body:w}}else{let w=i.signEndpoint.includes("{")?i.signEndpoint:`${i.signEndpoint}?fileName={fileName}`;if(!w.includes("{contentType}")){const m=w.includes("?")?"&":"?";w=`${w}${m}contentType={contentType}`}c=dr(w,s),u={method:i.signMethod??"GET",headers:l}}const d=await fetch(c,u);if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const p=await d.json().catch(()=>({})),g=bh(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const h=i.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,i.s3HostRewrite):g,b=await fetch(h,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(i.registerEndpoint){const w=JSON.parse(dr(JSON.stringify(i.registerBody??{}),s)),m=await fetch(i.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:i.viewerTemplate?dr(i.viewerTemplate,s):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Po(i){return{async upload(e,t){const r=new FormData,o=i.fieldName??"file";r.append(o,e,e.name);const n=typeof i.extraFields=="function"?i.extraFields(t):i.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 s=typeof i.headers=="function"?await i.headers():i.headers??{},a=await fetch(i.endpoint,{method:i.method??"POST",body:r,headers:s,credentials:i.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(i.parseResponse)return i.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const yh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Wl(i){const e=i.apiBase.replace(/\/$/,""),t=i.pageSize??200,r=i.pathTemplate??yh;return{async fetchMessages(o,n){const s=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=s.startsWith("http")?s:`${e}${s.startsWith("/")?s:`/${s}`}`,l={accept:"application/json","content-type":"application/json",...i.extraHeaders??{}};if(i.getToken){const p=await i.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(i.parseResponse&&u)return i.parseResponse(u);if(Array.isArray(u))return u;const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const vh="^[A-Z]{4}[0-9]{5}[A-Z]$",wh="^\\S{12}$",zl="^[A-Z]{4}0[A-Z0-9]{6}$",Vl="^[0-9]{6}$",kh=[{id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:vh,uppercase:!0,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"rentalIncome",type:"number",label:"Rental Income",currency:"₹",min:0},{id:"propertyTax",type:"number",label:"Municipal Taxes",currency:"₹",min:0},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",fields:[{id:"lenderName",type:"text",label:"Bank / Institute Name"},{id:"sanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"loanAccountNumber",type:"text",label:"Loan Account No."},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"outstandingAmount",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"Amount",currency:"₹",min:0,max:15e4},{id:"us80cSubType",type:"text",label:"Investment Type",placeholder:"e.g. LIC, PPF, ELSS, NSC"},{id:"us80cPolicyNumber",type:"text",label:"Policy Number"}]},{id:"section80ccd1b",type:"group",title:"Section 80CCD(1B)",fields:[{id:"us80ccd1bAmount",type:"number",label:"Amount",currency:"₹",min:0},{id:"us80ccd1bPanNo",type:"text",label:"PRAN No.",pattern:wh,maxLength:12}]},{id:"section80ccd2",type:"group",title:"Section 80CCD(2)",fields:[{id:"us80ccd2Amount",type:"number",label:"Amount",currency:"₹",min:0}]},{id:"section80g",type:"group",title:"Section 80G — Donations",fields:[{id:"us80gDonationInCash",type:"number",label:"Donation In Cash",currency:"₹",min:0},{id:"us80gDonationOnline",type:"number",label:"Donation Through Online Mode",currency:"₹",min:0},{id:"us80gTransactionRefNo",type:"text",label:"Transaction Reference No.",required:!0,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gIfscCode",type:"text",label:"IFSC Code",required:!0,uppercase:!0,pattern:zl,maxLength:11,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gNameOfCharity",type:"text",label:"Name of Charity / Trust"},{id:"us80gCharityPan",type:"text",label:"Charity / Trust PAN",uppercase:!0},{id:"us80gTrustAddress",type:"text",label:"Trust / Charity Address"},{id:"us80gPincode",type:"text",label:"Pincode",maxLength:6,pattern:Vl}]},{id:"section80e",type:"group",title:"Section 80E — Education Loan Interest",fields:[{id:"us80eLoanTakenFrom",type:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{id:"us80eBankName",type:"text",label:"Bank Name"},{id:"us80eLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]},{id:"section80ee",type:"group",title:"Section 80EEB — Electric Vehicle Loan Interest",fields:[{id:"us80eeLoanTakenFrom",type:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{id:"us80eeBankName",type:"text",label:"Bank Name"},{id:"us80eeLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eeLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eeLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eeOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eeVehicleRegistrationNumber",type:"text",label:"Vehicle Registration Number"},{id:"us80eeInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Self — Amount",currency:"₹",min:0,max:25e3},{id:"us80dForSelfAndFamilyPolicyCompany",type:"text",label:"Self — Policy Company Name"},{id:"us80dForSelfAndFamilyPolicyNumber",type:"text",label:"Self — Policy Number"},{id:"hasParentOverSixty",type:"yes-no",label:"Parent Senior Citizen"},{id:"us80dForParentsAmount",type:"number",label:"Parents — Amount",currency:"₹",min:0,max:5e4},{id:"us80dForParentsPolicyCompany",type:"text",label:"Parents — Policy Company Name"},{id:"us80dForParentsPolicyNumber",type:"text",label:"Parents — Policy Number"}]}],submitLabel:"Save"},{id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureExpenditure",type:"number",label:"Expenditure on Agriculture",currency:"₹",min:0},{id:"agricultureLandGroup",type:"group",title:"Land Details",hint:"Optional - leave blank if you only need to report income",fields:[{id:"agricultureLandInAcre",type:"number",label:"Land Area (Acres)",min:0},{id:"agricultureLandDistrict",type:"text",label:"District"},{id:"agricultureLandPincode",type:"text",label:"Pincode",maxLength:6,pattern:Vl},{id:"agricultureLandOwner",type:"radio",label:"Ownership",options:[{value:"Owned",label:"Owned"},{value:"Held on lease",label:"Held on lease"}]},{id:"agricultureLandType",type:"radio",label:"Type of Land",options:[{value:"Irrigated",label:"Irrigated"},{value:"Rain-fed",label:"Rain-fed"}]}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:zl,maxLength:11}]}],submitLabel:"Save"}];function _h(i,e){const t=i||{},r={userId:tt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Ee(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:Rh()};r.us80cAmount=xe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=xe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=xe(t.us80dForParentsAmount),r.hasParentOverSixty=hr(t.hasParentOverSixty),r.preventiveHealthCheckUp=xe(t.preventiveHealthCheckUp),r.medicalExpenditure=xe(t.medicalExpenditure);const o=Gl(t,{userId:e.userId,assessmentYear:e.assessmentYear});o&&(r.donations80g=o.donations80g),r.savingBankInterest=xe(t.savingBankInterest),r.fdInterest=xe(t.fdInterest),r.dividend=xe(t.dividend),r.anyOtherIncome=xe(t.anyOtherIncome),r.familyPension=xe(t.familyPension),r.cryptoSellValue=xe(t.cryptoSellPrice),r.cryptoPurchaseAmount=xe(t.cryptoPurchasePrice),r.vdaPurchaseCost=xe(t.cryptoPurchasePrice);const n=(xe(t.bizReceiptsBank)??0)+(xe(t.bizReceiptsCash)??0),s=(xe(t.profReceiptsBank)??0)+(xe(t.profReceiptsCash)??0),a=Ee(t.bizName)!==void 0||n>0;r.businessName=Ee(a?t.bizName:t.profName),r.businessAnnualTurnOver=a?n||void 0:s||void 0,r.agricultureDetails=Yl(t),r.exemptIncomeAmount=xe(t.exemptIncome),r.exemptIncomeNature=Ee(t.exemptIncomeNature),xe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Ee(t.exemptIncomeNature)??"Exempt income",value:String(xe(t.exemptIncome))}]),r.bankAccountNumber=Ee(t.bankAccountNumber),r.bankIfscCode=Ee(t.bankIfscCode),(Ee(t.bankAccountNumber)||Ee(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Ee(t.bankAccountNumber),bankIfscCode:Ee(t.bankIfscCode)}]);const l={description:Ee(t.immovableAssetDescription),flatNo:Ee(t.immovableAssetFlatNo),area:Ee(t.immovableAssetArea),pinCode:Ee(t.immovableAssetPincode),amount:xe(t.immovableAssetCost)};Object.values(l).some(d=>d!==void 0)&&(r.immovableAsset=[l]);const c=Oo(t.hpDetails,xh);c.length&&(r.hpDetails=c);const u=Oo(t.salaryDetails,Sh);if(u.length){r.salaryIncome=u;const d=Oo(t.salaryDetails,g=>({grossSalary:xe(g.grossSalary),employerName:Ee(g.employerName)}));d.length&&(r.salary=d);const p=an(t.salaryDetails)[0]??{};r.hraAmount=xe(p.hraReceived),r.leaveTravelAllowanceAmount=xe(p.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=xe(p.leaveEncashment),r.anyOtherAllowanceAmount=xe(p.anyOtherAllowance),r.salaryIncomeFlag=!0}return rt(r)}function xh(i){const e={loanType:"HOME_LOAN",loanTakenFrom:Ee(i.loanTakenFrom),bankOrInstituteName:Ee(i.lenderName),loanAccountNo:Ee(i.loanAccountNumber),loanSanctionDate:sn(i.sanctionDate),totalLoanAmount:xe(i.totalLoanAmount),loanOutstandingAmount:xe(i.outstandingAmount),interest:xe(i.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Ee(i.typeOfHouseProperty),hasRentalIncome:i.typeOfHouseProperty==="LOP"?!0:hr(i.hasRentalIncome),homeLoanInterest:xe(i.homeLoanInterest),homeLoanPrinciple:xe(i.homeLoanPrinciple),housePropertyAddress:Ee(i.housePropertyAddress),housePropertyPincode:Ee(i.housePropertyPincode),rentalIncome:xe(i.rentalIncome),nameOfTenant:Ee(i.nameOfTenant),propertyTax:xe(i.propertyTax),hasCoOwnedProperty:hr(i.hasCoOwnedProperty),coOwnerName:Ee(i.coOwnerName),coOwnerPan:Ee(i.coOwnerPan),coOwnerShare:Ee(i.coOwnerShare),loanDetails:t?[e]:void 0}}function Sh(i){return{grossSalaryIncome:xe(i.grossSalary),salary:xe(i.basicSalary),totalTdsDeposited:xe(i.totalTdsDeposited),employer:{employerName:Ee(i.employerName),employerTan:Ee(i.employerTan)},allowance:{hraAmount:xe(i.hraReceived),leaveTravelAllowanceAmount:xe(i.leaveTravelAllowance),leaveEncashmentAllowanceAmount:xe(i.leaveEncashment),anyOtherAllowanceAmount:xe(i.anyOtherAllowance)}}}function Eh(i,e){const t=[];for(const r of i){const o=Ee(r.employerName),n=Ee(r.employerTan),s=xe(r.grossSalary),a=xe(r.basicSalary),l=xe(r.totalTdsDeposited);o===void 0&&n===void 0&&s===void 0&&a===void 0&&l===void 0||t.push({grossSalary:s??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function Ah(i,e){const t=Ee(i.aadhaarNumber),r=Ee(i.bankAccountNumber),o=Ee(i.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:tt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function Ih(i,e){return{userId:tt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:xe(i.savingBankInterest)??0,fdInterest:xe(i.fdInterest)??0,dividend:xe(i.dividend)??0,anyOtherIncome:xe(i.anyOtherIncome)??0,familyPension:xe(i.familyPension)??0}}function Th(i,e){const t=xe(i.cryptoSellPrice),r=xe(i.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:tt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function Ch(i,e){const t=(o,n,s,a)=>{const l=Ee(i[n]),c=xe(i[s]),u=xe(i[a]);return l===void 0&&c===void 0&&u===void 0?null:{businessType:o,businessCode:l??"",cashAmount:u??0,bankAmount:c??0}},r=[t("BUSINESS","bizNature","bizReceiptsBank","bizReceiptsCash"),t("PROFESSIONAL","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Ph(i){return Ee(i.lenderName)!==void 0||Ee(i.loanAccountNumber)!==void 0||xe(i.totalLoanAmount)!==void 0||xe(i.outstandingAmount)!==void 0||xe(i.homeLoanInterest)!==void 0}function Kl(i){const e=Ee(i.typeOfHouseProperty)?.toUpperCase();return xe(i.rentalIncome)!==void 0||Ee(i.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function Oh(i,e){const t=an(i.hpDetails).filter(Ph).map(r=>{const o=rt({loanType:"HOMELOAN",bankOrInstituteName:Ee(r.lenderName),loanAccountNo:Ee(r.loanAccountNumber),loanSanctionDate:sn(r.sanctionDate),totalLoanAmount:xe(r.totalLoanAmount),loanOutstandingAmount:xe(r.outstandingAmount),interest:xe(r.homeLoanInterest)});return rt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),homeLoanInterest:xe(r.homeLoanInterest),homeLoanPrinciple:xe(r.homeLoanPrinciple),propertyTax:xe(r.propertyTax),eligible80EEAAmount:xe(r.eligible80EEAAmount),eligible80EEAmount:xe(r.eligible80EEAmount),hasCoOwnedProperty:hr(r.hasCoOwnedProperty)??!1,hasRentalIncome:Kl(r),loanDetails:[o]})});return t.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Lh(i,e){const t=an(i.hpDetails).filter(Kl).map(r=>rt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),rentalIncome:xe(r.rentalIncome),propertyTax:xe(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Ee(r.nameOfTenant),tenantPanNumber:Ee(r.tenantPanNumber),homeLoanInterest:xe(r.homeLoanInterest)}));return t.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Mh(i,e){const t=i||{},r=g=>({userId:tt(e.userId),assessmentYear:e.assessmentYear,deductions:rt(g)}),o=[],n=xe(t.us80cAmount);if(n!==void 0){const g=Ee(t.us80cSubType);g?o.push(r({deductionSection:"80C",subType:g,amount:n,accountNo:Ee(t.us80cPolicyNumber)})):console.warn("[smart-edit] 80C skipped — Investment Type is required by the API")}const s=Ee(t.us80ccd1bPanNo),a=xe(t.us80ccd1bAmount);a!==void 0&&o.push(r({deductionSection:"80CCD(1B)",subType:"NPS",amount:a,accountNo:s}));const l=xe(t.us80ccd2Amount);l!==void 0&&o.push(r({deductionSection:"80CCD(2)",subType:"EMPLOYER_NPS",amount:l,accountNo:s}));const c=xe(t.us80eInterest);c!==void 0&&o.push(r({deductionSection:"80E",subType:"EDUCATION_LOAN",interest:c,loanTakenFrom:Ee(t.us80eLoanTakenFrom),bankOrInstituteName:Ee(t.us80eBankName),loanAccountNo:Ee(t.us80eLoanAccountNumber),loanSanctionDate:sn(t.us80eLoanSanctionDate),totalLoanAmount:xe(t.us80eLoanAmount),loanOutstandingAmount:xe(t.us80eOutstandingLoan)}));const u=xe(t.us80eeInterest);u!==void 0&&o.push(r({deductionSection:"80EEB",interest:u,loanTakenFrom:Ee(t.us80eeLoanTakenFrom),bankOrInstituteName:Ee(t.us80eeBankName),loanAccountNo:Ee(t.us80eeLoanAccountNumber),loanSanctionDate:sn(t.us80eeLoanSanctionDate),totalLoanAmount:xe(t.us80eeLoanAmount),loanOutstandingAmount:xe(t.us80eeOutstandingLoan),vehicleRegistrationNo:Ee(t.us80eeVehicleRegistrationNumber)}));const d=xe(t.us80dForSelfAndFamilyAmount);d!==void 0&&o.push(r({deductionSection:"80D",subType:"selfFamilyPremium80D",amount:d,insurerName:Ee(t.us80dForSelfAndFamilyPolicyCompany),accountNo:Ee(t.us80dForSelfAndFamilyPolicyNumber)}));const p=xe(t.us80dForParentsAmount);return p!==void 0&&o.push(r({deductionSection:"80D",subType:"parentsPremium80D",amount:p,insurerName:Ee(t.us80dForParentsPolicyCompany),accountNo:Ee(t.us80dForParentsPolicyNumber),parentSeniorCitizen:hr(t.hasParentOverSixty)??!1})),o}function Gl(i,e){const t=i||{},r=xe(t.us80gDonationInCash),o=xe(t.us80gDonationOnline),n=Ee(t.us80gNameOfCharity);if(r===void 0&&o===void 0&&n===void 0)return null;const s=(o??0)>0;return{userId:tt(e.userId),assessmentYear:e.assessmentYear,donations80g:[rt({name:n,panNumber:Ee(t.us80gCharityPan),amountInCash:r,amountOtherThanCash:o,address:Ee(t.us80gTrustAddress),pinCode:Ee(t.us80gPincode),transactionRefNum:s?Ee(t.us80gTransactionRefNo):void 0,ifscCode:s?Ee(t.us80gIfscCode):void 0})]}}function Yl(i){const e=i||{},t=xe(e.agricultureIncome),r=xe(e.agricultureExpenditure),o=rt({landInAcre:xe(e.agricultureLandInAcre),nameOfDistrict:Ee(e.agricultureLandDistrict),pinCode:Ee(e.agricultureLandPincode),owner:Ee(e.agricultureLandOwner),typeOfLand:Ee(e.agricultureLandType)})??{},n=Object.keys(o).length>0;if(!(t===void 0&&r===void 0&&!n))return rt({income:t,expenditure:r??0,agricultureLandDetails:n?[o]:void 0})}function Nh(i,e){const t=Yl(i);return t?{userId:tt(e.userId),assessmentYear:e.assessmentYear,agricultureDetails:t}:null}function tt(i){if(i===void 0||i==="")return;const e=Number(i);return Number.isFinite(e)&&String(e)===String(i)?e:i}function xe(i){if(i==null||i==="")return;const e=typeof i=="number"?i:Number(i);return Number.isFinite(e)?e:void 0}function Ee(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function hr(i){return i===!0||i===!1?i:void 0}function Rh(){const i=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${i.getFullYear()}-${e(i.getMonth()+1)}-${e(i.getDate())}T${e(i.getHours())}:${e(i.getMinutes())}:${e(i.getSeconds())}.${e(i.getMilliseconds(),3)}`}function sn(i){const e=Ee(i);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function an(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Oo(i,e){return an(i).map(t=>rt(e(t))).filter(t=>t!==void 0)}function rt(i){if(Array.isArray(i)){const e=i.map(rt).filter(t=>t!==void 0);return e.length?e:void 0}if(i&&typeof i=="object"){const e={};for(const[t,r]of Object.entries(i)){const o=rt(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return i}function jh(i){const e=i&&typeof i=="object"?i:{},t={},r=$e(e.employers),o=$e(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(j=>{const W=Mo(j.salary),re=Mo(j.perquisites),U=Mo(j.profitsInLieuOfSalaryType),Q=W+re+U,O=qh(j.allowance);return{employerName:Ie(j.employerName),employerTan:Ie(j.employerTAN),basicSalary:W||void 0,grossSalary:Q||void 0,hraReceived:O.hra,leaveTravelAllowance:O.lta,leaveEncashment:O.leaveEncashment,anyOtherAllowance:O.other,totalTdsDeposited:Fh(j,o,r)??Oe(j.totalTdsDeposited)}}));const n=$e(e.houseProperties);n.length&&(t.hpDetails=n.map(j=>{const W=$e(j.loanDetails),re=W.length?W[0]:void 0,U=Oe(j.grossAnnualRentReceived),Q=W.length?W.reduce((ve,G)=>ve+(Oe(G.interest)??0),0):void 0,O=$e(j.tenant),J=$e(j.coOwners),pe=O[0],ee=J[0];return{typeOfHouseProperty:Ie(j.propertyType),loanTakenFrom:Ie(re?.loanTakenFrom),lenderName:Ie(re?.bankOrInstituteName),loanAccountNumber:Ie(re?.loanAccountNo),sanctionDate:Lo(re?.loanSanctionDate),totalLoanAmount:Oe(re?.totalLoanAmount),outstandingAmount:Oe(re?.loanOutstandingAmount),homeLoanInterest:Q,homeLoanPrinciple:void 0,housePropertyAddress:Ie(j.address),housePropertyPincode:Ie(j.pinCode),rentalIncome:U,nameOfTenant:Ie(pe?.name),tenantPanNumber:Ie(pe?.panNumber),eligible80EEAmount:Oe(j.eligible80EEAmount),eligible80EEAAmount:Oe(j.eligible80EEAAmount),propertyTax:Oe(j.propertyTax),hasCoOwnedProperty:J.length>0,coOwnerName:Ie(ee?.name),coOwnerPan:Ie(ee?.panNumber),coOwnerShare:Oe(ee?.share)?.toString()}}));const s=$e(e.deductionUS80CDetails),a=Ot(s.map(j=>Oe(j.amount))),l=s.find(j=>Ie(j.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ie(l?.identificationNo);const c=$e(e.investments),u=c.find(j=>!Dh(Ie(j.investmentType))),d=Array.isArray(u?.bifurcation)?u.bifurcation[0]:void 0;t.us80cSubType=Ie(d?.subType??u?.investmentType);const p=$e(e.deductionUS80DDetails),g=p.find(j=>Ie(j.policyFor)?.toUpperCase()==="DEPENDANT")??$e(e.insurances).find(j=>Ie(j.policyFor)?.toUpperCase()==="DEPENDANT"),h=p.find(j=>Ie(j.policyFor)?.toUpperCase()==="PARENTS")??$e(e.insurances).find(j=>Ie(j.policyFor)?.toUpperCase()==="PARENTS"),b=Array.isArray(g?.bifurcation)?g.bifurcation[0]:void 0,y=Array.isArray(h?.bifurcation)?h.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Oe(g?.healthInsuranceAmount??g?.premium),t.us80dForSelfAndFamilyPolicyCompany=Ie(g?.insurerName??b?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Ie(g?.policyNo??b?.accountNo),t.us80dForParentsAmount=Oe(h?.healthInsuranceAmount??h?.premium),t.us80dForParentsPolicyCompany=Ie(h?.insurerName??y?.insurerName),t.us80dForParentsPolicyNumber=Ie(h?.policyNo??y?.accountNo),t.hasParentOverSixty=Hh(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=Oe(e.us80ccd1bAmount)??Jl(c,"PENSION_SCHEME"),t.us80ccd1bPanNo=Ie(e.pranNumber)??Ie(e.us80ccd1bPanNo),t.us80ccd2Amount=Oe(e.us80ccd2Amount)??Jl(c,"PS_EMPLOYER");const m=$e(e.donations)[0];t.us80gDonationInCash=Oe(m?.amountInCash??m?.donationInCash),t.us80gDonationOnline=Oe(m?.amountOtherThanCash??m?.amount??m?.donationAmount),t.us80gNameOfCharity=Ie(m?.name??m?.nameOfCharity??m?.donorName??m?.trustName),t.us80gCharityPan=Ie(m?.panNumber??m?.charityPan),t.us80gTrustAddress=Ie(m?.address??m?.charityAddress),t.us80gPincode=Ie(m?.pinCode??m?.pincode),t.us80gTransactionRefNo=Ie(m?.transactionRefNum??m?.transactionReferenceNo??m?.transactionRefNo),t.us80gIfscCode=Ie(m?.ifscCode??m?.ifsCode);const k=$e(e.loanDetails),x=j=>k.find(W=>Ie(W.loanType)?.toUpperCase()===j),v=x("EDUCATION"),S=x("ELECTRIC_VEHICLE");t.us80eLoanTakenFrom=Ie(v?.loanTakenFrom),t.us80eBankName=Ie(v?.bankOrInstituteName),t.us80eLoanAccountNumber=Ie(v?.loanAccountNo),t.us80eLoanSanctionDate=Lo(v?.loanSanctionDate),t.us80eLoanAmount=Oe(v?.totalLoanAmount),t.us80eOutstandingLoan=Oe(v?.loanOutstandingAmount),t.us80eInterest=Oe(v?.interest),t.us80eeLoanTakenFrom=Ie(S?.loanTakenFrom),t.us80eeBankName=Ie(S?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ie(S?.loanAccountNo),t.us80eeLoanSanctionDate=Lo(S?.loanSanctionDate),t.us80eeLoanAmount=Oe(S?.totalLoanAmount),t.us80eeOutstandingLoan=Oe(S?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ie(S?.vehicleRegistrationNo),t.us80eeInterest=Oe(S?.interest);const E=$e(e.insurances);t.preventiveHealthCheckUp=Ot(E.map(j=>Oe(j.preventiveCheckUp))),t.medicalExpenditure=Ot(E.map(j=>Oe(j.medicalExpenditure)));const I=$e(e.incomes),P=j=>Ot(I.filter(W=>Ie(W.incomeType)===j).map(W=>Oe(W.amount)));t.savingBankInterest=P("SAVING_INTEREST"),t.fdInterest=P("FD_RD_INTEREST"),t.anyOtherIncome=P("ANY_OTHER"),t.familyPension=P("FAMILY_PENSION"),t.dividend=Ot($e(e.dividendIncomes).map(j=>Oe(j.income)));const L=e.business;if(L){const j=$e(L.presumptiveIncomes),W=Q=>{const O=Ie(Q.businessType)?.trim().toUpperCase()??"";if(O.includes("PROFESSION")||O==="44ADA")return!0;if(O.includes("BUSINESS")||O==="44AD"||O==="PRESUMPTIVE")return!1;const J=$e(Q.incomes),pe=ee=>Oe(J.find(ve=>Ie(ve.incomeType)===ee)?.receipts)??0;return pe("ANY_OTHER")>0?!0:(pe("BANK")>0||pe("CASH")>0,!1)},re=Q=>j.find(O=>W(O)===Q),U=(Q,O)=>{if(!Q)return;const J=$e(Q.incomes),pe=ve=>Oe(J.find(G=>Ie(G.incomeType)===ve)?.receipts),ee=pe("BANK")||pe("ANY_OTHER");t[O.nature]=Ie(Q.natureOfBusiness),t[O.bank]=ee||void 0,t[O.cash]=pe("CASH")||void 0,t[O.net]=Ot(J.map(ve=>Oe(ve.presumptiveIncome)))||void 0};U(re(!1),{nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),U(re(!0),{nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const $=$e(e.capitalGain).filter(j=>Ie(j.assetType)?.toUpperCase()==="VDA").flatMap(j=>$e(j.assetDetails));$.length&&(t.cryptoSellPrice=Ot($.map(j=>Oe(j.sellValue))),t.cryptoPurchasePrice=Ot($.map(j=>Oe(j.purchaseCost))));const T=e.agriculturalDetails,q=e.agriculturalIncome;t.agricultureIncome=Oe(q?.grossAgriculturalReceipts)??Oe(q?.netAgriculturalIncome)??Oe(T?.income),t.agricultureExpenditure=Oe(q?.expenditureIncurredOnAgriculture)??Oe(T?.expenditure);const D=([$e(e.agriculturalLandDetails),$e(T?.agricultureLandDetails),$e(T?.agriculturalLandDetails)].find(j=>j.length>0)??[])[0];D&&(t.agricultureLandInAcre=Oe(D.landInAcre),t.agricultureLandDistrict=Ie(D.nameOfDistrict),t.agricultureLandPincode=Ie(D.pinCode),t.agricultureLandOwner=Uh(D.owner),t.agricultureLandType=Bh(D.typeOfLand)),t.aadhaarNumber=Ie(e.aadharNumber);const oe=$e(e.bankDetails)[0];return oe&&(t.bankAccountNumber=Ie(oe.accountNumber),t.bankIfscCode=Ie(oe.ifsCode)),Ql(t)}const $h=["PENSION_SCHEME","PS_EMPLOYER","PS_EMPLOYEE","PENSION_FUND"];function Dh(i){const e=i?.trim().toUpperCase();return!!e&&$h.includes(e)}function Jl(i,e){const t=i.find(r=>Ie(r.investmentType)?.toUpperCase()===e);return Oe(t?.amount)}function Uh(i){const e=Ie(i)?.trim();if(!e)return;const t=e.toUpperCase();return t==="O"||t==="OWNED"?"Owned":t==="H"||t.startsWith("HELD")?"Held on lease":e}function Bh(i){const e=Ie(i)?.trim();if(!e)return;const t=e.toUpperCase();return t==="IRG"||t==="IRRIGATED"?"Irrigated":t==="RF"||t.startsWith("RAIN")?"Rain-fed":e}function Lo(i){const e=Ie(i);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function Mo(i){return $e(i).reduce((e,t)=>e+(Oe(t.taxableAmount)??0),0)}function Fh(i,e,t){if(!e.length)return;const r=Ie(i.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ie(n.deductorTAN)?.trim().toUpperCase()===r)return Oe(n.totalTdsDeposited)}const o=Ie(i.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Ie(n.deductorName)?.trim().toLowerCase()===o)return Oe(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Oe(e[0].totalTdsDeposited)}function qh(i){const e=$e(i);if(!e.length)return{};let t,r,o,n;for(const s of e){const a=Oe(s.exemptAmount)??Oe(s.allowanceAmount);switch(Ie(s.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Oe(s.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Ot(i){let e=0,t=!1;for(const r of i)r!=null&&(e+=r,t=!0);return t?e:void 0}function $e(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Oe(i){if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"&&i.trim()!==""&&Number.isFinite(Number(i)))return Number(i)}function Ie(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function Hh(i){if(typeof i=="boolean")return i;if(typeof i=="string"){const e=i.trim().toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="y")return!0;if(e==="false"||e==="0"||e==="no"||e==="n")return!1}if(typeof i=="number")return i===1?!0:i===0?!1:void 0}function Ql(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?Ql(o):o):e[t]=r);return e}function No(){if(typeof window>"u")return null;const i=window,e=i.__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=i.__aikaara_descriptor__??{},r=ep(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=tp(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",s=e.getChatJwt,a=async()=>n||await s(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):np(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:rp(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||ip(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function Wh(i){const e=await i.getToken(),t=i.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${i.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...i.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 jh(Ro(await r.json().catch(()=>({}))))}async function zh(i,e){const t=await i.getToken(),r=i.userId,o={..._h(e,{userId:r,assessmentYear:i.assessmentYear,isRevised:i.isRevised}),sendSummary:!0},n=i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...i.headers};i.txbdyApiKey&&(s["txbdy-api-key"]=i.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:s,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Ro(await a.json().catch(()=>({})))}async function Vh(i,e){return xt(i,`${i.baseUrl}/itr/v1/automation/salary`,e)}async function Kh(i,e){return xt(i,`${i.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Xl(i,e){return xt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Gh(i,e){return xt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Yh(i,e){return xt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Jh(i,e){return xt(i,`${i.baseUrl}/itr/v1/automation/deductions`,e)}async function Qh(i,e){return xt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Xh(i,e){return xt(i,`${i.baseUrl}/itr/v1/automation/hp-income`,e)}async function Zh(i,e){return xt(i,`${i.baseUrl}/itr/v1/automation/vda`,e)}async function xt(i,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await i.getToken()}`,...i.headers};i.txbdyApiKey&&(o["txbdy-api-key"]=i.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 s=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${s.slice(0,200)}`)}return Ro(await n.json().catch(()=>({})))}function ep(i){const e=[i.cloud?.listEndpoint,i.cloud?.downloadEndpoint,i.upload?.signEndpoint,i.login?.pan?.basicPanEndpoint,i.login?.pan?.panDetailEndpoint,i.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 tp(i){if(!i||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${i}`);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 rp(i){const e={};if(!i)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(i))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function np(i){if(!i)return;const e=i.userId??i.id??i.ext_uid??i.extUid;return e==null||e===""?void 0:String(e)}function Ro(i){if(i&&typeof i=="object"){const e=i;return e.data&&typeof e.data=="object"?e.data:e}return{}}function ip(){const i=new Date,e=i.getMonth()>=3?i.getFullYear():i.getFullYear()-1;return`${e}-${e+1}`}const op=["No, I have concerns","No, I have a concerns"];function ln(i){const e=window.__aikaara_descriptor__?.smartEdit?.openOnMessages,t=Array.isArray(e)?e:op;if(t.length===0)return!1;const r=n=>n.trim().toLowerCase(),o=r(i);return t.some(n=>typeof n=="string"&&r(n)===o)}function jo(i){return!Array.isArray(i)||i.length===0||!i.every(t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!("type"in t)&&!("data"in t)&&typeof t.message=="string")?!1:i.some(t=>{const{message:r,title:o}=t;return ln(r)||typeof o=="string"&&ln(o)})}class sp{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Fl(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(ln(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)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:kh,data:{}});const t=No();if(!(!t||!t.baseUrl))try{const r=await Wh(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=No();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],s=Eh(n,o);s&&await Vh(r,s)}else if(e==="bank-details"){const n=Ah(t,o);n&&await Kh(r,n)}else if(e==="other-sources")await Xl(r,Ih(t,o));else if(e==="business-profession"){const n=Ch(t,o);n&&await Gh(r,n)}else if(e==="crypto-income"){const n=Th(t,o);n&&await Zh(r,n)}else if(e==="agricultural-income"){const n=Nh(t,o);n&&await Yh(r,n)}else if(e==="deductions"){const n=Gl(t,o);n&&await Xl(r,n);for(const s of Mh(t,o))await Jh(r,s)}else if(e==="house-property"){const n=Oh(t,o);n&&await Qh(r,n);const s=Lh(t,o);s&&await Xh(r,s)}}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=No();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await zh(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 Zl 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||Xc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Jo,position:this.getAttribute("position")||this._config.position||Qc,width:Number(this.getAttribute("width"))||this._config.width||Kc,height:Number(this.getAttribute("height"))||this._config.height||Gc,fontFamily:this._config.fontFamily||Jc,borderRadius:this._config.borderRadius??Yc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Qo,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||Zc,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,s=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};s("primary",e?.primary??t),s("primary-hover",e?.primaryHover),s("primary-contrast",e?.primaryContrast),s("surface",e?.surface),s("surface-muted",e?.surfaceMuted),s("border",e?.border),s("text",e?.text),s("text-muted",e?.textMuted),s("font",e?.font??o),s("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),s("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),s("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),s("user-bubble-bg",e?.userBubbleBg),s("user-bubble-text",e?.userBubbleText),s("bot-bubble-bg",e?.botBubbleBg),s("bot-bubble-text",e?.botBubbleText),s("modal-width",e?.modalWidth),s("modal-height",e?.modalHeight),s("modal-max-width",e?.modalMaxWidth),s("modal-max-height",e?.modalMaxHeight),s("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
|
|
9
9
|
`)}setUploadAdapter(e){this._config.uploadAdapter=e,this.controller?.getClient().setUploadAdapter(e)}setHistoryAdapter(e){this._config.historyAdapter=e}render(){const e=this.getConfig(),t=e.display==="embed";this.propagateThemeToDocument(e.themeTokens,e.primaryColor,e.borderRadius,e.fontFamily);const r=`
|
|
10
10
|
font-family: var(--aikaara-font);
|
|
11
11
|
position: fixed;
|
|
@@ -119,7 +119,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
119
119
|
></aikaara-chat-input>
|
|
120
120
|
<aikaara-error-banner></aikaara-error-banner>
|
|
121
121
|
</div>
|
|
122
|
-
`;const a=this.shadow.querySelector("aikaara-message-list");if(a){e.hideSystemMessages?.length&&a.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&a.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&a.setShowTimestamps?.(e.showTimestamps);const l=e.templateLayout;l&&a.setTemplateLayout?.(l)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new sp(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
|
|
122
|
+
`;const a=this.shadow.querySelector("aikaara-message-list");if(a){e.hideSystemMessages?.length&&a.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&a.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&a.setShowTimestamps?.(e.showTimestamps);const l=e.templateLayout;l&&a.setTemplateLayout?.(l)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new sp(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 ec 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 ap=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class
|
|
157
|
+
`}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const ap=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class tc extends HTMLElement{shadow;actions=ap;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",s=this.actions.map(a=>`
|
|
158
158
|
<button class="menu-item" type="button" data-action-id="${a.id}" data-action-label="${a.label}">
|
|
159
159
|
<span class="menu-item-icon">${this.iconSvg(a.icon)}</span>
|
|
160
160
|
<span class="menu-item-label">${a.label}</span>
|
|
@@ -314,7 +314,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
314
314
|
</button>
|
|
315
315
|
</div>
|
|
316
316
|
</div>
|
|
317
|
-
`}setStatus(e){this.setAttribute("status",e)}}const lp=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,cp=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,up={""":'"',"'":"'","<":"<",">":">","&":"&"," ":" "};function dp(i){return i.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>up[e.toLowerCase()]??e).replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,10))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/&/gi,"&")}function Jt(i){if(lp.test(i))return i;const e=cp.test(i)?dp(i):i;let t=hp(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 s=/[.,!?;:]+$/.exec(n),a=s?s[0]:"",l=a?n.slice(0,n.length-a.length):n;return`${o}<a href="${l}" target="_self" rel="noopener noreferrer">${l}</a>${a}`}),t=t.replace(/\n/g,"<br>"),t}function hp(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return i.replace(/[&<>"']/g,t=>e[t])}const pp=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"]),fp={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 Qt(i){const e=document.createElement("template");return e.innerHTML=i,
|
|
317
|
+
`}setStatus(e){this.setAttribute("status",e)}}const lp=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,cp=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,up={""":'"',"'":"'","<":"<",">":">","&":"&"," ":" "};function dp(i){return i.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>up[e.toLowerCase()]??e).replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,10))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/&/gi,"&")}function Jt(i){if(lp.test(i))return i;const e=cp.test(i)?dp(i):i;let t=hp(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 s=/[.,!?;:]+$/.exec(n),a=s?s[0]:"",l=a?n.slice(0,n.length-a.length):n;return`${o}<a href="${l}" target="_self" rel="noopener noreferrer">${l}</a>${a}`}),t=t.replace(/\n/g,"<br>"),t}function hp(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return i.replace(/[&<>"']/g,t=>e[t])}const pp=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"]),fp={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 Qt(i){const e=document.createElement("template");return e.innerHTML=i,rc(e.content),e.innerHTML}function rc(i){const e=Array.from(i.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,o=r.tagName.toLowerCase();if(!pp.has(o)){const a=document.createTextNode(r.textContent||"");i.replaceChild(a,t);continue}const n=fp[o]||new Set,s=Array.from(r.attributes);for(const a of s)n.has(a.name)||r.removeAttribute(a.name);if(r.hasAttribute("href")){const a=r.getAttribute("href")||"";!a.startsWith("http://")&&!a.startsWith("https://")&&!a.startsWith("/")&&r.removeAttribute("href")}rc(t)}}function nc(i,e={}){const{width:t=600,height:r=700,closeOnTypes:o}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),s=Math.round(window.screenY+(window.outerHeight-r)/2),a=window.open(i,"aikaara_popup",`width=${t},height=${r},left=${n},top=${s},resizable=yes,scrollbars=yes,status=yes`);if(!a)return null;const l=u=>{if(u.source!==a)return;const d=u.data?.type;o&&typeof d=="string"&&!o.includes(d)||(a.close(),window.removeEventListener("message",l))};window.addEventListener("message",l);const c=setInterval(()=>{a.closed&&(window.removeEventListener("message",l),clearInterval(c))},500);return a}function mp(i){const e=Date.now()-i.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`:i.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class ic 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(s=>s&&s.tagName==="A");if(!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment"))return;const o=this.linkHandlers.some(s=>oc(r.href,s.match));r.target==="_self"&&!o||t.some(s=>{if(!s||!s.classList)return!1;const a=s.classList;return a.contains("bubble")&&a.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
|
|
318
318
|
<style>
|
|
319
319
|
:host {
|
|
320
320
|
display: flex;
|
|
@@ -475,7 +475,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
475
475
|
}
|
|
476
476
|
</style>
|
|
477
477
|
<div class="message-list"></div>
|
|
478
|
-
`,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${Qt(Jt(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 s=n.metadata?.attributes?.action;if(s){const a=gp(s);if(s.message_id&&t.set(s.message_id,a),Object.keys(a).length>0)for(let l=o-1;l>=0;l--){const c=e[l];if(c.role!=="user"&&c.template?.contentType){if(jo(c.template.payload))break;const u=c.externalId??c.id,d=t.get(u);(!d||Object.keys(d).length===0)&&t.set(u,a);break}}}}if(n.role!=="user"&&n.template?.contentType&&o<r&&!jo(n.template.payload)){const s=n.externalId??n.id;t.has(s)||t.set(s,{})}}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=Qt(Jt(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
|
|
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">${Qt(Jt(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 s=n.metadata?.attributes?.action;if(s){const a=gp(s);if(s.message_id&&t.set(s.message_id,a),Object.keys(a).length>0)for(let l=o-1;l>=0;l--){const c=e[l];if(c.role!=="user"&&c.template?.contentType){if(jo(c.template.payload))break;const u=c.externalId??c.id,d=t.get(u);(!d||Object.keys(d).length===0)&&t.set(u,a);break}}}}if(n.role!=="user"&&n.template?.contentType&&o<r&&!jo(n.template.payload)){const s=n.externalId??n.id;t.has(s)||t.set(s,{})}}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=Qt(Jt(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 o=document.createElement("div");o.classList.add("bubble",e.role);const s=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?o.classList.add("attachment-only"):o.textContent=e.content:s?e.content&&(o.innerHTML=Qt(Jt(e.content))):(o.innerHTML=Qt(Jt(e.content||"")),e.status==="streaming"&&o.classList.add("streaming-cursor"));let a=null;if(e.template?.contentType){const d=document.createElement("aikaara-template-renderer");d.setAttribute("content-type",e.template.contentType),e.template.templateId&&d.setAttribute("template-id",e.template.templateId);const p=e.externalId??e.id;p&&d.setAttribute("message-id",p),d.setPayload(e.template.payload),t!==void 0&&!jo(e.template.payload)&&(d.dataset.consumed="true",Object.keys(t).length>0&&d.setConsumedValues?.(t)),this.templateLayout==="outside"?(d.classList.add("template-outside"),a=d):o.appendChild(d)}const l=e.template?.templateId==="7";if(e.attachments?.length&&!l){const d=document.createElement("div");d.classList.add("attachments");for(const p of e.attachments){const g=document.createElement("aikaara-template-renderer");g.setAttribute("content-type","300"),g.setAttribute("template-id","7");const h={elements:[{description:p.fileName,action:{url:p.fileUrl,type:"link",isDeepLink:!0}}]};g.setPayload(h,""),d.appendChild(g)}o.appendChild(d)}const u=!(o.childNodes.length===0&&(o.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(o),a&&r.appendChild(a),(u||a)&&this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const d=document.createElement("div");if(d.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(d.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const 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 mp(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=>oc(e,g.match)),o=r?.target??"iframe";if(o==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(o==="popup"){nc(e);return}const n=this.getOrCreateModal(),s=r?.title??t??"Link";if(o==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,s));return}const a=bp(e),l=sc(r.fetch.url,a),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const g=await this.getLinkBearer(u);g&&(c.authorization=`Bearer ${g}`)}const d={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",d.body=JSON.stringify($o(r.fetch.body,a)));let p=null;try{const g=await fetch(l,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,s,g=>{const h=r.props??{setData:p};for(const[y,w]of Object.entries(h)){const m=g[y];typeof m=="function"&&m.call(g,w)}const b=y=>{const w=y,m=w.detail?.message??w.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...w.detail?.attributes??{}}},bubbles:!0,composed:!0})))};g.addEventListener("aikaara-plan-select",b),g.addEventListener("aikaara-select",b)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function gp(i){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,o]of Object.entries(i))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}function oc(i,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(i)}function bp(i){try{const e=new URL(i),t={};return e.searchParams.forEach((r,o)=>{t[o]=r}),t}catch{return{}}}function sc(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function $o(i,e){if(typeof i=="string")return sc(i,e);if(Array.isArray(i))return i.map(t=>$o(t,e));if(i&&typeof i=="object"){const t={};for(const[r,o]of Object.entries(i))t[r]=$o(o,e);return t}return i}class ac 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")||"",s=this.getAttribute("template-id")||"",a=this.getAttribute("inner-message")||"",l=e==="user"?document.createTextNode(t).textContent||"":Qt(Jt(t)),c=e==="user"&&o,u=o==="sending"?"○":o==="sent"?"✓":o==="delivered"||o==="read"?"✓✓":"";this.shadow.innerHTML=`
|
|
479
479
|
<style>
|
|
480
480
|
:host { display: flex; flex-direction: column; }
|
|
481
481
|
:host([role="user"]) { align-items: flex-end; }
|
|
@@ -543,7 +543,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
543
543
|
${n?`<aikaara-template-renderer
|
|
544
544
|
content-type="${n}"
|
|
545
545
|
template-id="${s}"
|
|
546
|
-
inner-message="${
|
|
546
|
+
inner-message="${lc(a)}"
|
|
547
547
|
></aikaara-template-renderer>`:""}
|
|
548
548
|
${this.renderAttachments()}
|
|
549
549
|
</div>
|
|
@@ -552,9 +552,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
552
552
|
${r}${c?`<span class="status">${u}</span>`:""}
|
|
553
553
|
</div>
|
|
554
554
|
`:""}
|
|
555
|
-
`;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,a),d&&d.addEventListener("template-action",
|
|
555
|
+
`;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,a),d&&d.addEventListener("template-action",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${lc(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
|
|
556
556
|
📎 ${yp(t.fileName)}
|
|
557
|
-
</a>`).join("")}</div>`:""}}function
|
|
557
|
+
</a>`).join("")}</div>`:""}}function lc(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function yp(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class cc 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",s=this.getAttribute("send-shape")==="square",a=t?`
|
|
558
558
|
<button class="attach-btn" aria-label="Attach file" type="button">
|
|
559
559
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
560
560
|
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
|
|
@@ -632,7 +632,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
632
632
|
${n?a:""}
|
|
633
633
|
${l}
|
|
634
634
|
</div>
|
|
635
|
-
`,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.attachBtn=this.shadow.querySelector(".attach-btn"),this.fileInput=this.shadow.querySelector('input[type="file"]'),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.refreshSendDisabled()}),this.textarea.addEventListener("keydown",u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend()),this.attachBtn?.addEventListener("click",()=>{this._disabled||this._uploading||this.fileInput?.click()}),this.fileInput?.addEventListener("change",()=>{const u=this.fileInput?.files;if(u?.length){for(const d of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:d},bubbles:!0,composed:!0}));this.fileInput&&(this.fileInput.value="")}})}set disabled(e){this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.attachBtn&&(this.attachBtn.disabled=e||this._uploading),this.refreshSendDisabled()}get disabled(){return this._disabled}set uploading(e){this._uploading=e,this.attachBtn&&(this.attachBtn.dataset.uploading=String(e),this.attachBtn.disabled=this._disabled||e)}get uploading(){return this._uploading}focus(){this.textarea?.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.refreshSendDisabled())}refreshSendDisabled(){this.sendBtn&&(this.sendBtn.disabled=this._disabled||this._uploading||!this.textarea.value.trim())}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class
|
|
635
|
+
`,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.attachBtn=this.shadow.querySelector(".attach-btn"),this.fileInput=this.shadow.querySelector('input[type="file"]'),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.refreshSendDisabled()}),this.textarea.addEventListener("keydown",u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend()),this.attachBtn?.addEventListener("click",()=>{this._disabled||this._uploading||this.fileInput?.click()}),this.fileInput?.addEventListener("change",()=>{const u=this.fileInput?.files;if(u?.length){for(const d of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:d},bubbles:!0,composed:!0}));this.fileInput&&(this.fileInput.value="")}})}set disabled(e){this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.attachBtn&&(this.attachBtn.disabled=e||this._uploading),this.refreshSendDisabled()}get disabled(){return this._disabled}set uploading(e){this._uploading=e,this.attachBtn&&(this.attachBtn.dataset.uploading=String(e),this.attachBtn.disabled=this._disabled||e)}get uploading(){return this._uploading}focus(){this.textarea?.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.refreshSendDisabled())}refreshSendDisabled(){this.sendBtn&&(this.sendBtn.disabled=this._disabled||this._uploading||!this.textarea.value.trim())}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class uc extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
|
|
636
636
|
<style>
|
|
637
637
|
:host { display: none; }
|
|
638
638
|
:host([visible]) { display: block; }
|
|
@@ -666,7 +666,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
666
666
|
<span class="dot"></span>
|
|
667
667
|
<span class="dot"></span>
|
|
668
668
|
</div>
|
|
669
|
-
`}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class
|
|
669
|
+
`}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class dc extends HTMLElement{shadow;bubble;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
|
|
670
670
|
<style>
|
|
671
671
|
:host {
|
|
672
672
|
display: flex;
|
|
@@ -715,7 +715,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
715
715
|
}
|
|
716
716
|
</style>
|
|
717
717
|
<div class="bubble cursor"></div>
|
|
718
|
-
`,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=Qt(Jt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class
|
|
718
|
+
`,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=Qt(Jt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class hc extends HTMLElement{shadow;container;dismissTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
|
|
719
719
|
<style>
|
|
720
720
|
.banner {
|
|
721
721
|
display: none;
|
|
@@ -743,7 +743,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
743
743
|
<span class="message"></span>
|
|
744
744
|
<button class="dismiss">Dismiss</button>
|
|
745
745
|
</div>
|
|
746
|
-
`,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const Do=new Map;function
|
|
746
|
+
`,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const Do=new Map;function pc(i){const e=Do.get(i);if(e)return e;const t=new Promise((r,o)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(i)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>o(new Error(`Failed to load ${i}`)),{once:!0}));return}const s=document.createElement("script");s.src=i,s.async=!0,s.crossOrigin="anonymous",s.dataset.aikaaraSrc=i,s.addEventListener("load",()=>{s.dataset.aikaaraReady="1",r()},{once:!0}),s.addEventListener("error",()=>{Do.delete(i),o(new Error(`Failed to load ${i}`))},{once:!0}),document.head.appendChild(s)});return Do.set(i,t),t}function vp(i,e=5e3){return new Promise((t,r)=>{const o=setTimeout(()=>r(new Error(`Custom element <${i}> not registered within ${e}ms`)),e);customElements.whenDefined(i).then(()=>{clearTimeout(o),t()})})}const wp={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>Hf).then(({registerAikaaraPaymentLink:i})=>i())},kp={"service-picker":"aikaara-service-picker","service-details":"aikaara-service-details","price-breakdown":"aikaara-price-breakdown","slot-picker":"aikaara-slot-picker","call-upload":"aikaara-call-upload","call-confirmation":"aikaara-call-confirmation"};function _p(i){const e=`template:${i}`,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?.[i]}class xp 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;if(t?.text&&ln(t.text))return;const r=this.getAttribute("message-id");if(r&&t?.attributes?.action){const o=Ap(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,s=n.getName?.();s&&r[s]?.length&&n.setPreSelected?.(r[s])})}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?_p(t):void 0,o=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=wp[o];if(n&&!customElements.get(o)?n().then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] native template ${o} failed to load`,s)):r?.scriptUrl&&!customElements.get(o)&&
|
|
760
|
+
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?_p(t):void 0,o=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=wp[o];if(n&&!customElements.get(o)?n().then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] native template ${o} failed to load`,s)):r?.scriptUrl&&!customElements.get(o)&&pc(r.scriptUrl).then(()=>vp(o)).then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,s)),customElements.get(o)){const s=document.createElement(o);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof s[a]=="function")try{s[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${o}>`,c)}}s.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(s),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&s.setConsumedValues?.(this._consumedValues),s.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const s=this.payloadData;if(s.length>0&&s.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&!("type"in l)&&!("data"in l)&&typeof l.message=="string")){const l=document.createElement("aikaara-option-list");l.setPayload({name:"quick-reply",type:"button",options:s.map(c=>{const u=typeof c.title=="string"?c.title:"",d=c.message;return{label:u||d,value:d}})}),this.appendChild(l);return}for(const l of s)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const s=this.payloadData;typeof s.message=="string"&&(s.okLabel||s.action||s.ok)&&this.mountModal(s)}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=t?kp[t.replace(/_/g,"-").toLowerCase()]:void 0;if(r){this.mountScheduleWidget(r,e);return}const o=e.data;if(o){if(t==="text"){const n=document.createElement("aikaara-text-input");n.setPayload(o),this.appendChild(n);return}if(t==="checkbox"||t==="radio"||t==="button"){const n=document.createElement("aikaara-option-list");n.setPayload({name:o.name??"",title:o.title,options:o.options??[],type:t}),this.appendChild(n);return}if(t==="submit"){const n=document.createElement("aikaara-submit-action"),s=this.getAttribute("message-id")??void 0;n.setPayload({name:o.name??"Submit",action:o.action??{message:o.name??"Submit"},messageId:s}),this.appendChild(n);return}t==="modal"&&this.mountModal({message:o.message??"",okLabel:o.okLabel,cancelLabel:o.cancelLabel,action:o.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>Kf).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:Ep(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountScheduleWidget(e,t){const r=document.createElement(e),n={...t.data??t};if(delete n.type,!n.messageId){const s=this.getAttribute("message-id");s&&(n.messageId=s)}r.setPayload?.(n),this.appendChild(r)}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Sp=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Ep(i){const e={};for(const[t,r]of Object.entries(i))Sp.has(t)||(e[t]=r);return e}function Ap(i){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,o]of Object.entries(i))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}class Ip extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
|
|
761
761
|
<style>
|
|
762
762
|
:host {
|
|
763
763
|
display: flex;
|
|
@@ -782,9 +782,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
782
782
|
color: var(--aikaara-text-secondary, #9ca3af);
|
|
783
783
|
}
|
|
784
784
|
</style>
|
|
785
|
-
<span class="pill">${
|
|
786
|
-
${t?`<span class="sub">${
|
|
787
|
-
`}}function
|
|
785
|
+
<span class="pill">${fc(e)}</span>
|
|
786
|
+
${t?`<span class="sub">${fc(t)}</span>`:""}
|
|
787
|
+
`}}function fc(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Tp 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 s=t[0],a=this.selected.has(s.value),l=this.preSelectedDisabled?"cursor: default; pointer-events: none;":"cursor: pointer;";if(this.shadow.innerHTML=`
|
|
788
788
|
<style>
|
|
789
789
|
:host { display: block; margin: 8px 0; }
|
|
790
790
|
.row {
|
|
@@ -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">${pr(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 pr(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Mp 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??{}},s=Object.keys(n).find(c=>c.toLowerCase()==="x-api-key"),a=this.apiKey??this.getAttribute("api-key")??(s?n[s]:void 0);a&&(s&&s!=="X-Api-Key"&&delete n[s],n["X-Api-Key"]=a);const l=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await
|
|
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 pr(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Mp 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??{}},s=Object.keys(n).find(c=>c.toLowerCase()==="x-api-key"),a=this.apiKey??this.getAttribute("api-key")??(s?n[s]:void 0);a&&(s&&s!=="X-Api-Key"&&delete n[s],n["X-Api-Key"]=a);const l=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await Lc({container:this,slug:e,configBase:this.getAttribute("config-base")??void 0,configHeaders:l,user:{id:t,name:this.getAttribute("user-name")??void 0,departmentId:this.getAttribute("department-id")??void 0,token:o,identity:this.identity,credentialProviders:this.credentialProviders},hooks:{onError:c=>this.dispatchEvent(new CustomEvent("error",{detail:c}))}}),this.dispatchEvent(new CustomEvent("ready",{detail:{requestId:this.mounted.requestId,fullName:this.mounted.fullName}}))}catch(c){this.dispatchEvent(new CustomEvent("error",{detail:c}))}finally{this.mountInflight=null}})(),this.mountInflight}}class Np 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 s=document.createElement(e);n.appendChild(s),requestAnimationFrame(()=>r?.(s))}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 {
|
|
@@ -1161,11 +1161,11 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1161
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 Fo(i){return i.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Dp extends HTMLElement{shadow;root=null;schemas=[];data={};view="picker";activeSectionId=null;keydownHandler=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.renderShell()}disconnectedCallback(){this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null)}open(e){this.root||this.renderShell(),this.root&&(this.schemas=e.schemas,this.data=e.data?{...e.data}:{},e.activeSectionId&&this.schemas.some(t=>t.id===e.activeSectionId)?(this.activeSectionId=e.activeSectionId,this.view="form"):(this.activeSectionId=null,this.view="picker"),this.renderView(),this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("smart-edit-open",{bubbles:!0,composed:!0})))}close(){this.root&&(this.root.classList.remove("open"),this.dispatchEvent(new CustomEvent("smart-edit-close",{bubbles:!0,composed:!0})))}setData(e){this.data={...e},this.view==="form"&&this.mountActiveForm()}openSection(e){this.activeSectionId=e,this.view="form",this.renderView()}backToPicker(){this.activeSectionId=null,this.view="picker",this.renderView()}extractSlice(e){const t=e.dataPath;if(!t)return this.data;const r=t.endsWith("[]"),o=r?t.slice(0,-2):t,n=this.data[o];return r?Array.isArray(n)?n:[]:n??null}handleSectionSubmit(e,t){const r=this.schemas.find(o=>o.id===e);if(r){if(r.dataPath){const n=r.dataPath.endsWith("[]")?r.dataPath.slice(0,-2):r.dataPath;this.data={...this.data,[n]:t}}else t&&typeof t=="object"&&(this.data={...this.data,...t});this.dispatchEvent(new CustomEvent("smart-edit-submit",{detail:{sectionId:e,record:this.data},bubbles:!0,composed:!0})),this.backToPicker()}}handleRecalculate(){this.dispatchEvent(new CustomEvent("smart-edit-recalculate",{detail:{record:this.data},bubbles:!0,composed:!0})),this.close()}renderView(){this.view==="form"?this.renderForm():this.renderPicker()}renderPicker(){const e=this.shadow.querySelector(".modal");if(!e)return;e.classList.remove("view-form"),e.classList.add("view-picker");const t=this.shadow.querySelector(".modal-header");t.innerHTML=`
|
|
1162
1162
|
<span class="header-spacer"></span>
|
|
1163
1163
|
<div class="modal-title">Correct Your ITR Details</div>
|
|
1164
|
-
<button class="icon-btn close-btn" type="button" aria-label="Close">${
|
|
1164
|
+
<button class="icon-btn close-btn" type="button" aria-label="Close">${mc}</button>
|
|
1165
1165
|
`;const r=this.shadow.querySelector(".modal-body"),o=this.schemas.map(s=>`
|
|
1166
1166
|
<button class="chip" type="button" data-section-id="${Bp(s.id)}">
|
|
1167
1167
|
<span class="chip-icon">${s.icon??"📄"}</span>
|
|
1168
|
-
<span class="chip-label">${
|
|
1168
|
+
<span class="chip-label">${gc(s.title)}</span>
|
|
1169
1169
|
</button>`).join("");r.innerHTML=`
|
|
1170
1170
|
<div class="picker">
|
|
1171
1171
|
<div class="intro-card">
|
|
@@ -1181,8 +1181,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1181
1181
|
<button class="primary-btn" type="button" data-action="recalculate">Save & Recalculate</button>
|
|
1182
1182
|
`,this.bindCommon(),r.querySelectorAll(".chip").forEach(s=>{s.addEventListener("click",()=>{const a=s.dataset.sectionId;a&&this.openSection(a)})}),n.querySelector('[data-action="recalculate"]')?.addEventListener("click",()=>this.handleRecalculate())}renderForm(){const e=this.shadow.querySelector(".modal");if(!e)return;e.classList.remove("view-picker"),e.classList.add("view-form");const t=this.schemas.find(n=>n.id===this.activeSectionId),r=this.shadow.querySelector(".modal-header");r.innerHTML=`
|
|
1183
1183
|
<button class="icon-btn back-btn" type="button" aria-label="Back">${Up}</button>
|
|
1184
|
-
<div class="modal-title">${
|
|
1185
|
-
<button class="icon-btn close-btn" type="button" aria-label="Close">${
|
|
1184
|
+
<div class="modal-title">${gc(t?.title??"Edit")}</div>
|
|
1185
|
+
<button class="icon-btn close-btn" type="button" aria-label="Close">${mc}</button>
|
|
1186
1186
|
`;const o=this.shadow.querySelector(".modal-footer");o.style.display="none",o.innerHTML="",this.bindCommon(),r.querySelector(".back-btn")?.addEventListener("click",()=>this.backToPicker()),this.mountActiveForm()}mountActiveForm(){const e=this.shadow.querySelector(".modal-body");if(!e)return;e.innerHTML="";const t=this.schemas.find(o=>o.id===this.activeSectionId);if(!t){e.innerHTML='<div class="empty">Section not found.</div>';return}const r=document.createElement("aikaara-schema-form");r.addEventListener("aikaara-form-submit",(o=>{const n=o.detail;this.handleSectionSubmit(n.sectionId,n.value)})),e.appendChild(r),requestAnimationFrame(()=>{r.setSchema(t),r.setValue(this.extractSlice(t))})}bindCommon(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>this.close())}renderShell(){this.shadow.innerHTML=`
|
|
1187
1187
|
<style>${this.css()}</style>
|
|
1188
1188
|
<div class="backdrop" part="backdrop">
|
|
@@ -1321,7 +1321,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1321
1321
|
border-radius: 16px 16px 0 0;
|
|
1322
1322
|
}
|
|
1323
1323
|
}
|
|
1324
|
-
`}}const
|
|
1324
|
+
`}}const mc='<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>',Up='<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 Bp(i){return i.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function gc(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}class Fp extends HTMLElement{shadow;schema=null;value={};errors=new Map;collapsed=new Set;collapseSeeded=new Set;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setSchema(e){this.collapsed.clear(),this.collapseSeeded.clear(),this.schema=e,this.isRepeatable()&&!Array.isArray(this.value)?this.value=[]:!this.isRepeatable()&&Array.isArray(this.value)&&(this.value={}),this.render()}setValue(e){this.isRepeatable()?(this.value=Array.isArray(e)?[...e]:[],this.value.length===0&&this.value.push({})):this.value=e&&typeof e=="object"?{...e}:{},this.render()}isRepeatable(){return!!this.schema?.repeatable&&this.schema.repeatable.maxCount>0}getEntries(){return this.isRepeatable()?this.value:[this.value]}setEntry(e,t,r){this.setEntryNoRender(e,t,r),this.renderPreservingScroll()}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.renderPreservingScroll())}removeEntry(e){if(!this.isRepeatable())return;const t=this.getEntries();t.length<=1||(t.splice(e,1),this.value=t,this.renderPreservingScroll())}fieldVisible(e,t){const r=s=>{if(!s)return null;const a=t[s.field];return typeof s.gt=="number"?typeof a=="number"&&a>s.gt:"equals"in s?a===s.equals:Array.isArray(s.in)?s.in.includes(a):null};return!(r(e.showWhen)===!1||r(e.hideWhen)===!0)}renderPreservingScroll(){const e=this.shadow.querySelector(".scroll")?.scrollTop??0;this.render();const t=this.shadow.querySelector(".scroll");if(!t)return;const r=()=>{t.scrollHeight,t.scrollTop=e};r(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(r)}findField(e){let t;return this.walkFields(this.schema?.fields||[],r=>{!t&&r.id===e&&(t=r)}),t}normalizeUppercase(){this.getEntries().forEach((e,t)=>{this.walkFields(this.schema?.fields||[],r=>{if(r.type!=="text"||!r.uppercase)return;const o=e[r.id];typeof o=="string"&&o!==o.toUpperCase()&&this.setEntryNoRender(t,r.id,o.toUpperCase())})})}validate(){return this.normalizeUppercase(),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],s=`${r}.${o.id}`;if(o.required&&(n==null||n==="")){this.errors.set(s,"Required");return}if(o.type==="text"&&typeof n=="string"&&(o.pattern&&n&&!new RegExp(o.pattern).test(n)?this.errors.set(s,"Invalid format"):o.maxLength&&n.length>o.maxLength&&this.errors.set(s,`Max ${o.maxLength} characters`)),o.type==="textarea"&&typeof n=="string"&&o.maxLength&&n.length>o.maxLength&&this.errors.set(s,`Max ${o.maxLength} characters`),o.type==="number"&&n!==void 0&&n!==null&&n!==""){const a=typeof n=="number"?n:Number(n),l=o;Number.isNaN(a)?this.errors.set(s,"Must be a number"):l.min!==void 0&&a<l.min?this.errors.set(s,`Minimum ${l.min}`):l.max!==void 0&&a>l.max&&this.errors.set(s,`Maximum ${l.max.toLocaleString("en-IN")}`)}})}),this.errors.size===0}walkFields(e,t){for(const r of e)t(r),r.type==="group"&&this.walkFields(r.fields,t)}handleSubmit(){if(!this.schema)return;if(!this.validate()){this.render(),this.shadow.querySelector(".field.has-error")?.scrollIntoView({behavior:"smooth",block:"center"});return}const e=this.isRepeatable()?this.getEntries():this.value;this.dispatchEvent(new CustomEvent("aikaara-form-submit",{detail:{sectionId:this.schema.id,value:e},bubbles:!0,composed:!0}))}render(){if(!this.schema){this.shadow.innerHTML="<style>:host{display:block;}</style>";return}const e=this.getEntries(),t=e.map((o,n)=>this.renderEntry(o,n)).join(""),r=this.isRepeatable()&&e.length<(this.schema.repeatable?.maxCount||1);this.shadow.innerHTML=`
|
|
1325
1325
|
<style>${this.css()}</style>
|
|
1326
1326
|
<div class="container">
|
|
1327
1327
|
<div class="scroll">
|
|
@@ -1347,11 +1347,11 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1347
1347
|
${Ke(o)}
|
|
1348
1348
|
</span>
|
|
1349
1349
|
${n}
|
|
1350
|
-
</div>`:""}<div class="entry-body">${s}</div></section>`}renderField(e,t,r){if(!e.showWhen&&!e.hideWhen)return this.renderFieldInner(e,t,r);const o=this.fieldVisible(e,t);return`<div class="cond" data-cond-key="${at(`${r}.${e.id}`)}" ${o?"":"hidden"}>${this.renderFieldInner(e,t,r)}</div>`}syncConditionalVisibility(){this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],o=>{if(!o.showWhen&&!o.hideWhen)return;const n=this.shadow.querySelector(`.cond[data-cond-key="${CSS.escape(`${r}.${o.id}`)}"]`);n&&(n.hidden=!this.fieldVisible(o,t))})})}renderFieldInner(e,t,r){if(e.type==="group"){const d=e,
|
|
1350
|
+
</div>`:""}<div class="entry-body">${s}</div></section>`}renderField(e,t,r){if(!e.showWhen&&!e.hideWhen)return this.renderFieldInner(e,t,r);const o=this.fieldVisible(e,t);return`<div class="cond" data-cond-key="${at(`${r}.${e.id}`)}" ${o?"":"hidden"}>${this.renderFieldInner(e,t,r)}</div>`}syncConditionalVisibility(){this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],o=>{if(!o.showWhen&&!o.hideWhen)return;const n=this.shadow.querySelector(`.cond[data-cond-key="${CSS.escape(`${r}.${o.id}`)}"]`);n&&(n.hidden=!this.fieldVisible(o,t))})})}renderFieldInner(e,t,r){if(e.type==="group"){const d=e,p=d.fields.map(b=>this.renderField(b,t,r)).join("");if(!d.collapsible)return`
|
|
1351
1351
|
<fieldset class="group">
|
|
1352
1352
|
${d.title?`<legend class="group-title">${Ke(d.title)}</legend>`:""}
|
|
1353
1353
|
${d.hint?`<div class="group-hint">${Ke(d.hint)}</div>`:""}
|
|
1354
|
-
<div class="group-body">${
|
|
1354
|
+
<div class="group-body">${p}</div>
|
|
1355
1355
|
</fieldset>`;const g=`${r}.${d.id}`;d.defaultCollapsed&&!this.collapseSeeded.has(g)&&(this.collapseSeeded.add(g),this.collapsed.add(g));const h=this.collapsed.has(g);return`
|
|
1356
1356
|
<fieldset class="group group--collapsible ${h?"is-collapsed":""}">
|
|
1357
1357
|
<button type="button" class="group-toggle" data-action="toggle-group" data-group-key="${at(g)}" aria-expanded="${!h}">
|
|
@@ -1359,7 +1359,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1359
1359
|
<span class="group-chevron" aria-hidden="true"></span>
|
|
1360
1360
|
</button>
|
|
1361
1361
|
${d.hint&&!h?`<div class="group-hint">${Ke(d.hint)}</div>`:""}
|
|
1362
|
-
<div class="group-body" ${h?"hidden":""}>${
|
|
1362
|
+
<div class="group-body" ${h?"hidden":""}>${p}</div>
|
|
1363
1363
|
</fieldset>`}const o=`${r}.${e.id}`,n=this.errors.get(o),s=n?"has-error":"",a=e.required?'<span class="req">*</span>':"",l=e.label?`<label class="field-label" for="${this.fieldHtmlId(e,r)}">${Ke(e.label)} ${a}</label>`:"",c=this.renderInput(e,t,r),u=n?`<div class="field-error">${Ke(n)}</div>`:"";return`
|
|
1364
1364
|
<div class="field ${s}" data-field-id="${e.id}" data-entry-index="${r}">
|
|
1365
1365
|
${l}
|
|
@@ -1604,7 +1604,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1604
1604
|
}
|
|
1605
1605
|
.save-btn:hover { filter: brightness(1.07); }
|
|
1606
1606
|
.save-btn:active { filter: brightness(0.95); }
|
|
1607
|
-
`}}function at(i){return i.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ke(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Pe(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Xt(i){return Pe(i)}function nt(i){return`₹${Math.round(Number.isFinite(i)?i:0).toLocaleString("en-IN")}`}function cn(i){const e=Number(i.basePrice)||0,t=i.gstRate??.18,r=Math.round(e*t),o=Number(i.discount)||0;return{base:e,gst:r,discount:o,total:e+r-o}}function qo(i){const[e,t,r]=i.split("-").map(Number);return new Date(e||1970,(t||1)-1,r||1)}function
|
|
1607
|
+
`}}function at(i){return i.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ke(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Pe(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Xt(i){return Pe(i)}function nt(i){return`₹${Math.round(Number.isFinite(i)?i:0).toLocaleString("en-IN")}`}function cn(i){const e=Number(i.basePrice)||0,t=i.gstRate??.18,r=Math.round(e*t),o=Number(i.discount)||0;return{base:e,gst:r,discount:o,total:e+r-o}}function qo(i){const[e,t,r]=i.split("-").map(Number);return new Date(e||1970,(t||1)-1,r||1)}function bc(i){const e=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),r=String(i.getDate()).padStart(2,"0");return`${e}-${t}-${r}`}function qp(i,e){const t=new Date(i);return t.setDate(t.getDate()+e),t}function Ho(i){return qo(i).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"})}function Hp(i){const e=qo(i);return{weekday:e.toLocaleDateString("en-GB",{weekday:"short"}),day:String(e.getDate()),month:e.toLocaleDateString("en-GB",{month:"short"})}}function fr(i){const[e=0,t=0]=i.split(":").map(Number);return`${yc(e*60+t)} – ${yc(e*60+t+30)}`}function yc(i){const e=(i%1440+1440)%1440,t=Math.floor(e/60),r=e%60,o=(t+11)%12+1,n=t<12?"AM":"PM";return`${o}:${String(r).padStart(2,"0")} ${n}`}const Wp="serviceId";class zp extends HTMLElement{shadow;data=null;selectedId=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e??{services:[]},this.dataset.consumed!=="true"&&(this.selectedId=null),this.render()}getName(){return this.data?.postbackKey??Wp}setConsumedValues(e){const t=e?.[this.getName()],r=Array.isArray(t)?t[0]:t;typeof r=="string"&&r&&(this.selectedId=r),this.render()}locked(){return this.dataset.consumed==="true"}select(e){this.locked()||!this.data||(this.selectedId=e.id,this.render(),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:this.data.postbackMessage??e.name,attributes:{action:{[this.getName()]:e.id,serviceName:e.name,basePrice:e.basePrice,...e.discount?{discount:e.discount}:{},...this.data.messageId?{message_id:this.data.messageId}:{},...this.data.action??{}}}},bubbles:!0,composed:!0})))}render(){const e=this.data?.services??[],t=this.data?.showFrom??!0,r=e.map(o=>`
|
|
1608
1608
|
<button class="service" type="button" role="radio" aria-checked="${o.id===this.selectedId}"
|
|
1609
1609
|
data-id="${Xt(o.id)}" ${this.locked()?"disabled":""}>
|
|
1610
1610
|
<span class="info">
|
|
@@ -1648,7 +1648,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1648
1648
|
.name { font-weight: 600; font-size: 14px; }
|
|
1649
1649
|
.tagline { font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1650
1650
|
.from { flex-shrink: 0; font-size: 13px; font-weight: 600; color: var(--aikaara-primary, #6366f1); white-space: nowrap; }
|
|
1651
|
-
`,Kp="serviceDetails";class Gp extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e,this.render()}getName(){return this.data?.postbackKey??Kp}locked(){return this.dataset.consumed==="true"}handleContinue(){if(this.locked()||!this.data)return;const e=this.data.continueLabel??"Continue",t={[this.getName()]:!0,serviceName:this.data.name};typeof this.data.basePrice=="number"&&(t.total=cn({basePrice:this.data.basePrice,discount:this.data.discount,gstRate:this.data.gstRate}).total),this.data.messageId&&(t.message_id=this.data.messageId),Object.assign(t,this.data.action??{}),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:this.data.postbackMessage??e,attributes:{action:t}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const{name:e,tagline:t,badge:r,inclusions:o=[],limitations:n=[],extraInclusions:s=[],extraLimitations:a=[]}=this.data,c=(this.data.showPricing??!0)&&typeof this.data.basePrice=="number"?cn({basePrice:this.data.basePrice??0,discount:this.data.discount,gstRate:this.data.gstRate}):null,u=[...o,...s],d=[...n,...a],
|
|
1651
|
+
`,Kp="serviceDetails";class Gp extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e,this.render()}getName(){return this.data?.postbackKey??Kp}locked(){return this.dataset.consumed==="true"}handleContinue(){if(this.locked()||!this.data)return;const e=this.data.continueLabel??"Continue",t={[this.getName()]:!0,serviceName:this.data.name};typeof this.data.basePrice=="number"&&(t.total=cn({basePrice:this.data.basePrice,discount:this.data.discount,gstRate:this.data.gstRate}).total),this.data.messageId&&(t.message_id=this.data.messageId),Object.assign(t,this.data.action??{}),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:this.data.postbackMessage??e,attributes:{action:t}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const{name:e,tagline:t,badge:r,inclusions:o=[],limitations:n=[],extraInclusions:s=[],extraLimitations:a=[]}=this.data,c=(this.data.showPricing??!0)&&typeof this.data.basePrice=="number"?cn({basePrice:this.data.basePrice??0,discount:this.data.discount,gstRate:this.data.gstRate}):null,u=[...o,...s],d=[...n,...a],p=u.map(y=>`<li class="row"><span class="mark ok">✓</span><span>${Pe(y)}</span></li>`).join(""),g=d.map(y=>`<li class="row muted"><span class="mark no">✕</span><span>${Pe(y)}</span></li>`).join(""),h=c?`
|
|
1652
1652
|
<div class="section">
|
|
1653
1653
|
<h3>Pricing</h3>
|
|
1654
1654
|
<div class="price">
|
|
@@ -1665,7 +1665,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1665
1665
|
<h2 class="name">${Pe(e)}</h2>
|
|
1666
1666
|
${t?`<p class="tagline">${Pe(t)}</p>`:""}
|
|
1667
1667
|
</div>
|
|
1668
|
-
${
|
|
1668
|
+
${p?`<div class="section"><h3>What's Included</h3><ul>${p}</ul></div>`:""}
|
|
1669
1669
|
${g?`<div class="section"><h3>Not Included</h3><ul>${g}</ul></div>`:""}
|
|
1670
1670
|
${h}
|
|
1671
1671
|
${b}
|
|
@@ -1744,8 +1744,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1744
1744
|
font-family: inherit; cursor: pointer;
|
|
1745
1745
|
}
|
|
1746
1746
|
.cta:hover { filter: brightness(0.96); }
|
|
1747
|
-
`,Zp=["09:00","10:00","11:00","12:00","14:00","15:00","16:00","17:00"],ef=7,tf="callSlot";class rf extends HTMLElement{shadow;data=null;selectedDate=null;selectedSlot=null;availabilityOverride=null;loading=!1;errorMessage="";submitted=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e??{},this.availabilityOverride=null,this.loading=!1,this.errorMessage="",this.dataset.consumed!=="true"&&(this.submitted=!1,this.selectedDate=null,this.selectedSlot=null),this.render()}setAvailability(e){this.availabilityOverride=Array.isArray(e)?e:[],this.selectedSlot=null,this.render()}setSlots(e){this.setAvailability(e)}setLoading(e){this.loading=!!e,this.render()}setError(e){this.errorMessage=e??"",this.render()}getName(){return this.data?.postbackKey??tf}setConsumedValues(e){const t=e?.[this.getName()],r=Array.isArray(t)?t[0]:t;if(typeof r=="string"&&r.trim()){const[o,n]=r.trim().split(/[ T]/);o&&(this.selectedDate=o),n&&(this.selectedSlot=n),this.submitted=!0}this.render()}isLocked(){return this.submitted||this.dataset.consumed==="true"}normalizeDays(){const e=this.data;if(!e)return[];const t=new Set(e.disabledDates??[]),r=this.availabilityOverride??e.days??e.availability??e.slots;if(r&&r.length)return r.filter(l=>l&&typeof l.date=="string").map(l=>({iso:l.date,slots:(l.slots??[]).map(nf)})).filter(l=>!t.has(l.iso));const o=e.startDate?qo(e.startDate):new Date,n=Math.max(1,e.daysAhead??ef),s=e.times&&e.times.length?e.times:Zp,a=[];for(let l=0;l<n;l++){const c=
|
|
1748
|
-
<style>${
|
|
1747
|
+
`,Zp=["09:00","10:00","11:00","12:00","14:00","15:00","16:00","17:00"],ef=7,tf="callSlot";class rf extends HTMLElement{shadow;data=null;selectedDate=null;selectedSlot=null;availabilityOverride=null;loading=!1;errorMessage="";submitted=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e??{},this.availabilityOverride=null,this.loading=!1,this.errorMessage="",this.dataset.consumed!=="true"&&(this.submitted=!1,this.selectedDate=null,this.selectedSlot=null),this.render()}setAvailability(e){this.availabilityOverride=Array.isArray(e)?e:[],this.selectedSlot=null,this.render()}setSlots(e){this.setAvailability(e)}setLoading(e){this.loading=!!e,this.render()}setError(e){this.errorMessage=e??"",this.render()}getName(){return this.data?.postbackKey??tf}setConsumedValues(e){const t=e?.[this.getName()],r=Array.isArray(t)?t[0]:t;if(typeof r=="string"&&r.trim()){const[o,n]=r.trim().split(/[ T]/);o&&(this.selectedDate=o),n&&(this.selectedSlot=n),this.submitted=!0}this.render()}isLocked(){return this.submitted||this.dataset.consumed==="true"}normalizeDays(){const e=this.data;if(!e)return[];const t=new Set(e.disabledDates??[]),r=this.availabilityOverride??e.days??e.availability??e.slots;if(r&&r.length)return r.filter(l=>l&&typeof l.date=="string").map(l=>({iso:l.date,slots:(l.slots??[]).map(nf)})).filter(l=>!t.has(l.iso));const o=e.startDate?qo(e.startDate):new Date,n=Math.max(1,e.daysAhead??ef),s=e.times&&e.times.length?e.times:Zp,a=[];for(let l=0;l<n;l++){const c=bc(qp(o,l));t.has(c)||a.push({iso:c,slots:s.map(u=>({start:u,available:!0}))})}return a}isSelectable(e,t){if(t.available===!1)return!1;if(e!==bc(new Date))return!0;const[r=0,o=0]=t.start.split(":").map(Number),n=new Date;return r*60+o>n.getHours()*60+n.getMinutes()}selectDate(e){this.isLocked()||(this.selectedDate=e,this.selectedSlot=null,this.render())}selectSlot(e){this.isLocked()||(this.selectedSlot=e,this.render())}handleContinue(){if(this.isLocked()||!this.data||!this.selectedDate||!this.selectedSlot)return;const e=this.data.continueLabel??"Continue",t={[this.getName()]:`${this.selectedDate} ${this.selectedSlot}`,scheduledDate:this.selectedDate,scheduledTime:this.selectedSlot,slot:this.selectedSlot,slotLabel:fr(this.selectedSlot)};this.data.timezone&&(t.timezone=this.data.timezone),this.data.messageId&&(t.message_id=this.data.messageId),Object.assign(t,this.data.action??{}),this.submitted=!0,this.render(),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:this.data.postbackMessage??e,attributes:{action:t}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}if(this.isLocked()&&this.selectedDate&&this.selectedSlot){this.shadow.innerHTML=this.lockedTemplate();return}const e=this.normalizeDays();e.length&&(!this.selectedDate||!e.some(r=>r.iso===this.selectedDate))&&(this.selectedDate=e[0].iso,this.selectedSlot=null);const t=e.find(r=>r.iso===this.selectedDate)??null;this.shadow.innerHTML=`
|
|
1748
|
+
<style>${vc}</style>
|
|
1749
1749
|
<div class="card" part="card">
|
|
1750
1750
|
${this.data.title?`<div class="title">${Pe(this.data.title)}</div>`:""}
|
|
1751
1751
|
${this.data.subtitle?`<div class="subtitle">${Pe(this.data.subtitle)}</div>`:""}
|
|
@@ -1771,13 +1771,13 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1771
1771
|
${n}
|
|
1772
1772
|
${s}
|
|
1773
1773
|
`}lockedTemplate(){return`
|
|
1774
|
-
<style>${
|
|
1774
|
+
<style>${vc}</style>
|
|
1775
1775
|
<div class="card locked" part="card">
|
|
1776
1776
|
<div class="locked-head"><span class="tick" aria-hidden="true">✓</span> Slot selected</div>
|
|
1777
1777
|
<div class="locked-when">${Pe(Ho(this.selectedDate))} · ${Pe(fr(this.selectedSlot))}</div>
|
|
1778
1778
|
${this.data?.timezone?`<div class="locked-tz">${Pe(this.data.timezone)}</div>`:""}
|
|
1779
1779
|
</div>
|
|
1780
|
-
`}attachListeners(){this.shadow.querySelectorAll("button.day").forEach(e=>{e.addEventListener("click",()=>this.selectDate(e.dataset.date||""))}),this.shadow.querySelectorAll("button.slot").forEach(e=>{e.addEventListener("click",()=>this.selectSlot(e.dataset.time||""))}),this.shadow.querySelector("button.cta")?.addEventListener("click",()=>this.handleContinue())}}function nf(i){return typeof i=="string"?{start:i,available:!0}:{start:i.start,available:i.available}}const
|
|
1780
|
+
`}attachListeners(){this.shadow.querySelectorAll("button.day").forEach(e=>{e.addEventListener("click",()=>this.selectDate(e.dataset.date||""))}),this.shadow.querySelectorAll("button.slot").forEach(e=>{e.addEventListener("click",()=>this.selectSlot(e.dataset.time||""))}),this.shadow.querySelector("button.cta")?.addEventListener("click",()=>this.handleContinue())}}function nf(i){return typeof i=="string"?{start:i,available:!0}:{start:i.start,available:i.available}}const vc=`
|
|
1781
1781
|
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1782
1782
|
.card {
|
|
1783
1783
|
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
@@ -1859,7 +1859,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1859
1859
|
${this.error?`<p class="error">${Pe(this.error)}</p>`:""}
|
|
1860
1860
|
${a}
|
|
1861
1861
|
</div>
|
|
1862
|
-
`,this.shadow.querySelector('input[type="file"]')?.addEventListener("change",c=>{this.handleFiles(c.target.files)}),this.shadow.querySelectorAll("button.rm").forEach(c=>{c.addEventListener("click",()=>{const u=Number(c.dataset.i);this.fileNames=this.fileNames.filter((d,
|
|
1862
|
+
`,this.shadow.querySelector('input[type="file"]')?.addEventListener("change",c=>{this.handleFiles(c.target.files)}),this.shadow.querySelectorAll("button.rm").forEach(c=>{c.addEventListener("click",()=>{const u=Number(c.dataset.i);this.fileNames=this.fileNames.filter((d,p)=>p!==u),this.render()})});const l=this.shadow.querySelector("textarea");l&&(l.value=this.query,l.addEventListener("input",()=>{this.query=l.value;const c=this.shadow.querySelector(".counter");c&&(c.textContent=`${this.query.length}/${this.queryConfig().maxLength??1e3}`)})),this.shadow.querySelector("button.cta")?.addEventListener("click",()=>this.handleSubmit())}}const af=`
|
|
1863
1863
|
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1864
1864
|
.card {
|
|
1865
1865
|
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
@@ -1937,7 +1937,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1937
1937
|
.label { color: var(--aikaara-text-secondary, #6b7280); }
|
|
1938
1938
|
.value { font-weight: 600; text-align: right; }
|
|
1939
1939
|
.note { margin: 12px 0 0; text-align: center; font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1940
|
-
`;function Wo(){const i=[["aikaara-chat-widget",Xl],["aikaara-chat-bubble",Zl],["aikaara-chat-header",ec],["aikaara-message-list",nc],["aikaara-message-bubble",sc],["aikaara-chat-input",lc],["aikaara-typing-indicator",cc],["aikaara-streaming-message",uc],["aikaara-error-banner",dc],["aikaara-template-renderer",xp],["aikaara-system-pill",Ip],["aikaara-option-list",Tp],["aikaara-submit-action",Cp],["aikaara-modal-action",Op],["aikaara-text-input",Lp],["aikaara-chat",Mp],["aikaara-link-modal",Np],["aikaara-compare-plans",$p],["aikaara-smart-edit-modal",Dp],["aikaara-schema-form",Fp],["aikaara-service-picker",zp],["aikaara-service-details",Gp],["aikaara-price-breakdown",Qp],["aikaara-slot-picker",rf],["aikaara-call-upload",sf],["aikaara-call-confirmation",lf]];for(const[e,t]of i)customElements.get(e)||customElements.define(e,t)}Wo();function un(i,e,t=""){if(!e)return t;const r=e.split(".");let o=i;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 vc(i){try{const e=i.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 Zt(i){return typeof i=="function"?await i():i}class wc{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=vc(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 Zt(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",s={method:n,headers:o};n==="POST"&&(o["content-type"]="application/json",s.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,s);if(!a.ok){const w=await a.text().catch(()=>"");throw new Error(`Session auth failed: ${a.status} ${w.slice(0,200)}`)}const l=await a.json().catch(()=>({})),c=un(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!d)throw new Error("Session auth response missing token");const f=un(l,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||f||"",h=un(l,this.descriptor.fullNamePath??"data.fullName"),b=un(l,this.descriptor.userPath??"data.userId"),y=vc(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:h,userId:b,expiresAt:y},this.cache}}async function kc(i){const e={};for(const t of i.spec){const r=await uf(t,i.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 uf(i,e){const t=i.key??i.name;switch(i.source){case"cookie":return df(t);case"localStorage":return dn(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return dn(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return dn(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return dn(()=>document.querySelector(`meta[name="${hf(t)}"]`)?.content??void 0);case"callback":{const r=e?.[i.name];if(!r)return;const o=await r();return typeof o=="string"?o:void 0}default:return}}function df(i){if(typeof document>"u")return;const e=encodeURIComponent(i),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===i||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function dn(i){try{return i()}catch{return}}function hf(i){return i.replace(/["\\]/g,"\\$&")}const pf=1800;class _c{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await kc({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const o=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!o)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(o,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const a=(await n.json().catch(()=>({}))).user??{},l=String(a.ext_uid??a.extUid??""),c=String(a.token??a.user_token??a.userToken??"");if(!l)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:a.id,extUid:l,userToken:c,email:typeof a.email=="string"?a.email:void 0,displayName:typeof a.display_name=="string"?a.display_name:typeof a.displayName=="string"?a.displayName:void 0,properties:a.properties&&typeof a.properties=="object"?a.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??pf;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 ff=3e4,mf=2e3,gf=100;async function xc(i){const{descriptor:e}=i,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!i.initToken)throw new Ze("init","No init token supplied to Aikaara.init({token})");return{token:i.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=bf(r);if(!o)throw new Ze("query",`?${r}= not present`);return{token:o,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=yf(r);if(!o)throw new Ze("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=xf(typeof t.origins=="string"?t.origins:""),s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:ff;return{token:await _f({type:r,key:o,origins:n,timeoutMs:s}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ze("cookie","cookie.name not configured");const o=vf(r);if(!o)throw new Ze("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 Ze("storage","storage.key not configured");const s=wf(r,o,n);if(!s)throw new Ze("storage",`${r}Storage["${o}"] not set`);return{token:s,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ze("global","global.path not configured");const o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:mf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:gf,s=await kf(r,o,n);if(!s)throw new Ze("global",`window.${r} not present`);return{token:s,source:"global"}}default:{const r=e.tokenSource;throw new Ze("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class Sc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await xc(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Ze extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function bf(i){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))===i)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function yf(i){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(i)??void 0}catch{return}}function vf(i){if(typeof document>"u")return;const e=encodeURIComponent(i),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===i||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function wf(i,e,t){if(!(typeof window>"u"))try{const o=(i==="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 s=Ec(n,t);return typeof s=="string"?s:void 0}catch{return}}async function kf(i,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const o=Ec(window,i);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 _f(i){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ze("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(o)},o=setTimeout(()=>{r(),t(new Ze("postmsg",`timeout after ${i.timeoutMs}ms`))},i.timeoutMs),n=s=>{if(i.origins.length>0&&!i.origins.includes(s.origin))return;const a=s.data;if(!a||typeof a!="object")return;const l=a;if(i.type&&l.type!==i.type)return;const c=l[i.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function xf(i){return i?i.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Ec(i,e){if(!e)return i;const t=e.split(".").filter(Boolean);let r=i;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function Sf(){const i=typeof crypto<"u"?crypto:null;if(i?.randomUUID)return i.randomUUID();if(i?.getRandomValues){const e=new Uint8Array(16);i.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 Ef="aikaara_chat:requestId";function zo(i,e,t){const r=`${Ef}:${i}:${e}`;return t?`${r}:${t}`:r}function Ac(i,e,t){try{return localStorage.getItem(zo(i,e,t))}catch{return null}}function Af(i,e,t,r){try{localStorage.setItem(zo(i,e,r),t)}catch{}}function If(i,e,t){try{localStorage.removeItem(zo(i,e,t))}catch{}}async function Vo(i,e,t="before-chat"){const r=i.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const o={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(o[u]=d);typeof e.serviceType=="string"&&(o.serviceType=e.serviceType),typeof e.userType=="string"&&(o.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,f)=>f in o?o[f]:""),s=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(s);if(u&&typeof u=="object"){const d={};for(const[f,g]of Object.entries(u))d[f]=s(g);return d}return u},a=await Zt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const d=r[u],f=n(d.url),g=d.method??(d.body?"POST":"GET"),h={accept:"application/json",...d.headers??{}};if((d.authHeader??"session")==="session"){const x=d.authHeaderTemplate??"Bearer {token}";h.authorization=x.replace("{token}",a)}const b={method:g,headers:h};d.body&&(h["content-type"]="application/json",b.body=JSON.stringify(s(d.body)));let y=0,w="",m=0,k=null;for(;;)try{const x=await fetch(f,b);if(x.ok){k=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&Cf(y,w)){const S=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${f} → ${y} (transient). Retry #${m} in ${S}ms.`),await new Promise(E=>setTimeout(E,S));continue}const v=`Preflight #${u} ${g} ${f} → ${y} ${w.slice(0,200)}`;if(d.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(x){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,x),await new Promise(S=>setTimeout(S,v));continue}if(d.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(k&&d.capture&&d.capture.as)try{const x=await k.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(d.capture.path)for(const S of d.capture.path.split("."))if(v&&typeof v=="object"&&S in v)v=v[S];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let S=v;d.capture.stripPrefix&&S.startsWith(d.capture.stripPrefix)&&(S=S.slice(d.capture.stripPrefix.length)),l[d.capture.as]=S,o[d.capture.as]=S,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${d.capture.as} (${S.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function Tf(i){const e=i.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await Vo(e,{sessionToken:i.sessionToken,userId:i.userId,projectId:i.projectId??"",slug:i.slug??"",identity:i.identity,serviceType:i.serviceType,userType:i.userType},"on-method-select")).captured:{}}function Cf(i,e){if(i===503||i===504||i===502)return!0;if(i===401||i===403)return e.trim().length===0;if(i===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Ic(i,e){const t=await fetch(i,{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 Tc(i,e){return i.replace("{projectId}",e).replace("{uuid}",Sf().replace(/-/g,""))}function Cc(i){const e=i._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=>hc(r)))}async function Pc(i){const e={...i.config??(i.configUrl?await Ic(i.configUrl,i.configHeaders):{}),...i.overrides??{}};Cc(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const o=r?.projectId??"",n=i.identity.userId,s=i.conversationScope||void 0,a=i.forceNewConversation?null:Ac(n,o,s),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=i.conversationId??a??Tc(l,o);(i.conversationId||!a||i.forceNewConversation)&&o&&Af(n,o,c,s);const u=await i.tokenProvider(),d=i.tokenProvider,f=i.historyTokenProvider??d,g=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:i.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,...i.identity.departmentId?{departmentId:i.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:i.identity.senderFullname??i.identity.userName,tokenProvider:d}:void 0,h=i.uploadAdapter??(e.uploadEndpoint?Po({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),b=i.historyAdapter??(e.historyApiBase?Wl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:f}):void 0),y={transport:t,baseUrl:"",userToken:i.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:i.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:i.identity.userName,departmentId:i.identity.departmentId,senderFullname:i.identity.senderFullname??i.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:h,historyAdapter:b,onError:i.onError,onMessage:i.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;"),i.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function Pf(i){if(typeof i!="string")return i;const e=document.querySelector(i);if(!e)throw new Error(`mountFromSlug: container "${i}" not found`);return e}async function Oc(i){const e=(i.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(i.slug)}`;let r=null;try{r=await Ic(t,i.configHeaders)}catch(I){if(!i.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${i.slug}" — using fallbackConfig.`,I)}const o={...i.fallbackConfig??{},...r??{},...i.overrides??{}};if(Cc(o),o.templates&&Object.keys(o.templates).length>0){o.components={...o.components??{}};for(const[I,P]of Object.entries(o.templates)){const L=`template:${I}`;o.components[L]||!P?.scriptUrl||!P?.render||(o.components[L]={kind:"iife-element",scriptUrl:P.scriptUrl,tag:P.render,...P.props?{props:P.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:o.templates,components:o.components,razorpay:o.razorpay,title:o.title,cloud:o.cloud??n.__aikaara_descriptor__?.cloud,upload:o.upload??n.__aikaara_descriptor__?.upload,themeSource:o.themeSource??n.__aikaara_descriptor__?.themeSource,api:o.api,auth:o.auth,smartEdit:o.smartEdit??n.__aikaara_descriptor__?.smartEdit},!o.auth)throw new Error(`mountFromSlug: widget_configs/${i.slug} descriptor must include "auth" block`);let s=null,a=i.user.id,l=i.user.name,c="",u=i.user.token,d=null;const f=await Zt(i.user.token).catch(()=>""),g=typeof f=="string"&&f.length>0;if(!g&&o.sso?.tokenSource){d=new Sc({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:i.user.partnerToken});const I=await d.get();u=async()=>(await d.get()).token,i.user.identity&&!i.user.identity.partnerToken&&(i.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(i.slug)}/sso_exchange`;s=await new _c({descriptor:o.sso,providers:i.user.credentialProviders,exchangeUrl:I}).get(),a=s.extUid||a,l=l??s.displayName,c=s.userToken}let h="",b="";if(o.preflight&&o.preflight.length){const I=await Vo(o.preflight,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:i.slug,identity:i.user.identity});if(I.captured.sessionToken){h=I.captured.sessionToken;const P=h;u=()=>P}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(b=I.captured.requestId)}const y=new wc(o.auth,u);if(h){const I=o.tiledesk?.projectId??"",P=I?Ac(a,I):null,L=o.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",$=P??(I?Tc(L,I):"");y.prime(h,{requestId:$,fullName:l})}const w=await y.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,getSessionToken:()=>Zt(i.user.token),identity:i.user.identity,slug:i.slug,configBase:e};const k=d&&o.sso?.autoRefresh?async()=>{try{return await d.refresh(),y.reset(),(await y.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=o.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await y.get()).token:await Zt(i.user.token)}`,S=i.hooks?.upload??(x&&x.mode==="presigned-3step"?Hl({...x,authHeader:v}):x&&x.mode==="direct"?Po({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),E=await Pc({container:Pf(i.container),config:o,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:i.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:S,historyAdapter:i.hooks?.history,conversationId:w.requestId||b||void 0,conversationScope:i.conversationScope,onError:i.hooks?.onError,onMessage:i.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Zt(i.user.token)});return Object.assign(E,{fullName:m,requestId:w.requestId,descriptor:o,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return k?k():null},async runMethodSelectPreflight(I){const P=o.preflight;return!P||!P.length?{}:P.some($=>$.trigger==="on-method-select")?(await Vo(P,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:i.slug,identity:{...i.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}function Of(i){Wo();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=i[r];n!=null&&e.setAttribute(o,String(n))}return e.configure(i),document.body.appendChild(e),e}function Lf(){const i=document.querySelector("aikaara-chat-widget");i&&i.remove()}const Mf="https://checkout.razorpay.com/v1/checkout.js";let mr=null;function gr(){return window}class Lc 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",s=!!this.paidIdx[o];return`<button class="link${s?" paid":""}" data-i="${o}" type="button"${s?" disabled":""}><span class="lbl">${Nf(s?"Paid":n)}</span>`+(s?'<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=Rf(t),o=gr().__aikaara_descriptor__,n=o?.partnerPayment,s=o?.razorpay;if(r&&n?.paymentLinkUrl){this.openPartnerPaymentLink(e,r,t,n);return}if(!r||!s?.keyId){t.openLinkInNewTab?window.open(t.url,"_blank","noopener,noreferrer"):Ff(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}$f(s.preferredBanksUrl,r,s.preferredBanksMethod,s.preferredBanksHeaders).catch(a=>(console.warn("[payment_link] preferred-banks fetch failed; continuing with default UI",a),[])).then(a=>jf().then(()=>this.openRazorpay(e,r,s,a))).catch(a=>{console.error("[payment_link] Razorpay launch failed",a)})}openPartnerPaymentLink(e,t,r,o){Df(t,o).then(n=>{if(!n){er("Failed to generate payment link, please try again later");return}const s=(n.paymentStatus??"").toLowerCase();if(s==="paid"||s==="success"||s==="completed"){this.paidIdx[e]=!0,this.render(),er("Payment already completed");return}const a=n.vendorPaymentLink;if(!a){er("Failed to generate payment link, please try again later");return}const l=navigator.userAgent.toLowerCase();if(l.includes("iphone")||l.includes("ipad")||l.includes("ipod")){window.location.href=a;return}const u=Uf(a);if(!u){window.open(a,"_blank"),er("Allow popups for the best payment experience");return}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:r.name||"link-click",attributes:{action:{type:"partner-payment",url:a,orderId:t,openedIn:"popup"}}},bubbles:!0,composed:!0})),Bf(u,o.checkoutOrigin,{onSuccess:()=>{this.paidIdx[e]=!0,this.render()},onError:d=>{er(d||"Payment failed, please try again")},onClose:()=>{}})}).catch(n=>{console.error("[payment_link] partner payment link fetch failed",n),er("Failed to generate payment link, please try again later")})}openRazorpay(e,t,r,o){const n=gr(),s=n.__aikaara_runtime__?.identity??{},a={key:r.keyId,order_id:t,name:r.name||n.__aikaara_descriptor__?.title||"Payment",prefill:{},handler:()=>{this.paidIdx[e]=!0,this.render()},modal:{ondismiss:()=>{}}};typeof s.mobile=="string"?a.prefill.contact=s.mobile:typeof s.phone=="string"&&(a.prefill.contact=s.phone),typeof s.email=="string"&&(a.prefill.email=s.email),typeof s.name=="string"?a.prefill.name=s.name:typeof s.userName=="string"&&(a.prefill.name=s.userName),Array.isArray(o)&&o.length&&(a.config={display:{blocks:{utib:{name:"Pay Using Preferred Netbanking",instruments:[{method:"netbanking",banks:o}]}},sequence:["block.utib","netbanking","card","upi"],preferences:{show_default_blocks:!0}}});const l=n.Razorpay;if(typeof l!="function")throw new Error("Razorpay Checkout script not available");const c=new l(a);c.on("payment.failed",u=>{console.warn("[payment_link] payment.failed",u?.error)}),c.open()}}function Nf(i){return String(i??"").replace(/[&<>]/g,e=>e==="&"?"&":e==="<"?"<":">")}function Rf(i){if(typeof i.orderId=="string"&&i.orderId)return i.orderId;try{const e=new URL(i.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 jf(){return typeof gr().Razorpay=="function"?Promise.resolve():mr||(mr=new Promise((i,e)=>{const t=document.querySelector('script[data-aikaara-razorpay="1"]');if(t){t.addEventListener("load",()=>i()),t.addEventListener("error",()=>e(new Error("checkout.js failed to load")));return}const r=document.createElement("script");r.src=Mf,r.async=!0,r.dataset.aikaaraRazorpay="1",r.onload=()=>i(),r.onerror=()=>{mr=null,e(new Error("checkout.js failed to load"))},document.head.appendChild(r)}),mr)}function $f(i,e,t,r){if(!i)return Promise.resolve([]);const o=String(t||"GET").toUpperCase()==="POST"?"POST":"GET",n=i.includes("{orderId}")?i.replace("{orderId}",encodeURIComponent(e)):i+(i.includes("?")?"&":"?")+"orderId="+encodeURIComponent(e),s=gr().__aikaara_runtime__??{};return(typeof s.getSessionToken=="function"?s.getSessionToken():typeof s.getChatJwt=="function"?s.getChatJwt():Promise.resolve(null)).then(l=>{const c={Accept:"application/json",...r??{}};l&&(c.Authorization=`Bearer ${l}`);const u={method:o,headers:c,credentials:"omit"};return o==="POST"&&(c["Content-Type"]="application/json",u.body=JSON.stringify({orderId:e})),fetch(n,u)}).then(l=>{if(!l.ok)throw new Error(`preferred-banks ${l.status}`);return l.json()}).then(l=>{const c=l,u=c?.data&&typeof c.data=="object"&&!Array.isArray(c.data)?c.data:null;return(Array.isArray(l)?l:Array.isArray(c?.banks)?c.banks:Array.isArray(c?.data)?c.data:Array.isArray(u?.preferredPaymentBank)?u.preferredPaymentBank:Array.isArray(u?.banks)?u.banks:[]).map(f=>{if(typeof f=="string")return f;if(f&&typeof f=="object"){const g=f;return g.code||g.bankCode||g.bank_code||null}return null}).filter(f=>!!f)})}async function Df(i,e){const t=String(e.method||"GET").toUpperCase()==="POST"?"POST":"GET",r=e.paymentLinkUrl,o=r.includes("{orderId}")?r.replace("{orderId}",encodeURIComponent(i)):r+(r.includes("?")?"&":"?")+"orderId="+encodeURIComponent(i),n=gr().__aikaara_runtime__??{},s=typeof n.getSessionToken=="function"?await n.getSessionToken():typeof n.getChatJwt=="function"?await n.getChatJwt():null,a={Accept:"application/json",...e.headers??{}};s&&(a.Authorization=`Bearer ${s}`);const l={method:t,headers:a,credentials:"omit"};t==="POST"&&(a["Content-Type"]="application/json",l.body=JSON.stringify({orderId:i}));const c=await fetch(o,l);if(!c.ok)throw new Error(`partner-payment-link ${c.status}`);const d=(await c.json())?.data;return!d||typeof d.vendorPaymentLink!="string"?null:{vendorPaymentLink:d.vendorPaymentLink,paymentStatus:d.paymentStatus??""}}function Uf(i){const r=window.screenX+Math.round((window.outerWidth-520)/2),o=window.screenY+Math.round((window.outerHeight-680)/2);return window.open(i,"taxbuddy_payment",`width=520,height=680,left=${r},top=${o},scrollbars=yes,resizable=yes`)}function Bf(i,e,t){let r=!1;function o(){clearInterval(a),window.removeEventListener("message",s)}function n(l){r||(r=!0,o(),l())}function s(l){if(e&&l.origin!==e)return;const c=l.data;if(!(!c||typeof c!="object")){if(c.type==="payment-completed"&&c.success===!0){n(()=>t.onSuccess());return}c.type==="payment-error"&&c.success===!1&&n(()=>t.onError(c.error??"Payment failed"))}}const a=setInterval(()=>{i.closed&&n(()=>t.onClose())},500);window.addEventListener("message",s)}function er(i){try{const e=document.querySelector("aikaara-error-banner");if(e&&typeof e.show=="function"){e.show(i);return}}catch{}console.warn("[payment_link]",i)}function Ff(i,e){if(!i)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(i,e):window.open(i,"_blank","noopener,noreferrer")}function qf(){typeof customElements>"u"||customElements.get("aikaara-template-payment-link")||customElements.define("aikaara-template-payment-link",Lc)}const Hf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraPaymentLink:Lc,registerAikaaraPaymentLink:qf},Symbol.toStringTag,{value:"Module"}));class Mc 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=`
|
|
1940
|
+
`;function Wo(){const i=[["aikaara-chat-widget",Zl],["aikaara-chat-bubble",ec],["aikaara-chat-header",tc],["aikaara-message-list",ic],["aikaara-message-bubble",ac],["aikaara-chat-input",cc],["aikaara-typing-indicator",uc],["aikaara-streaming-message",dc],["aikaara-error-banner",hc],["aikaara-template-renderer",xp],["aikaara-system-pill",Ip],["aikaara-option-list",Tp],["aikaara-submit-action",Cp],["aikaara-modal-action",Op],["aikaara-text-input",Lp],["aikaara-chat",Mp],["aikaara-link-modal",Np],["aikaara-compare-plans",$p],["aikaara-smart-edit-modal",Dp],["aikaara-schema-form",Fp],["aikaara-service-picker",zp],["aikaara-service-details",Gp],["aikaara-price-breakdown",Qp],["aikaara-slot-picker",rf],["aikaara-call-upload",sf],["aikaara-call-confirmation",lf]];for(const[e,t]of i)customElements.get(e)||customElements.define(e,t)}Wo();function un(i,e,t=""){if(!e)return t;const r=e.split(".");let o=i;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 wc(i){try{const e=i.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 Zt(i){return typeof i=="function"?await i():i}class kc{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=wc(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 Zt(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",s={method:n,headers:o};n==="POST"&&(o["content-type"]="application/json",s.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,s);if(!a.ok){const w=await a.text().catch(()=>"");throw new Error(`Session auth failed: ${a.status} ${w.slice(0,200)}`)}const l=await a.json().catch(()=>({})),c=un(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!d)throw new Error("Session auth response missing token");const p=un(l,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||p||"",h=un(l,this.descriptor.fullNamePath??"data.fullName"),b=un(l,this.descriptor.userPath??"data.userId"),y=wc(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:h,userId:b,expiresAt:y},this.cache}}async function _c(i){const e={};for(const t of i.spec){const r=await uf(t,i.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 uf(i,e){const t=i.key??i.name;switch(i.source){case"cookie":return df(t);case"localStorage":return dn(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return dn(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return dn(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return dn(()=>document.querySelector(`meta[name="${hf(t)}"]`)?.content??void 0);case"callback":{const r=e?.[i.name];if(!r)return;const o=await r();return typeof o=="string"?o:void 0}default:return}}function df(i){if(typeof document>"u")return;const e=encodeURIComponent(i),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===i||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function dn(i){try{return i()}catch{return}}function hf(i){return i.replace(/["\\]/g,"\\$&")}const pf=1800;class xc{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await _c({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const o=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!o)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(o,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const a=(await n.json().catch(()=>({}))).user??{},l=String(a.ext_uid??a.extUid??""),c=String(a.token??a.user_token??a.userToken??"");if(!l)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:a.id,extUid:l,userToken:c,email:typeof a.email=="string"?a.email:void 0,displayName:typeof a.display_name=="string"?a.display_name:typeof a.displayName=="string"?a.displayName:void 0,properties:a.properties&&typeof a.properties=="object"?a.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??pf;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 ff=3e4,mf=2e3,gf=100;async function Sc(i){const{descriptor:e}=i,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!i.initToken)throw new Ze("init","No init token supplied to Aikaara.init({token})");return{token:i.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=bf(r);if(!o)throw new Ze("query",`?${r}= not present`);return{token:o,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=yf(r);if(!o)throw new Ze("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=xf(typeof t.origins=="string"?t.origins:""),s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:ff;return{token:await _f({type:r,key:o,origins:n,timeoutMs:s}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ze("cookie","cookie.name not configured");const o=vf(r);if(!o)throw new Ze("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 Ze("storage","storage.key not configured");const s=wf(r,o,n);if(!s)throw new Ze("storage",`${r}Storage["${o}"] not set`);return{token:s,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ze("global","global.path not configured");const o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:mf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:gf,s=await kf(r,o,n);if(!s)throw new Ze("global",`window.${r} not present`);return{token:s,source:"global"}}default:{const r=e.tokenSource;throw new Ze("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class Ec{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Sc(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 Ze extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function bf(i){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))===i)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function yf(i){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(i)??void 0}catch{return}}function vf(i){if(typeof document>"u")return;const e=encodeURIComponent(i),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===i||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function wf(i,e,t){if(!(typeof window>"u"))try{const o=(i==="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 s=Ac(n,t);return typeof s=="string"?s:void 0}catch{return}}async function kf(i,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const o=Ac(window,i);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 _f(i){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ze("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(o)},o=setTimeout(()=>{r(),t(new Ze("postmsg",`timeout after ${i.timeoutMs}ms`))},i.timeoutMs),n=s=>{if(i.origins.length>0&&!i.origins.includes(s.origin))return;const a=s.data;if(!a||typeof a!="object")return;const l=a;if(i.type&&l.type!==i.type)return;const c=l[i.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function xf(i){return i?i.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Ac(i,e){if(!e)return i;const t=e.split(".").filter(Boolean);let r=i;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function Sf(){const i=typeof crypto<"u"?crypto:null;if(i?.randomUUID)return i.randomUUID();if(i?.getRandomValues){const e=new Uint8Array(16);i.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 Ef="aikaara_chat:requestId";function zo(i,e,t){const r=`${Ef}:${i}:${e}`;return t?`${r}:${t}`:r}function Ic(i,e,t){try{return localStorage.getItem(zo(i,e,t))}catch{return null}}function Af(i,e,t,r){try{localStorage.setItem(zo(i,e,r),t)}catch{}}function If(i,e,t){try{localStorage.removeItem(zo(i,e,t))}catch{}}async function Vo(i,e,t="before-chat"){const r=i.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const o={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(o[u]=d);typeof e.serviceType=="string"&&(o.serviceType=e.serviceType),typeof e.userType=="string"&&(o.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,p)=>p in o?o[p]:""),s=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(s);if(u&&typeof u=="object"){const d={};for(const[p,g]of Object.entries(u))d[p]=s(g);return d}return u},a=await Zt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const d=r[u],p=n(d.url),g=d.method??(d.body?"POST":"GET"),h={accept:"application/json",...d.headers??{}};if((d.authHeader??"session")==="session"){const x=d.authHeaderTemplate??"Bearer {token}";h.authorization=x.replace("{token}",a)}const b={method:g,headers:h};d.body&&(h["content-type"]="application/json",b.body=JSON.stringify(s(d.body)));let y=0,w="",m=0,k=null;for(;;)try{const x=await fetch(p,b);if(x.ok){k=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&Cf(y,w)){const S=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${p} → ${y} (transient). Retry #${m} in ${S}ms.`),await new Promise(E=>setTimeout(E,S));continue}const v=`Preflight #${u} ${g} ${p} → ${y} ${w.slice(0,200)}`;if(d.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(x){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,x),await new Promise(S=>setTimeout(S,v));continue}if(d.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(k&&d.capture&&d.capture.as)try{const x=await k.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(d.capture.path)for(const S of d.capture.path.split("."))if(v&&typeof v=="object"&&S in v)v=v[S];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let S=v;d.capture.stripPrefix&&S.startsWith(d.capture.stripPrefix)&&(S=S.slice(d.capture.stripPrefix.length)),l[d.capture.as]=S,o[d.capture.as]=S,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${d.capture.as} (${S.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function Tf(i){const e=i.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await Vo(e,{sessionToken:i.sessionToken,userId:i.userId,projectId:i.projectId??"",slug:i.slug??"",identity:i.identity,serviceType:i.serviceType,userType:i.userType},"on-method-select")).captured:{}}function Cf(i,e){if(i===503||i===504||i===502)return!0;if(i===401||i===403)return e.trim().length===0;if(i===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Tc(i,e){const t=await fetch(i,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const o=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${o.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function Cc(i,e){return i.replace("{projectId}",e).replace("{uuid}",Sf().replace(/-/g,""))}function Pc(i){const e=i._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=>pc(r)))}async function Oc(i){const e={...i.config??(i.configUrl?await Tc(i.configUrl,i.configHeaders):{}),...i.overrides??{}};Pc(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=i.identity.userId,s=i.conversationScope||void 0,a=i.forceNewConversation?null:Ic(n,o,s),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=i.conversationId??a??Cc(l,o);(i.conversationId||!a||i.forceNewConversation)&&o&&Af(n,o,c,s);const u=await i.tokenProvider(),d=i.tokenProvider,p=i.historyTokenProvider??d,g=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:i.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,...i.identity.departmentId?{departmentId:i.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:i.identity.senderFullname??i.identity.userName,tokenProvider:d}:void 0,h=i.uploadAdapter??(e.uploadEndpoint?Po({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),b=i.historyAdapter??(e.historyApiBase?Wl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),y={transport:t,baseUrl:"",userToken:i.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:i.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:i.identity.userName,departmentId:i.identity.departmentId,senderFullname:i.identity.senderFullname??i.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:h,historyAdapter:b,onError:i.onError,onMessage:i.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;"),i.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function Pf(i){if(typeof i!="string")return i;const e=document.querySelector(i);if(!e)throw new Error(`mountFromSlug: container "${i}" not found`);return e}async function Lc(i){const e=(i.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(i.slug)}`;let r=null;try{r=await Tc(t,i.configHeaders)}catch(I){if(!i.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${i.slug}" — using fallbackConfig.`,I)}const o={...i.fallbackConfig??{},...r??{},...i.overrides??{}};if(Pc(o),o.templates&&Object.keys(o.templates).length>0){o.components={...o.components??{}};for(const[I,P]of Object.entries(o.templates)){const L=`template:${I}`;o.components[L]||!P?.scriptUrl||!P?.render||(o.components[L]={kind:"iife-element",scriptUrl:P.scriptUrl,tag:P.render,...P.props?{props:P.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:o.templates,components:o.components,razorpay:o.razorpay,title:o.title,cloud:o.cloud??n.__aikaara_descriptor__?.cloud,upload:o.upload??n.__aikaara_descriptor__?.upload,themeSource:o.themeSource??n.__aikaara_descriptor__?.themeSource,api:o.api,auth:o.auth,smartEdit:o.smartEdit??n.__aikaara_descriptor__?.smartEdit},!o.auth)throw new Error(`mountFromSlug: widget_configs/${i.slug} descriptor must include "auth" block`);let s=null,a=i.user.id,l=i.user.name,c="",u=i.user.token,d=null;const p=await Zt(i.user.token).catch(()=>""),g=typeof p=="string"&&p.length>0;if(!g&&o.sso?.tokenSource){d=new Ec({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:i.user.partnerToken});const I=await d.get();u=async()=>(await d.get()).token,i.user.identity&&!i.user.identity.partnerToken&&(i.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(i.slug)}/sso_exchange`;s=await new xc({descriptor:o.sso,providers:i.user.credentialProviders,exchangeUrl:I}).get(),a=s.extUid||a,l=l??s.displayName,c=s.userToken}let h="",b="";if(o.preflight&&o.preflight.length){const I=await Vo(o.preflight,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:i.slug,identity:i.user.identity});if(I.captured.sessionToken){h=I.captured.sessionToken;const P=h;u=()=>P}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(b=I.captured.requestId)}const y=new kc(o.auth,u);if(h){const I=o.tiledesk?.projectId??"",P=I?Ic(a,I):null,L=o.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",$=P??(I?Cc(L,I):"");y.prime(h,{requestId:$,fullName:l})}const w=await y.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,getSessionToken:()=>Zt(i.user.token),identity:i.user.identity,slug:i.slug,configBase:e};const k=d&&o.sso?.autoRefresh?async()=>{try{return await d.refresh(),y.reset(),(await y.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=o.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await y.get()).token:await Zt(i.user.token)}`,S=i.hooks?.upload??(x&&x.mode==="presigned-3step"?Hl({...x,authHeader:v}):x&&x.mode==="direct"?Po({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),E=await Oc({container:Pf(i.container),config:o,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:i.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:S,historyAdapter:i.hooks?.history,conversationId:w.requestId||b||void 0,conversationScope:i.conversationScope,onError:i.hooks?.onError,onMessage:i.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Zt(i.user.token)});return Object.assign(E,{fullName:m,requestId:w.requestId,descriptor:o,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return k?k():null},async runMethodSelectPreflight(I){const P=o.preflight;return!P||!P.length?{}:P.some($=>$.trigger==="on-method-select")?(await Vo(P,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:i.slug,identity:{...i.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}function Of(i){Wo();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=i[r];n!=null&&e.setAttribute(o,String(n))}return e.configure(i),document.body.appendChild(e),e}function Lf(){const i=document.querySelector("aikaara-chat-widget");i&&i.remove()}const Mf="https://checkout.razorpay.com/v1/checkout.js";let mr=null;function gr(){return window}class Mc 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",s=!!this.paidIdx[o];return`<button class="link${s?" paid":""}" data-i="${o}" type="button"${s?" disabled":""}><span class="lbl">${Nf(s?"Paid":n)}</span>`+(s?'<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=Rf(t),o=gr().__aikaara_descriptor__,n=o?.partnerPayment,s=o?.razorpay;if(r&&n?.paymentLinkUrl){this.openPartnerPaymentLink(e,r,t,n);return}if(!r||!s?.keyId){t.openLinkInNewTab?window.open(t.url,"_blank","noopener,noreferrer"):Ff(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}$f(s.preferredBanksUrl,r,s.preferredBanksMethod,s.preferredBanksHeaders).catch(a=>(console.warn("[payment_link] preferred-banks fetch failed; continuing with default UI",a),[])).then(a=>jf().then(()=>this.openRazorpay(e,r,s,a))).catch(a=>{console.error("[payment_link] Razorpay launch failed",a)})}openPartnerPaymentLink(e,t,r,o){Df(t,o).then(n=>{if(!n){er("Failed to generate payment link, please try again later");return}const s=(n.paymentStatus??"").toLowerCase();if(s==="paid"||s==="success"||s==="completed"){this.paidIdx[e]=!0,this.render(),er("Payment already completed");return}const a=n.vendorPaymentLink;if(!a){er("Failed to generate payment link, please try again later");return}const l=navigator.userAgent.toLowerCase();if(l.includes("iphone")||l.includes("ipad")||l.includes("ipod")){window.location.href=a;return}const u=Uf(a);if(!u){window.open(a,"_blank"),er("Allow popups for the best payment experience");return}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:r.name||"link-click",attributes:{action:{type:"partner-payment",url:a,orderId:t,openedIn:"popup"}}},bubbles:!0,composed:!0})),Bf(u,o.checkoutOrigin,{onSuccess:()=>{this.paidIdx[e]=!0,this.render()},onError:d=>{er(d||"Payment failed, please try again")},onClose:()=>{}})}).catch(n=>{console.error("[payment_link] partner payment link fetch failed",n),er("Failed to generate payment link, please try again later")})}openRazorpay(e,t,r,o){const n=gr(),s=n.__aikaara_runtime__?.identity??{},a={key:r.keyId,order_id:t,name:r.name||n.__aikaara_descriptor__?.title||"Payment",prefill:{},handler:()=>{this.paidIdx[e]=!0,this.render()},modal:{ondismiss:()=>{}}};typeof s.mobile=="string"?a.prefill.contact=s.mobile:typeof s.phone=="string"&&(a.prefill.contact=s.phone),typeof s.email=="string"&&(a.prefill.email=s.email),typeof s.name=="string"?a.prefill.name=s.name:typeof s.userName=="string"&&(a.prefill.name=s.userName),Array.isArray(o)&&o.length&&(a.config={display:{blocks:{utib:{name:"Pay Using Preferred Netbanking",instruments:[{method:"netbanking",banks:o}]}},sequence:["block.utib","netbanking","card","upi"],preferences:{show_default_blocks:!0}}});const l=n.Razorpay;if(typeof l!="function")throw new Error("Razorpay Checkout script not available");const c=new l(a);c.on("payment.failed",u=>{console.warn("[payment_link] payment.failed",u?.error)}),c.open()}}function Nf(i){return String(i??"").replace(/[&<>]/g,e=>e==="&"?"&":e==="<"?"<":">")}function Rf(i){if(typeof i.orderId=="string"&&i.orderId)return i.orderId;try{const e=new URL(i.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 jf(){return typeof gr().Razorpay=="function"?Promise.resolve():mr||(mr=new Promise((i,e)=>{const t=document.querySelector('script[data-aikaara-razorpay="1"]');if(t){t.addEventListener("load",()=>i()),t.addEventListener("error",()=>e(new Error("checkout.js failed to load")));return}const r=document.createElement("script");r.src=Mf,r.async=!0,r.dataset.aikaaraRazorpay="1",r.onload=()=>i(),r.onerror=()=>{mr=null,e(new Error("checkout.js failed to load"))},document.head.appendChild(r)}),mr)}function $f(i,e,t,r){if(!i)return Promise.resolve([]);const o=String(t||"GET").toUpperCase()==="POST"?"POST":"GET",n=i.includes("{orderId}")?i.replace("{orderId}",encodeURIComponent(e)):i+(i.includes("?")?"&":"?")+"orderId="+encodeURIComponent(e),s=gr().__aikaara_runtime__??{};return(typeof s.getSessionToken=="function"?s.getSessionToken():typeof s.getChatJwt=="function"?s.getChatJwt():Promise.resolve(null)).then(l=>{const c={Accept:"application/json",...r??{}};l&&(c.Authorization=`Bearer ${l}`);const u={method:o,headers:c,credentials:"omit"};return o==="POST"&&(c["Content-Type"]="application/json",u.body=JSON.stringify({orderId:e})),fetch(n,u)}).then(l=>{if(!l.ok)throw new Error(`preferred-banks ${l.status}`);return l.json()}).then(l=>{const c=l,u=c?.data&&typeof c.data=="object"&&!Array.isArray(c.data)?c.data:null;return(Array.isArray(l)?l:Array.isArray(c?.banks)?c.banks:Array.isArray(c?.data)?c.data:Array.isArray(u?.preferredPaymentBank)?u.preferredPaymentBank:Array.isArray(u?.banks)?u.banks:[]).map(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)})}async function Df(i,e){const t=String(e.method||"GET").toUpperCase()==="POST"?"POST":"GET",r=e.paymentLinkUrl,o=r.includes("{orderId}")?r.replace("{orderId}",encodeURIComponent(i)):r+(r.includes("?")?"&":"?")+"orderId="+encodeURIComponent(i),n=gr().__aikaara_runtime__??{},s=typeof n.getSessionToken=="function"?await n.getSessionToken():typeof n.getChatJwt=="function"?await n.getChatJwt():null,a={Accept:"application/json",...e.headers??{}};s&&(a.Authorization=`Bearer ${s}`);const l={method:t,headers:a,credentials:"omit"};t==="POST"&&(a["Content-Type"]="application/json",l.body=JSON.stringify({orderId:i}));const c=await fetch(o,l);if(!c.ok)throw new Error(`partner-payment-link ${c.status}`);const d=(await c.json())?.data;return!d||typeof d.vendorPaymentLink!="string"?null:{vendorPaymentLink:d.vendorPaymentLink,paymentStatus:d.paymentStatus??""}}function Uf(i){const r=window.screenX+Math.round((window.outerWidth-520)/2),o=window.screenY+Math.round((window.outerHeight-680)/2);return window.open(i,"taxbuddy_payment",`width=520,height=680,left=${r},top=${o},scrollbars=yes,resizable=yes`)}function Bf(i,e,t){let r=!1;function o(){clearInterval(a),window.removeEventListener("message",s)}function n(l){r||(r=!0,o(),l())}function s(l){if(e&&l.origin!==e)return;const c=l.data;if(!(!c||typeof c!="object")){if(c.type==="payment-completed"&&c.success===!0){n(()=>t.onSuccess());return}c.type==="payment-error"&&c.success===!1&&n(()=>t.onError(c.error??"Payment failed"))}}const a=setInterval(()=>{i.closed&&n(()=>t.onClose())},500);window.addEventListener("message",s)}function er(i){try{const e=document.querySelector("aikaara-error-banner");if(e&&typeof e.show=="function"){e.show(i);return}}catch{}console.warn("[payment_link]",i)}function Ff(i,e){if(!i)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(i,e):window.open(i,"_blank","noopener,noreferrer")}function qf(){typeof customElements>"u"||customElements.get("aikaara-template-payment-link")||customElements.define("aikaara-template-payment-link",Mc)}const Hf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraPaymentLink:Mc,registerAikaaraPaymentLink:qf},Symbol.toStringTag,{value:"Module"}));class Nc 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=`
|
|
1941
1941
|
<style>
|
|
1942
1942
|
:host { display: block; margin-top: 8px; }
|
|
1943
1943
|
button {
|
|
@@ -1961,4 +1961,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1961
1961
|
${Wf(e?.name??"Open")}
|
|
1962
1962
|
<span aria-hidden="true">↗</span>
|
|
1963
1963
|
</button>
|
|
1964
|
-
`,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:s,messageId:a}=this.payload,l=o?"popup":r?"tab":"modal",c=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:n,openedIn:l,extra:s,messageId:a},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(c))if(o)
|
|
1964
|
+
`,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:s,messageId:a}=this.payload,l=o?"popup":r?"tab":"modal",c=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:n,openedIn:l,extra:s,messageId:a},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(c))if(o)nc(e);else if(r)window.open(e,"_blank","noopener,noreferrer");else{const d=zf();requestAnimationFrame(()=>d?.show?.(e,t))}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t,attributes:{action:{type:"link",url:e,orderId:n,openedIn:l,...s??{}},...a?{message_id:a}:{}}},bubbles:!0,composed:!0}))}}function Wf(i){return i.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function zf(){if(typeof document>"u")return null;let i=document.querySelector("aikaara-link-modal");if(!i){const e=document.createElement("aikaara-link-modal");document.body.appendChild(e),i=e}return i}function Vf(){typeof customElements>"u"||customElements.get("aikaara-link-button")||customElements.define("aikaara-link-button",Nc)}const Kf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraLinkButton:Nc,registerAikaaraLinkButton:Vf},Symbol.toStringTag,{value:"Module"}));return Ne.ActionCableClient=fn,Ne.AikaaraChatBubble=ec,Ne.AikaaraChatClient=Fl,Ne.AikaaraChatHeader=tc,Ne.AikaaraChatInput=cc,Ne.AikaaraChatWidget=Zl,Ne.AikaaraErrorBanner=hc,Ne.AikaaraMessageBubble=ac,Ne.AikaaraMessageList=ic,Ne.AikaaraStreamingMessage=dc,Ne.AikaaraTypingIndicator=uc,Ne.ApiClient=Zo,Ne.ChannelSubscription=Yo,Ne.ConnectionManager=Xo,Ne.ConversationManager=os,Ne.EventEmitter=_r,Ne.FormBridge=fh,Ne.MessageStore=es,Ne.SessionAuthAdapter=kc,Ne.SsoExchangeAdapter=xc,Ne.TiledeskTransport=jl,Ne.TokenDiscoveryError=Ze,Ne.TokenDiscoveryReader=Ec,Ne.clearPersistedConversationId=If,Ne.collectSsoCredentials=_c,Ne.createFetchUploadAdapter=Po,Ne.createPresigned3StepUploadAdapter=Hl,Ne.createTiledeskHistoryAdapter=Wl,Ne.discoverToken=Sc,Ne.extractTiledeskFileEnvelope=Ul,Ne.inferTiledeskRole=Dl,Ne.isTiledeskSelfEcho=$l,Ne.mount=Of,Ne.mountFromSlug=Lc,Ne.mountTenantWidget=Oc,Ne.parseTiledeskTemplate=Co,Ne.registerComponents=Wo,Ne.runMethodSelectPreflight=Tf,Ne.unmount=Lf,Object.defineProperty(Ne,Symbol.toStringTag,{value:"Module"}),Ne})({});
|