@aikaara/chat-sdk 1.3.2 → 1.3.4

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.
@@ -0,0 +1,1471 @@
1
+ "use strict";class Ws{identifier;callbacks={};sendFn;constructor(e,t){this.identifier=e,this.sendFn=t}onReceived(e){return this.callbacks.received=e,this}onConnected(e){return this.callbacks.connected=e,this}onDisconnected(e){return this.callbacks.disconnected=e,this}onRejected(e){return this.callbacks.rejected=e,this}perform(e,t={}){this.sendFn({action:e,...t})}_notifyReceived(e){this.callbacks.received?.(e)}_notifyConnected(){this.callbacks.connected?.()}_notifyDisconnected(){this.callbacks.disconnected?.()}_notifyRejected(){this.callbacks.rejected?.()}}class en{ws=null;url;subscriptions=new Map;welcomePromise=null;pendingSubscriptions=new Map;constructor(e){this.url=e}connect(){return new Promise((e,t)=>{this.welcomePromise={resolve:e,reject:t},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=r=>{this.handleMessage(r)},this.ws.onerror=()=>{const r=new Error("WebSocket connection error");this.welcomePromise?.reject(r),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(r=>r._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(e=>e._notifyDisconnected()),this.subscriptions.clear()}subscribe(e){const t=JSON.stringify(e),r=new Ws(t,i=>{this.send({command:"message",identifier:t,data:JSON.stringify(i)})});return this.subscriptions.set(t,r),this.send({command:"subscribe",identifier:t}),r}subscribeAsync(e){const t=this.subscribe(e),r=t.identifier;return new Promise((i,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>i(t),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(r)&&(this.pendingSubscriptions.delete(r),n(new Error(`Subscription timeout for ${r}`)))},1e4)})}unsubscribe(e){this.send({command:"unsubscribe",identifier:e}),this.subscriptions.delete(e)}perform(e,t,r={}){this.send({command:"message",identifier:e,data:JSON.stringify({action:t,...r})})}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}send(e){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(e.data)}catch{return}switch(t.type){case"welcome":this.welcomePromise?.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyConnected();const n=this.pendingSubscriptions.get(r);n&&(n.resolve(),this.pendingSubscriptions.delete(r));break}case"reject_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyRejected(),this.subscriptions.delete(r);const n=this.pendingSubscriptions.get(r);n&&(n.reject(new Error(`Subscription rejected: ${r}`)),this.pendingSubscriptions.delete(r));break}case"disconnect":this.subscriptions.forEach(r=>r._notifyDisconnected());break;default:{t.identifier&&t.message!==void 0&&this.subscriptions.get(t.identifier)?._notifyReceived(t.message);break}}}}class ro{handlers=new Map;on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){this.handlers.get(e)?.forEach(r=>{try{r(t)}catch(i){console.error(`Error in event handler for "${e}":`,i)}})}removeAllListeners(){this.handlers.clear()}}const vc=1e3,wc=10,_c=400,kc=600,_o="#6366f1",xc=12,Sc="system-ui, -apple-system, sans-serif",ko="Type a message...",Ec="bottom-right",Ac="light",Ic={x:20,y:20},zr="aikaara_conversation_id";class zs extends ro{client;config;state="disconnected";reconnectAttempt=0;reconnectTimer=null;constructor(e){super(),this.config=e;const t=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new en(t)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,t){const r=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(r,"send_message",{content:t})}sendUserEvent(e,t,r,i){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...i&&{source:i}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??wc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??vc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const i=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new en(i),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const i=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${i}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class Vs{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,i){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=i}setAuthRefreshHook(e){this.refreshHook=e}getAuthToken(){return this.authToken}setAuthToken(e){this.authToken=e}async createConversation(e){const t={conversation:{...e.extUid&&{ext_uid:e.extUid},...e.systemPromptId&&{system_prompt_id:e.systemPromptId},...e.channel&&{channel:e.channel},...e.title&&{title:e.title}}};return this.request("POST","/api/v1/conversations",t)}async updateContext(e,t){const r=this.authToken?`/dashboard/sidekick_conversations/${e}`:`/api/v1/conversations/${e}`;await this.request("PATCH",r,t)}async getMessages(e){return(await this.request("GET",`/api/v1/conversations/${e}/messages`)).map(this.mapMessage)}mapMessage(e){return{id:String(e.id),conversationId:String(e.conversation_id),role:e.role,content:e.content||"",toolCalls:e.tool_calls?.map(t=>({id:t.id,type:t.type,function:t.function})),toolCallResults:e.tool_call_results,tokensInput:e.tokens_input,tokensOutput:e.tokens_output,metadata:e.metadata,createdAt:e.created_at,status:"complete"}}async request(e,t,r){const i=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(i,e,r);if(n.status===401&&this.refreshHook){let s=null;try{s=await this.refreshHook()}catch(l){console.warn("[aikaara-chat-sdk] auth refresh hook threw",l)}s&&(this.authToken=s,n=await this.fetchWithHeaders(i,e,r))}if(!n.ok){const s=await n.text();let l;try{const c=JSON.parse(s);l=c.error||c.message||s}catch{l=s}throw new Error(`API error ${n.status}: ${l}`)}const o=await n.json();if(o&&typeof o=="object"&&"success"in o){if(!o.success)throw new Error(`API error: ${o.message||"Request failed"}`);return o.data}return o}async fetchWithHeaders(e,t,r){const i={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(i["X-Api-Key"]=this.apiKey),this.authToken&&(i.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:i};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class Gs{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const i={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(i),i}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(i=>i.status==="sending"&&i.role===e.role&&i.content===e.content&&i.conversationId===e.conversationId&&Date.now()-new Date(i.createdAt).getTime()<t);return r?(r.status=e.status??"sent",r.externalId=e.externalId??e.id,e.template&&(r.template=e.template),e.attachments&&(r.attachments=e.attachments),e.metadata&&(r.metadata={...r.metadata??{},...e.metadata}),r):null}upsertRemoteMessage(e){const t=this.reconcileOptimistic(e);if(t)return{message:t,deduped:!0};const r=e.externalId?this._messages.find(n=>n.externalId&&n.externalId===e.externalId):void 0;if(r)return Object.assign(r,e,{id:r.id}),{message:r,deduped:!0};const i=xo(this._messages,e);return i?(Object.assign(i,e,{id:i.id}),{message:i,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(i=>i.externalId===e||i.id===e);return r&&(r.status=t),r}confirmOptimistic(e){const t=this._messages.find(r=>r.id===e);t&&(t.status="sent")}addStreamingMessage(e){const t={id:`streaming_${Date.now()}`,conversationId:e,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(t),t}updateStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content=e)}appendToStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content+=e)}get streamingContent(){return this._messages.findLast(t=>t.status==="streaming")?.content||""}finalizeStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");return t&&(t.status="complete",e&&(t.tokensInput=e.tokensInput,t.tokensOutput=e.tokensOutput)),t}addMessage(e){this._messages.push(e)}setMessages(e){const t=[];for(const r of e){const i=xo(t,r);if(i){const n=jr(i),o=jr(r);!n&&o&&Object.assign(i,r,{id:i.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function xo(a,e,t=15e3){const r=e.attachments&&e.attachments[0],i=(e.metadata??{}).attributes;if(!(!!r||!!(i&&i.fileMessage)))return null;const o=jr(e),s=So(e),l=Eo(e);if(!o&&!s&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=a.length-1;u>=0;u--){const h=a[u],p=h.attachments&&h.attachments[0],b=(h.metadata??{}).attributes;if(!(!!p||!!(b&&b.fileMessage)))continue;const g=(h.content||"").trim().toLowerCase();if(g==="file_uploaded"||g==="file_upload"||Math.abs(c-new Date(h.createdAt).getTime())>t)continue;const y=jr(h);if(o&&y&&o===y)return h;const w=So(h);if(s&&w&&s===w)return h;const m=Eo(h);if(l&&m&&l===m)return h}return null}function So(a){const e=a.attachments&&a.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=Ks(a);if(t)return t}function Eo(a){const e=a.attachments&&a.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(a.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=a.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function jr(a){const e=a.attachments&&a.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(a.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=Ks(a);if(r){const i=/[?&]cloudFileId=([^&]+)/.exec(r);if(i)return decodeURIComponent(i[1])}}function Ks(a){const e=a.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class Ys{_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(zr)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(zr)}catch{return null}}saveToStorage(e){try{localStorage.setItem(zr,e)}catch{}}}var no=Object.defineProperty,Tc=Object.getOwnPropertyDescriptor,Cc=Object.getOwnPropertyNames,Oc=Object.prototype.hasOwnProperty,Ve=(a,e)=>()=>(a&&(e=a(a=0)),e),pe=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Dt=(a,e)=>{for(var t in e)no(a,t,{get:e[t],enumerable:!0})},Pc=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Cc(e))!Oc.call(a,i)&&i!==t&&no(a,i,{get:()=>e[i],enumerable:!(r=Tc(e,i))||r.enumerable});return a},Pe=a=>Pc(no({},"__esModule",{value:!0}),a),le=Ve(()=>{}),Re={};Dt(Re,{_debugEnd:()=>jn,_debugProcess:()=>Ln,_events:()=>Qn,_eventsCount:()=>Jn,_exiting:()=>wn,_fatalExceptions:()=>Pn,_getActiveHandles:()=>ra,_getActiveRequests:()=>ta,_kill:()=>xn,_linkedBinding:()=>Zs,_maxListeners:()=>Yn,_preload_modules:()=>Gn,_rawDebug:()=>bn,_startProfilerIdleNotifier:()=>Nn,_stopProfilerIdleNotifier:()=>Un,_tickCallback:()=>Rn,abort:()=>$n,addListener:()=>Xn,allowedNodeEnvironmentFlags:()=>Cn,arch:()=>rn,argv:()=>sn,argv0:()=>Vn,assert:()=>na,binding:()=>hn,browser:()=>gn,chdir:()=>pn,config:()=>_n,cpuUsage:()=>Gt,cwd:()=>fn,debugPort:()=>zn,default:()=>oo,dlopen:()=>ea,domain:()=>vn,emit:()=>ni,emitWarning:()=>un,env:()=>on,execArgv:()=>an,execPath:()=>Wn,exit:()=>In,features:()=>On,hasUncaughtExceptionCaptureCallback:()=>ia,hrtime:()=>ur,kill:()=>An,listeners:()=>sa,memoryUsage:()=>En,moduleLoadList:()=>yn,nextTick:()=>Js,off:()=>ei,on:()=>st,once:()=>Zn,openStdin:()=>Tn,pid:()=>qn,platform:()=>nn,ppid:()=>Hn,prependListener:()=>ii,prependOnceListener:()=>oi,reallyExit:()=>kn,release:()=>mn,removeAllListeners:()=>ri,removeListener:()=>ti,resourceUsage:()=>Sn,setSourceMapsEnabled:()=>Kn,setUncaughtExceptionCaptureCallback:()=>Mn,stderr:()=>Dn,stdin:()=>Fn,stdout:()=>Bn,title:()=>tn,umask:()=>dn,uptime:()=>oa,version:()=>ln,versions:()=>cn});function io(a){throw new Error("Node.js process "+a+" is not supported by JSPM core outside of Node.js")}function Mc(){!It||!Et||(It=!1,Et.length?nt=Et.concat(nt):Jt=-1,nt.length&&Qs())}function Qs(){if(!It){var a=setTimeout(Mc,0);It=!0;for(var e=nt.length;e;){for(Et=nt,nt=[];++Jt<e;)Et&&Et[Jt].run();Jt=-1,e=nt.length}Et=null,It=!1,clearTimeout(a)}}function Js(a){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];nt.push(new Xs(a,e)),nt.length===1&&!It&&setTimeout(Qs,0)}function Xs(a,e){this.fun=a,this.array=e}function Fe(){}function Zs(a){io("_linkedBinding")}function ea(a){io("dlopen")}function ta(){return[]}function ra(){return[]}function na(a,e){if(!a)throw new Error(e||"assertion error")}function ia(){return!1}function oa(){return lt.now()/1e3}function ur(a){var e=Math.floor((Date.now()-lt.now())*.001),t=lt.now()*.001,r=Math.floor(t)+e,i=Math.floor(t%1*1e9);return a&&(r=r-a[0],i=i-a[1],i<0&&(r--,i+=hr)),[r,i]}function st(){return oo}function sa(a){return[]}var nt,It,Et,Jt,tn,rn,nn,on,sn,an,ln,cn,un,hn,dn,fn,pn,mn,gn,bn,yn,vn,wn,_n,kn,xn,Gt,Sn,En,An,In,Tn,Cn,On,Pn,Mn,Rn,Ln,jn,Nn,Un,Bn,Dn,Fn,$n,qn,Hn,Wn,zn,Vn,Gn,Kn,lt,Vr,hr,Yn,Qn,Jn,Xn,Zn,ei,ti,ri,ni,ii,oi,oo,Rc=Ve(()=>{le(),ue(),ce(),nt=[],It=!1,Jt=-1,Xs.prototype.run=function(){this.fun.apply(null,this.array)},tn="browser",rn="x64",nn="browser",on={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},sn=["/usr/bin/node"],an=[],ln="v16.8.0",cn={},un=function(a,e){console.warn((e?e+": ":"")+a)},hn=function(a){io("binding")},dn=function(a){return 0},fn=function(){return"/"},pn=function(a){},mn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},gn=!0,bn=Fe,yn=[],vn={},wn=!1,_n={},kn=Fe,xn=Fe,Gt=function(){return{}},Sn=Gt,En=Gt,An=Fe,In=Fe,Tn=Fe,Cn={},On={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Pn=Fe,Mn=Fe,Rn=Fe,Ln=Fe,jn=Fe,Nn=Fe,Un=Fe,Bn=void 0,Dn=void 0,Fn=void 0,$n=Fe,qn=2,Hn=1,Wn="/bin/usr/node",zn=9229,Vn="node",Gn=[],Kn=Fe,lt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},lt.now===void 0&&(Vr=Date.now(),lt.timing&&lt.timing.navigationStart&&(Vr=lt.timing.navigationStart),lt.now=()=>Date.now()-Vr),hr=1e9,ur.bigint=function(a){var e=ur(a);return typeof BigInt>"u"?e[0]*hr+e[1]:BigInt(e[0]*hr)+BigInt(e[1])},Yn=10,Qn={},Jn=0,Xn=st,Zn=st,ei=st,ti=st,ri=st,ni=Fe,ii=st,oi=st,oo={version:ln,versions:cn,arch:rn,platform:nn,browser:gn,release:mn,_rawDebug:bn,moduleLoadList:yn,binding:hn,_linkedBinding:Zs,_events:Qn,_eventsCount:Jn,_maxListeners:Yn,on:st,addListener:Xn,once:Zn,off:ei,removeListener:ti,removeAllListeners:ri,emit:ni,prependListener:ii,prependOnceListener:oi,listeners:sa,domain:vn,_exiting:wn,config:_n,dlopen:ea,uptime:oa,_getActiveRequests:ta,_getActiveHandles:ra,reallyExit:kn,_kill:xn,cpuUsage:Gt,resourceUsage:Sn,memoryUsage:En,kill:An,exit:In,openStdin:Tn,allowedNodeEnvironmentFlags:Cn,assert:na,features:On,_fatalExceptions:Pn,setUncaughtExceptionCaptureCallback:Mn,hasUncaughtExceptionCaptureCallback:ia,emitWarning:un,nextTick:Js,_tickCallback:Rn,_debugProcess:Ln,_debugEnd:jn,_startProfilerIdleNotifier:Nn,_stopProfilerIdleNotifier:Un,stdout:Bn,stdin:Fn,stderr:Dn,abort:$n,umask:dn,chdir:pn,cwd:fn,env:on,title:tn,argv:sn,execArgv:an,pid:qn,ppid:Hn,execPath:Wn,debugPort:zn,hrtime:ur,argv0:Vn,_preload_modules:Gn,setSourceMapsEnabled:Kn}}),ce=Ve(()=>{Rc()});function Lc(){if(si)return Lt;si=!0,Lt.byteLength=s,Lt.toByteArray=c,Lt.fromByteArray=p;for(var a=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,n=r.length;i<n;++i)a[i]=r[i],e[r.charCodeAt(i)]=i;e[45]=62,e[95]=63;function o(b){var f=b.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var g=b.indexOf("=");g===-1&&(g=f);var y=g===f?0:4-g%4;return[g,y]}function s(b){var f=o(b),g=f[0],y=f[1];return(g+y)*3/4-y}function l(b,f,g){return(f+g)*3/4-g}function c(b){var f,g=o(b),y=g[0],w=g[1],m=new t(l(b,y,w)),_=0,x=w>0?y-4:y,v;for(v=0;v<x;v+=4)f=e[b.charCodeAt(v)]<<18|e[b.charCodeAt(v+1)]<<12|e[b.charCodeAt(v+2)]<<6|e[b.charCodeAt(v+3)],m[_++]=f>>16&255,m[_++]=f>>8&255,m[_++]=f&255;return w===2&&(f=e[b.charCodeAt(v)]<<2|e[b.charCodeAt(v+1)]>>4,m[_++]=f&255),w===1&&(f=e[b.charCodeAt(v)]<<10|e[b.charCodeAt(v+1)]<<4|e[b.charCodeAt(v+2)]>>2,m[_++]=f>>8&255,m[_++]=f&255),m}function u(b){return a[b>>18&63]+a[b>>12&63]+a[b>>6&63]+a[b&63]}function h(b,f,g){for(var y,w=[],m=f;m<g;m+=3)y=(b[m]<<16&16711680)+(b[m+1]<<8&65280)+(b[m+2]&255),w.push(u(y));return w.join("")}function p(b){for(var f,g=b.length,y=g%3,w=[],m=16383,_=0,x=g-y;_<x;_+=m)w.push(h(b,_,_+m>x?x:_+m));return y===1?(f=b[g-1],w.push(a[f>>2]+a[f<<4&63]+"==")):y===2&&(f=(b[g-2]<<8)+b[g-1],w.push(a[f>>10]+a[f>>4&63]+a[f<<2&63]+"=")),w.join("")}return Lt}function jc(){return ai?Kt:(ai=!0,Kt.read=function(a,e,t,r,i){var n,o,s=i*8-r-1,l=(1<<s)-1,c=l>>1,u=-7,h=t?i-1:0,p=t?-1:1,b=a[e+h];for(h+=p,n=b&(1<<-u)-1,b>>=-u,u+=s;u>0;n=n*256+a[e+h],h+=p,u-=8);for(o=n&(1<<-u)-1,n>>=-u,u+=r;u>0;o=o*256+a[e+h],h+=p,u-=8);if(n===0)n=1-c;else{if(n===l)return o?NaN:(b?-1:1)*(1/0);o=o+Math.pow(2,r),n=n-c}return(b?-1:1)*o*Math.pow(2,n-r)},Kt.write=function(a,e,t,r,i,n){var o,s,l,c=n*8-i-1,u=(1<<c)-1,h=u>>1,p=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,b=r?0:n-1,f=r?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+h>=1?e+=p/l:e+=p*Math.pow(2,1-h),e*l>=2&&(o++,l/=2),o+h>=u?(s=0,o=u):o+h>=1?(s=(e*l-1)*Math.pow(2,i),o=o+h):(s=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;a[t+b]=s&255,b+=f,s/=256,i-=8);for(o=o<<i|s,c+=i;c>0;a[t+b]=o&255,b+=f,o/=256,c-=8);a[t+b-f]|=g*128},Kt)}function Nc(){if(li)return bt;li=!0;let a=Lc(),e=jc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;bt.Buffer=o,bt.SlowBuffer=w,bt.INSPECT_MAX_BYTES=50;let r=2147483647;bt.kMaxLength=r,o.TYPED_ARRAY_SUPPORT=i(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{let d=new Uint8Array(1),k={foo:function(){return 42}};return Object.setPrototypeOf(k,Uint8Array.prototype),Object.setPrototypeOf(d,k),d.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function n(d){if(d>r)throw new RangeError('The value "'+d+'" is invalid for option "size"');let k=new Uint8Array(d);return Object.setPrototypeOf(k,o.prototype),k}function o(d,k,A){if(typeof d=="number"){if(typeof k=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(d)}return s(d,k,A)}o.poolSize=8192;function s(d,k,A){if(typeof d=="string")return h(d,k);if(ArrayBuffer.isView(d))return b(d);if(d==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof d);if(H(d,ArrayBuffer)||d&&H(d.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(d,SharedArrayBuffer)||d&&H(d.buffer,SharedArrayBuffer)))return f(d,k,A);if(typeof d=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=d.valueOf&&d.valueOf();if(B!=null&&B!==d)return o.from(B,k,A);let X=g(d);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof d[Symbol.toPrimitive]=="function")return o.from(d[Symbol.toPrimitive]("string"),k,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof d)}o.from=function(d,k,A){return s(d,k,A)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(d){if(typeof d!="number")throw new TypeError('"size" argument must be of type number');if(d<0)throw new RangeError('The value "'+d+'" is invalid for option "size"')}function c(d,k,A){return l(d),d<=0?n(d):k!==void 0?typeof A=="string"?n(d).fill(k,A):n(d).fill(k):n(d)}o.alloc=function(d,k,A){return c(d,k,A)};function u(d){return l(d),n(d<0?0:y(d)|0)}o.allocUnsafe=function(d){return u(d)},o.allocUnsafeSlow=function(d){return u(d)};function h(d,k){if((typeof k!="string"||k==="")&&(k="utf8"),!o.isEncoding(k))throw new TypeError("Unknown encoding: "+k);let A=m(d,k)|0,B=n(A),X=B.write(d,k);return X!==A&&(B=B.slice(0,X)),B}function p(d){let k=d.length<0?0:y(d.length)|0,A=n(k);for(let B=0;B<k;B+=1)A[B]=d[B]&255;return A}function b(d){if(H(d,Uint8Array)){let k=new Uint8Array(d);return f(k.buffer,k.byteOffset,k.byteLength)}return p(d)}function f(d,k,A){if(k<0||d.byteLength<k)throw new RangeError('"offset" is outside of buffer bounds');if(d.byteLength<k+(A||0))throw new RangeError('"length" is outside of buffer bounds');let B;return k===void 0&&A===void 0?B=new Uint8Array(d):A===void 0?B=new Uint8Array(d,k):B=new Uint8Array(d,k,A),Object.setPrototypeOf(B,o.prototype),B}function g(d){if(o.isBuffer(d)){let k=y(d.length)|0,A=n(k);return A.length===0||d.copy(A,0,0,k),A}if(d.length!==void 0)return typeof d.length!="number"||me(d.length)?n(0):p(d);if(d.type==="Buffer"&&Array.isArray(d.data))return p(d.data)}function y(d){if(d>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return d|0}function w(d){return+d!=d&&(d=0),o.alloc(+d)}o.isBuffer=function(d){return d!=null&&d._isBuffer===!0&&d!==o.prototype},o.compare=function(d,k){if(H(d,Uint8Array)&&(d=o.from(d,d.offset,d.byteLength)),H(k,Uint8Array)&&(k=o.from(k,k.offset,k.byteLength)),!o.isBuffer(d)||!o.isBuffer(k))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(d===k)return 0;let A=d.length,B=k.length;for(let X=0,he=Math.min(A,B);X<he;++X)if(d[X]!==k[X]){A=d[X],B=k[X];break}return A<B?-1:B<A?1:0},o.isEncoding=function(d){switch(String(d).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(d,k){if(!Array.isArray(d))throw new TypeError('"list" argument must be an Array of Buffers');if(d.length===0)return o.alloc(0);let A;if(k===void 0)for(k=0,A=0;A<d.length;++A)k+=d[A].length;let B=o.allocUnsafe(k),X=0;for(A=0;A<d.length;++A){let he=d[A];if(H(he,Uint8Array))X+he.length>B.length?(o.isBuffer(he)||(he=o.from(he)),he.copy(B,X)):Uint8Array.prototype.set.call(B,he,X);else if(o.isBuffer(he))he.copy(B,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=he.length}return B};function m(d,k){if(o.isBuffer(d))return d.length;if(ArrayBuffer.isView(d)||H(d,ArrayBuffer))return d.byteLength;if(typeof d!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof d);let A=d.length,B=arguments.length>2&&arguments[2]===!0;if(!B&&A===0)return 0;let X=!1;for(;;)switch(k){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return $(d).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(d).length;default:if(X)return B?-1:$(d).length;k=(""+k).toLowerCase(),X=!0}}o.byteLength=m;function _(d,k,A){let B=!1;if((k===void 0||k<0)&&(k=0),k>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,k>>>=0,A<=k))return"";for(d||(d="utf8");;)switch(d){case"hex":return V(this,k,A);case"utf8":case"utf-8":return q(this,k,A);case"ascii":return ae(this,k,A);case"latin1":case"binary":return Y(this,k,A);case"base64":return T(this,k,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,k,A);default:if(B)throw new TypeError("Unknown encoding: "+d);d=(d+"").toLowerCase(),B=!0}}o.prototype._isBuffer=!0;function x(d,k,A){let B=d[k];d[k]=d[A],d[A]=B}o.prototype.swap16=function(){let d=this.length;if(d%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let k=0;k<d;k+=2)x(this,k,k+1);return this},o.prototype.swap32=function(){let d=this.length;if(d%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let k=0;k<d;k+=4)x(this,k,k+3),x(this,k+1,k+2);return this},o.prototype.swap64=function(){let d=this.length;if(d%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let k=0;k<d;k+=8)x(this,k,k+7),x(this,k+1,k+6),x(this,k+2,k+5),x(this,k+3,k+4);return this},o.prototype.toString=function(){let d=this.length;return d===0?"":arguments.length===0?q(this,0,d):_.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(d){if(!o.isBuffer(d))throw new TypeError("Argument must be a Buffer");return this===d?!0:o.compare(this,d)===0},o.prototype.inspect=function(){let d="",k=bt.INSPECT_MAX_BYTES;return d=this.toString("hex",0,k).replace(/(.{2})/g,"$1 ").trim(),this.length>k&&(d+=" ... "),"<Buffer "+d+">"},t&&(o.prototype[t]=o.prototype.inspect),o.prototype.compare=function(d,k,A,B,X){if(H(d,Uint8Array)&&(d=o.from(d,d.offset,d.byteLength)),!o.isBuffer(d))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof d);if(k===void 0&&(k=0),A===void 0&&(A=d?d.length:0),B===void 0&&(B=0),X===void 0&&(X=this.length),k<0||A>d.length||B<0||X>this.length)throw new RangeError("out of range index");if(B>=X&&k>=A)return 0;if(B>=X)return-1;if(k>=A)return 1;if(k>>>=0,A>>>=0,B>>>=0,X>>>=0,this===d)return 0;let he=X-B,ke=A-k,z=Math.min(he,ke),ie=this.slice(B,X),Ee=d.slice(k,A);for(let Ae=0;Ae<z;++Ae)if(ie[Ae]!==Ee[Ae]){he=ie[Ae],ke=Ee[Ae];break}return he<ke?-1:ke<he?1:0};function v(d,k,A,B,X){if(d.length===0)return-1;if(typeof A=="string"?(B=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,me(A)&&(A=X?0:d.length-1),A<0&&(A=d.length+A),A>=d.length){if(X)return-1;A=d.length-1}else if(A<0)if(X)A=0;else return-1;if(typeof k=="string"&&(k=o.from(k,B)),o.isBuffer(k))return k.length===0?-1:E(d,k,A,B,X);if(typeof k=="number")return k=k&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(d,k,A):Uint8Array.prototype.lastIndexOf.call(d,k,A):E(d,[k],A,B,X);throw new TypeError("val must be string, number or Buffer")}function E(d,k,A,B,X){let he=1,ke=d.length,z=k.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(d.length<2||k.length<2)return-1;he=2,ke/=2,z/=2,A/=2}function ie(Ae,Ie){return he===1?Ae[Ie]:Ae.readUInt16BE(Ie*he)}let Ee;if(X){let Ae=-1;for(Ee=A;Ee<ke;Ee++)if(ie(d,Ee)===ie(k,Ae===-1?0:Ee-Ae)){if(Ae===-1&&(Ae=Ee),Ee-Ae+1===z)return Ae*he}else Ae!==-1&&(Ee-=Ee-Ae),Ae=-1}else for(A+z>ke&&(A=ke-z),Ee=A;Ee>=0;Ee--){let Ae=!0;for(let Ie=0;Ie<z;Ie++)if(ie(d,Ee+Ie)!==ie(k,Ie)){Ae=!1;break}if(Ae)return Ee}return-1}o.prototype.includes=function(d,k,A){return this.indexOf(d,k,A)!==-1},o.prototype.indexOf=function(d,k,A){return v(this,d,k,A,!0)},o.prototype.lastIndexOf=function(d,k,A){return v(this,d,k,A,!1)};function S(d,k,A,B){A=Number(A)||0;let X=d.length-A;B?(B=Number(B),B>X&&(B=X)):B=X;let he=k.length;B>he/2&&(B=he/2);let ke;for(ke=0;ke<B;++ke){let z=parseInt(k.substr(ke*2,2),16);if(me(z))return ke;d[A+ke]=z}return ke}function I(d,k,A,B){return ye($(k,d.length-A),d,A,B)}function O(d,k,A,B){return ye(ee(k),d,A,B)}function P(d,k,A,B){return ye(fe(k),d,A,B)}function N(d,k,A,B){return ye(de(k,d.length-A),d,A,B)}o.prototype.write=function(d,k,A,B){if(k===void 0)B="utf8",A=this.length,k=0;else if(A===void 0&&typeof k=="string")B=k,A=this.length,k=0;else if(isFinite(k))k=k>>>0,isFinite(A)?(A=A>>>0,B===void 0&&(B="utf8")):(B=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let X=this.length-k;if((A===void 0||A>X)&&(A=X),d.length>0&&(A<0||k<0)||k>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let he=!1;for(;;)switch(B){case"hex":return S(this,d,k,A);case"utf8":case"utf-8":return I(this,d,k,A);case"ascii":case"latin1":case"binary":return O(this,d,k,A);case"base64":return P(this,d,k,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,d,k,A);default:if(he)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),he=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(d,k,A){return k===0&&A===d.length?a.fromByteArray(d):a.fromByteArray(d.slice(k,A))}function q(d,k,A){A=Math.min(d.length,A);let B=[],X=k;for(;X<A;){let he=d[X],ke=null,z=he>239?4:he>223?3:he>191?2:1;if(X+z<=A){let ie,Ee,Ae,Ie;switch(z){case 1:he<128&&(ke=he);break;case 2:ie=d[X+1],(ie&192)===128&&(Ie=(he&31)<<6|ie&63,Ie>127&&(ke=Ie));break;case 3:ie=d[X+1],Ee=d[X+2],(ie&192)===128&&(Ee&192)===128&&(Ie=(he&15)<<12|(ie&63)<<6|Ee&63,Ie>2047&&(Ie<55296||Ie>57343)&&(ke=Ie));break;case 4:ie=d[X+1],Ee=d[X+2],Ae=d[X+3],(ie&192)===128&&(Ee&192)===128&&(Ae&192)===128&&(Ie=(he&15)<<18|(ie&63)<<12|(Ee&63)<<6|Ae&63,Ie>65535&&Ie<1114112&&(ke=Ie))}}ke===null?(ke=65533,z=1):ke>65535&&(ke-=65536,B.push(ke>>>10&1023|55296),ke=56320|ke&1023),B.push(ke),X+=z}return U(B)}let D=4096;function U(d){let k=d.length;if(k<=D)return String.fromCharCode.apply(String,d);let A="",B=0;for(;B<k;)A+=String.fromCharCode.apply(String,d.slice(B,B+=D));return A}function ae(d,k,A){let B="";A=Math.min(d.length,A);for(let X=k;X<A;++X)B+=String.fromCharCode(d[X]&127);return B}function Y(d,k,A){let B="";A=Math.min(d.length,A);for(let X=k;X<A;++X)B+=String.fromCharCode(d[X]);return B}function V(d,k,A){let B=d.length;(!k||k<0)&&(k=0),(!A||A<0||A>B)&&(A=B);let X="";for(let he=k;he<A;++he)X+=ve[d[he]];return X}function re(d,k,A){let B=d.slice(k,A),X="";for(let he=0;he<B.length-1;he+=2)X+=String.fromCharCode(B[he]+B[he+1]*256);return X}o.prototype.slice=function(d,k){let A=this.length;d=~~d,k=k===void 0?A:~~k,d<0?(d+=A,d<0&&(d=0)):d>A&&(d=A),k<0?(k+=A,k<0&&(k=0)):k>A&&(k=A),k<d&&(k=d);let B=this.subarray(d,k);return Object.setPrototypeOf(B,o.prototype),B};function F(d,k,A){if(d%1!==0||d<0)throw new RangeError("offset is not uint");if(d+k>A)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(d,k,A){d=d>>>0,k=k>>>0,A||F(d,k,this.length);let B=this[d],X=1,he=0;for(;++he<k&&(X*=256);)B+=this[d+he]*X;return B},o.prototype.readUintBE=o.prototype.readUIntBE=function(d,k,A){d=d>>>0,k=k>>>0,A||F(d,k,this.length);let B=this[d+--k],X=1;for(;k>0&&(X*=256);)B+=this[d+--k]*X;return B},o.prototype.readUint8=o.prototype.readUInt8=function(d,k){return d=d>>>0,k||F(d,1,this.length),this[d]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(d,k){return d=d>>>0,k||F(d,2,this.length),this[d]|this[d+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(d,k){return d=d>>>0,k||F(d,2,this.length),this[d]<<8|this[d+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(d,k){return d=d>>>0,k||F(d,4,this.length),(this[d]|this[d+1]<<8|this[d+2]<<16)+this[d+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(d,k){return d=d>>>0,k||F(d,4,this.length),this[d]*16777216+(this[d+1]<<16|this[d+2]<<8|this[d+3])},o.prototype.readBigUInt64LE=se(function(d){d=d>>>0,Q(d,"offset");let k=this[d],A=this[d+7];(k===void 0||A===void 0)&&ge(d,this.length-8);let B=k+this[++d]*2**8+this[++d]*2**16+this[++d]*2**24,X=this[++d]+this[++d]*2**8+this[++d]*2**16+A*2**24;return BigInt(B)+(BigInt(X)<<BigInt(32))}),o.prototype.readBigUInt64BE=se(function(d){d=d>>>0,Q(d,"offset");let k=this[d],A=this[d+7];(k===void 0||A===void 0)&&ge(d,this.length-8);let B=k*2**24+this[++d]*2**16+this[++d]*2**8+this[++d],X=this[++d]*2**24+this[++d]*2**16+this[++d]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(X)}),o.prototype.readIntLE=function(d,k,A){d=d>>>0,k=k>>>0,A||F(d,k,this.length);let B=this[d],X=1,he=0;for(;++he<k&&(X*=256);)B+=this[d+he]*X;return X*=128,B>=X&&(B-=Math.pow(2,8*k)),B},o.prototype.readIntBE=function(d,k,A){d=d>>>0,k=k>>>0,A||F(d,k,this.length);let B=k,X=1,he=this[d+--B];for(;B>0&&(X*=256);)he+=this[d+--B]*X;return X*=128,he>=X&&(he-=Math.pow(2,8*k)),he},o.prototype.readInt8=function(d,k){return d=d>>>0,k||F(d,1,this.length),this[d]&128?(255-this[d]+1)*-1:this[d]},o.prototype.readInt16LE=function(d,k){d=d>>>0,k||F(d,2,this.length);let A=this[d]|this[d+1]<<8;return A&32768?A|4294901760:A},o.prototype.readInt16BE=function(d,k){d=d>>>0,k||F(d,2,this.length);let A=this[d+1]|this[d]<<8;return A&32768?A|4294901760:A},o.prototype.readInt32LE=function(d,k){return d=d>>>0,k||F(d,4,this.length),this[d]|this[d+1]<<8|this[d+2]<<16|this[d+3]<<24},o.prototype.readInt32BE=function(d,k){return d=d>>>0,k||F(d,4,this.length),this[d]<<24|this[d+1]<<16|this[d+2]<<8|this[d+3]},o.prototype.readBigInt64LE=se(function(d){d=d>>>0,Q(d,"offset");let k=this[d],A=this[d+7];(k===void 0||A===void 0)&&ge(d,this.length-8);let B=this[d+4]+this[d+5]*2**8+this[d+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(k+this[++d]*2**8+this[++d]*2**16+this[++d]*2**24)}),o.prototype.readBigInt64BE=se(function(d){d=d>>>0,Q(d,"offset");let k=this[d],A=this[d+7];(k===void 0||A===void 0)&&ge(d,this.length-8);let B=(k<<24)+this[++d]*2**16+this[++d]*2**8+this[++d];return(BigInt(B)<<BigInt(32))+BigInt(this[++d]*2**24+this[++d]*2**16+this[++d]*2**8+A)}),o.prototype.readFloatLE=function(d,k){return d=d>>>0,k||F(d,4,this.length),e.read(this,d,!0,23,4)},o.prototype.readFloatBE=function(d,k){return d=d>>>0,k||F(d,4,this.length),e.read(this,d,!1,23,4)},o.prototype.readDoubleLE=function(d,k){return d=d>>>0,k||F(d,8,this.length),e.read(this,d,!0,52,8)},o.prototype.readDoubleBE=function(d,k){return d=d>>>0,k||F(d,8,this.length),e.read(this,d,!1,52,8)};function Z(d,k,A,B,X,he){if(!o.isBuffer(d))throw new TypeError('"buffer" argument must be a Buffer instance');if(k>X||k<he)throw new RangeError('"value" argument is out of bounds');if(A+B>d.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(d,k,A,B){if(d=+d,k=k>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,d,k,A,ke,0)}let X=1,he=0;for(this[k]=d&255;++he<A&&(X*=256);)this[k+he]=d/X&255;return k+A},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(d,k,A,B){if(d=+d,k=k>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,d,k,A,ke,0)}let X=A-1,he=1;for(this[k+X]=d&255;--X>=0&&(he*=256);)this[k+X]=d/he&255;return k+A},o.prototype.writeUint8=o.prototype.writeUInt8=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,1,255,0),this[k]=d&255,k+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,2,65535,0),this[k]=d&255,this[k+1]=d>>>8,k+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,2,65535,0),this[k]=d>>>8,this[k+1]=d&255,k+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,4,4294967295,0),this[k+3]=d>>>24,this[k+2]=d>>>16,this[k+1]=d>>>8,this[k]=d&255,k+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,4,4294967295,0),this[k]=d>>>24,this[k+1]=d>>>16,this[k+2]=d>>>8,this[k+3]=d&255,k+4};function M(d,k,A,B,X){K(k,B,X,d,A,7);let he=Number(k&BigInt(4294967295));d[A++]=he,he=he>>8,d[A++]=he,he=he>>8,d[A++]=he,he=he>>8,d[A++]=he;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return d[A++]=ke,ke=ke>>8,d[A++]=ke,ke=ke>>8,d[A++]=ke,ke=ke>>8,d[A++]=ke,A}function J(d,k,A,B,X){K(k,B,X,d,A,7);let he=Number(k&BigInt(4294967295));d[A+7]=he,he=he>>8,d[A+6]=he,he=he>>8,d[A+5]=he,he=he>>8,d[A+4]=he;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return d[A+3]=ke,ke=ke>>8,d[A+2]=ke,ke=ke>>8,d[A+1]=ke,ke=ke>>8,d[A]=ke,A+8}o.prototype.writeBigUInt64LE=se(function(d,k=0){return M(this,d,k,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=se(function(d,k=0){return J(this,d,k,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(d,k,A,B){if(d=+d,k=k>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,d,k,A,z-1,-z)}let X=0,he=1,ke=0;for(this[k]=d&255;++X<A&&(he*=256);)d<0&&ke===0&&this[k+X-1]!==0&&(ke=1),this[k+X]=(d/he>>0)-ke&255;return k+A},o.prototype.writeIntBE=function(d,k,A,B){if(d=+d,k=k>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,d,k,A,z-1,-z)}let X=A-1,he=1,ke=0;for(this[k+X]=d&255;--X>=0&&(he*=256);)d<0&&ke===0&&this[k+X+1]!==0&&(ke=1),this[k+X]=(d/he>>0)-ke&255;return k+A},o.prototype.writeInt8=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,1,127,-128),d<0&&(d=255+d+1),this[k]=d&255,k+1},o.prototype.writeInt16LE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,2,32767,-32768),this[k]=d&255,this[k+1]=d>>>8,k+2},o.prototype.writeInt16BE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,2,32767,-32768),this[k]=d>>>8,this[k+1]=d&255,k+2},o.prototype.writeInt32LE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,4,2147483647,-2147483648),this[k]=d&255,this[k+1]=d>>>8,this[k+2]=d>>>16,this[k+3]=d>>>24,k+4},o.prototype.writeInt32BE=function(d,k,A){return d=+d,k=k>>>0,A||Z(this,d,k,4,2147483647,-2147483648),d<0&&(d=4294967295+d+1),this[k]=d>>>24,this[k+1]=d>>>16,this[k+2]=d>>>8,this[k+3]=d&255,k+4},o.prototype.writeBigInt64LE=se(function(d,k=0){return M(this,d,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=se(function(d,k=0){return J(this,d,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(d,k,A,B,X,he){if(A+B>d.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(d,k,A,B,X){return k=+k,A=A>>>0,X||be(d,k,A,4),e.write(d,k,A,B,23,4),A+4}o.prototype.writeFloatLE=function(d,k,A){return te(this,d,k,!0,A)},o.prototype.writeFloatBE=function(d,k,A){return te(this,d,k,!1,A)};function we(d,k,A,B,X){return k=+k,A=A>>>0,X||be(d,k,A,8),e.write(d,k,A,B,52,8),A+8}o.prototype.writeDoubleLE=function(d,k,A){return we(this,d,k,!0,A)},o.prototype.writeDoubleBE=function(d,k,A){return we(this,d,k,!1,A)},o.prototype.copy=function(d,k,A,B){if(!o.isBuffer(d))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),k>=d.length&&(k=d.length),k||(k=0),B>0&&B<A&&(B=A),B===A||d.length===0||this.length===0)return 0;if(k<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),d.length-k<B-A&&(B=d.length-k+A);let X=B-A;return this===d&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(k,A,B):Uint8Array.prototype.set.call(d,this.subarray(A,B),k),X},o.prototype.fill=function(d,k,A,B){if(typeof d=="string"){if(typeof k=="string"?(B=k,k=0,A=this.length):typeof A=="string"&&(B=A,A=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!o.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(d.length===1){let he=d.charCodeAt(0);(B==="utf8"&&he<128||B==="latin1")&&(d=he)}}else typeof d=="number"?d=d&255:typeof d=="boolean"&&(d=Number(d));if(k<0||this.length<k||this.length<A)throw new RangeError("Out of range index");if(A<=k)return this;k=k>>>0,A=A===void 0?this.length:A>>>0,d||(d=0);let X;if(typeof d=="number")for(X=k;X<A;++X)this[X]=d;else{let he=o.isBuffer(d)?d:o.from(d,B),ke=he.length;if(ke===0)throw new TypeError('The value "'+d+'" is invalid for argument "value"');for(X=0;X<A-k;++X)this[X+k]=he[X%ke]}return this};let G={};function j(d,k,A){G[d]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:k.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${d}]`,this.stack,delete this.name}get code(){return d}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${d}]: ${this.message}`}}}j("ERR_BUFFER_OUT_OF_BOUNDS",function(d){return d?`${d} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(d,k){return`The "${d}" argument must be of type number. Received type ${typeof k}`},TypeError),j("ERR_OUT_OF_RANGE",function(d,k,A){let B=`The value of "${d}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>2**32?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),B+=` It must be ${k}. Received ${X}`,B},RangeError);function ne(d){let k="",A=d.length,B=d[0]==="-"?1:0;for(;A>=B+4;A-=3)k=`_${d.slice(A-3,A)}${k}`;return`${d.slice(0,A)}${k}`}function W(d,k,A){Q(k,"offset"),(d[k]===void 0||d[k+A]===void 0)&&ge(k,d.length-(A+1))}function K(d,k,A,B,X,he){if(d>A||d<k){let ke=typeof k=="bigint"?"n":"",z;throw k===0||k===BigInt(0)?z=`>= 0${ke} and < 2${ke} ** ${(he+1)*8}${ke}`:z=`>= -(2${ke} ** ${(he+1)*8-1}${ke}) and < 2 ** ${(he+1)*8-1}${ke}`,new G.ERR_OUT_OF_RANGE("value",z,d)}W(B,X,he)}function Q(d,k){if(typeof d!="number")throw new G.ERR_INVALID_ARG_TYPE(k,"number",d)}function ge(d,k,A){throw Math.floor(d)!==d?(Q(d,A),new G.ERR_OUT_OF_RANGE("offset","an integer",d)):k<0?new G.ERR_BUFFER_OUT_OF_BOUNDS:new G.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${k}`,d)}let oe=/[^+/0-9A-Za-z-_]/g;function R(d){if(d=d.split("=")[0],d=d.trim().replace(oe,""),d.length<2)return"";for(;d.length%4!==0;)d=d+"=";return d}function $(d,k){k=k||1/0;let A,B=d.length,X=null,he=[];for(let ke=0;ke<B;++ke){if(A=d.charCodeAt(ke),A>55295&&A<57344){if(!X){if(A>56319){(k-=3)>-1&&he.push(239,191,189);continue}else if(ke+1===B){(k-=3)>-1&&he.push(239,191,189);continue}X=A;continue}if(A<56320){(k-=3)>-1&&he.push(239,191,189),X=A;continue}A=(X-55296<<10|A-56320)+65536}else X&&(k-=3)>-1&&he.push(239,191,189);if(X=null,A<128){if((k-=1)<0)break;he.push(A)}else if(A<2048){if((k-=2)<0)break;he.push(A>>6|192,A&63|128)}else if(A<65536){if((k-=3)<0)break;he.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((k-=4)<0)break;he.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return he}function ee(d){let k=[];for(let A=0;A<d.length;++A)k.push(d.charCodeAt(A)&255);return k}function de(d,k){let A,B,X,he=[];for(let ke=0;ke<d.length&&!((k-=2)<0);++ke)A=d.charCodeAt(ke),B=A>>8,X=A%256,he.push(X),he.push(B);return he}function fe(d){return a.toByteArray(R(d))}function ye(d,k,A,B){let X;for(X=0;X<B&&!(X+A>=k.length||X>=d.length);++X)k[X+A]=d[X];return X}function H(d,k){return d instanceof k||d!=null&&d.constructor!=null&&d.constructor.name!=null&&d.constructor.name===k.name}function me(d){return d!==d}let ve=(function(){let d="0123456789abcdef",k=new Array(256);for(let A=0;A<16;++A){let B=A*16;for(let X=0;X<16;++X)k[B+X]=d[A]+d[X]}return k})();function se(d){return typeof BigInt>"u"?Te:d}function Te(){throw new Error("BigInt not supported")}return bt}var Lt,si,Kt,ai,bt,li,Uc=Ve(()=>{le(),ue(),ce(),Lt={},si=!1,Kt={},ai=!1,bt={},li=!1}),Ue={};Dt(Ue,{Buffer:()=>Nr,INSPECT_MAX_BYTES:()=>aa,default:()=>at,kMaxLength:()=>la});var at,Nr,aa,la,Be=Ve(()=>{le(),ue(),ce(),Uc(),at=Nc(),at.Buffer,at.SlowBuffer,at.INSPECT_MAX_BYTES,at.kMaxLength,Nr=at.Buffer,aa=at.INSPECT_MAX_BYTES,la=at.kMaxLength}),ue=Ve(()=>{Be()}),je=pe((a,e)=>{le(),ue(),ce();var t=class extends Error{constructor(r){if(!Array.isArray(r))throw new TypeError(`Expected input to be an Array, got ${typeof r}`);let i="";for(let n=0;n<r.length;n++)i+=` ${r[n].stack}
2
+ `;super(i),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,i){return r.includes(i)},ArrayPrototypeIndexOf(r,i){return r.indexOf(i)},ArrayPrototypeJoin(r,i){return r.join(i)},ArrayPrototypeMap(r,i){return r.map(i)},ArrayPrototypePop(r,i){return r.pop(i)},ArrayPrototypePush(r,i){return r.push(i)},ArrayPrototypeSlice(r,i,n){return r.slice(i,n)},Error,FunctionPrototypeCall(r,i,...n){return r.call(i,...n)},FunctionPrototypeSymbolHasInstance(r,i){return Function.prototype[Symbol.hasInstance].call(r,i)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(r,i){return Object.defineProperties(r,i)},ObjectDefineProperty(r,i,n){return Object.defineProperty(r,i,n)},ObjectGetOwnPropertyDescriptor(r,i){return Object.getOwnPropertyDescriptor(r,i)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,i){return Object.setPrototypeOf(r,i)},Promise,PromisePrototypeCatch(r,i){return r.catch(i)},PromisePrototypeThen(r,i,n){return r.then(i,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,i){return r.test(i)},SafeSet:Set,String,StringPrototypeSlice(r,i,n){return r.slice(i,n)},StringPrototypeToLowerCase(r){return r.toLowerCase()},StringPrototypeToUpperCase(r){return r.toUpperCase()},StringPrototypeTrim(r){return r.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(r,i,n){return r.set(i,n)},Boolean,Uint8Array}}),ca=pe((a,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[i,n]){let o=r.shift();return n==="f"?o.toFixed(6):n==="j"?JSON.stringify(o):n==="s"&&typeof o=="object"?`${o.constructor!==Object?o.constructor.name:""} {}`.trim():o.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}}}}),We=pe((a,e)=>{le(),ue(),ce();var{format:t,inspect:r}=ca(),{AggregateError:i}=je(),n=globalThis.AggregateError||i,o=Symbol("kIsNodeError"),s=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function h(m,_){if(!m)throw new u.ERR_INTERNAL_ASSERTION(_)}function p(m){let _="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)_=`_${m.slice(x-3,x)}${_}`;return`${m.slice(0,x)}${_}`}function b(m,_,x){if(typeof _=="function")return h(_.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${_.length}).`),_(...x);let v=(_.match(/%[dfijoOs]/g)||[]).length;return h(v===x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${v}).`),x.length===0?_:t(_,...x)}function f(m,_,x){x||(x=Error);class v extends x{constructor(...S){super(b(m,_,S))}toString(){return`${this.name} [${m}]: ${this.message}`}}Object.defineProperties(v.prototype,{name:{value:x.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${m}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),v.prototype.code=m,v.prototype[o]=!0,u[m]=v}function g(m){let _=c+m.name;return Object.defineProperty(m,"name",{value:_}),m}function y(m,_){if(m&&_&&m!==_){if(Array.isArray(_.errors))return _.errors.push(m),_;let x=new n([_,m],_.message);return x.code=_.code,x}return m||_}var w=class extends Error{constructor(m="The operation was aborted",_=void 0){if(_!==void 0&&typeof _!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",_);super(m,_),this.code="ABORT_ERR",this.name="AbortError"}};f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(m,_,x)=>{h(typeof m=="string","'name' must be a string"),Array.isArray(_)||(_=[_]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let E=[],S=[],I=[];for(let P of _)h(typeof P=="string","All expected entries have to be of type string"),s.includes(P)?E.push(P.toLowerCase()):l.test(P)?S.push(P):(h(P!=="object",'The value "object" should be written as "Object"'),I.push(P));if(S.length>0){let P=E.indexOf("object");P!==-1&&(E.splice(E,P,1),S.push("Object"))}if(E.length>0){switch(E.length){case 1:v+=`of type ${E[0]}`;break;case 2:v+=`one of type ${E[0]} or ${E[1]}`;break;default:{let P=E.pop();v+=`one of type ${E.join(", ")}, or ${P}`}}(S.length>0||I.length>0)&&(v+=" or ")}if(S.length>0){switch(S.length){case 1:v+=`an instance of ${S[0]}`;break;case 2:v+=`an instance of ${S[0]} or ${S[1]}`;break;default:{let P=S.pop();v+=`an instance of ${S.join(", ")}, or ${P}`}}I.length>0&&(v+=" or ")}switch(I.length){case 0:break;case 1:I[0].toLowerCase()!==I[0]&&(v+="an "),v+=`${I[0]}`;break;case 2:v+=`one of ${I[0]} or ${I[1]}`;break;default:{let P=I.pop();v+=`one of ${I.join(", ")}, or ${P}`}}if(x==null)v+=`. Received ${x}`;else if(typeof x=="function"&&x.name)v+=`. Received function ${x.name}`;else if(typeof x=="object"){var O;if((O=x.constructor)!==null&&O!==void 0&&O.name)v+=`. Received an instance of ${x.constructor.name}`;else{let P=r(x,{depth:-1});v+=`. Received ${P}`}}else{let P=r(x,{colors:!1});P.length>25&&(P=`${P.slice(0,25)}...`),v+=`. Received type ${typeof x} (${P})`}return v},TypeError),f("ERR_INVALID_ARG_VALUE",(m,_,x="is invalid")=>{let v=r(_);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${x}. Received ${v}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(m,_,x)=>{var v;let E=x!=null&&(v=x.constructor)!==null&&v!==void 0&&v.name?`instance of ${x.constructor.name}`:`type ${typeof x}`;return`Expected ${m} to be returned from the "${_}" function but got ${E}.`},TypeError),f("ERR_MISSING_ARGS",(...m)=>{h(m.length>0,"At least one arg needs to be specified");let _,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:_+=`The ${m[0]} argument`;break;case 2:_+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();_+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${_} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(m,_,x)=>{h(_,'Missing "range" argument');let v;if(Number.isInteger(x)&&Math.abs(x)>2**32)v=p(String(x));else if(typeof x=="bigint"){v=String(x);let E=BigInt(2)**BigInt(32);(x>E||x<-E)&&(v=p(v)),v+="n"}else v=r(x);return`The value of "${m}" is out of range. It must be ${_}. Received ${v}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:g(y),hideStackFrames:g,codes:u}}),er=pe((a,e)=>{le(),ue(),ce();var{AbortController:t,AbortSignal:r}=typeof self<"u"?self:typeof window<"u"?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t}),wt={};Dt(wt,{EventEmitter:()=>ua,default:()=>jt,defaultMaxListeners:()=>ha,init:()=>da,listenerCount:()=>fa,on:()=>pa,once:()=>ma});function Bc(){if(ci)return Yt;ci=!0;var a=typeof Reflect=="object"?Reflect:null,e=a&&typeof a.apply=="function"?a.apply:function(x,v,E){return Function.prototype.apply.call(x,v,E)},t;a&&typeof a.ownKeys=="function"?t=a.ownKeys:Object.getOwnPropertySymbols?t=function(x){return Object.getOwnPropertyNames(x).concat(Object.getOwnPropertySymbols(x))}:t=function(x){return Object.getOwnPropertyNames(x)};function r(x){console&&console.warn&&console.warn(x)}var i=Number.isNaN||function(x){return x!==x};function n(){n.init.call(this)}Yt=n,Yt.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var o=10;function s(x){if(typeof x!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof x)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(x){if(typeof x!="number"||x<0||i(x))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+x+".");o=x}}),n.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(x){if(typeof x!="number"||x<0||i(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function l(x){return x._maxListeners===void 0?n.defaultMaxListeners:x._maxListeners}n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(x){for(var v=[],E=1;E<arguments.length;E++)v.push(arguments[E]);var S=x==="error",I=this._events;if(I!==void 0)S=S&&I.error===void 0;else if(!S)return!1;if(S){var O;if(v.length>0&&(O=v[0]),O instanceof Error)throw O;var P=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw P.context=O,P}var N=I[x];if(N===void 0)return!1;if(typeof N=="function")e(N,this,v);else for(var T=N.length,q=f(N,T),E=0;E<T;++E)e(q[E],this,v);return!0};function c(x,v,E,S){var I,O,P;if(s(E),O=x._events,O===void 0?(O=x._events=Object.create(null),x._eventsCount=0):(O.newListener!==void 0&&(x.emit("newListener",v,E.listener?E.listener:E),O=x._events),P=O[v]),P===void 0)P=O[v]=E,++x._eventsCount;else if(typeof P=="function"?P=O[v]=S?[E,P]:[P,E]:S?P.unshift(E):P.push(E),I=l(x),I>0&&P.length>I&&!P.warned){P.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+P.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=x,N.type=v,N.count=P.length,r(N)}return x}n.prototype.addListener=function(x,v){return c(this,x,v,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(x,v){return c(this,x,v,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(x,v,E){var S={fired:!1,wrapFn:void 0,target:x,type:v,listener:E},I=u.bind(S);return I.listener=E,S.wrapFn=I,I}n.prototype.once=function(x,v){return s(v),this.on(x,h(this,x,v)),this},n.prototype.prependOnceListener=function(x,v){return s(v),this.prependListener(x,h(this,x,v)),this},n.prototype.removeListener=function(x,v){var E,S,I,O,P;if(s(v),S=this._events,S===void 0)return this;if(E=S[x],E===void 0)return this;if(E===v||E.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete S[x],S.removeListener&&this.emit("removeListener",x,E.listener||v));else if(typeof E!="function"){for(I=-1,O=E.length-1;O>=0;O--)if(E[O]===v||E[O].listener===v){P=E[O].listener,I=O;break}if(I<0)return this;I===0?E.shift():g(E,I),E.length===1&&(S[x]=E[0]),S.removeListener!==void 0&&this.emit("removeListener",x,P||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(x){var v,E,S;if(E=this._events,E===void 0)return this;if(E.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):E[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete E[x]),this;if(arguments.length===0){var I=Object.keys(E),O;for(S=0;S<I.length;++S)O=I[S],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=E[x],typeof v=="function")this.removeListener(x,v);else if(v!==void 0)for(S=v.length-1;S>=0;S--)this.removeListener(x,v[S]);return this};function p(x,v,E){var S=x._events;if(S===void 0)return[];var I=S[v];return I===void 0?[]:typeof I=="function"?E?[I.listener||I]:[I]:E?y(I):f(I,I.length)}n.prototype.listeners=function(x){return p(this,x,!0)},n.prototype.rawListeners=function(x){return p(this,x,!1)},n.listenerCount=function(x,v){return typeof x.listenerCount=="function"?x.listenerCount(v):b.call(x,v)},n.prototype.listenerCount=b;function b(x){var v=this._events;if(v!==void 0){var E=v[x];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(x,v){for(var E=new Array(v),S=0;S<v;++S)E[S]=x[S];return E}function g(x,v){for(;v+1<x.length;v++)x[v]=x[v+1];x.pop()}function y(x){for(var v=new Array(x.length),E=0;E<v.length;++E)v[E]=x[E].listener||x[E];return v}function w(x,v){return new Promise(function(E,S){function I(P){x.removeListener(v,O),S(P)}function O(){typeof x.removeListener=="function"&&x.removeListener("error",I),E([].slice.call(arguments))}_(x,v,O,{once:!0}),v!=="error"&&m(x,I,{once:!0})})}function m(x,v,E){typeof x.on=="function"&&_(x,"error",v,E)}function _(x,v,E,S){if(typeof x.on=="function")S.once?x.once(v,E):x.on(v,E);else if(typeof x.addEventListener=="function")x.addEventListener(v,function I(O){S.once&&x.removeEventListener(v,I),E(O)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return Yt}var Yt,ci,jt,ua,ha,da,fa,pa,ma,Ct=Ve(()=>{le(),ue(),ce(),Yt={},ci=!1,jt=Bc(),jt.once,jt.once=function(a,e){return new Promise((t,r)=>{function i(...o){n!==void 0&&a.removeListener("error",n),t(o)}let n;e!=="error"&&(n=o=>{a.removeListener(name,i),r(o)},a.once("error",n)),a.once(e,i)})},jt.on=function(a,e){let t=[],r=[],i=null,n=!1,o={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(i){let u=Promise.reject(i);return i=null,u}return n?createIterResult(void 0,!0):new Promise((u,h)=>r.push({resolve:u,reject:h}))},async return(){a.removeListener(e,s),a.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){i=c,a.removeListener(e,s),a.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return a.on(e,s),a.on("error",l),o;function s(...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):i=c,o.return()}},{EventEmitter:ua,defaultMaxListeners:ha,init:da,listenerCount:fa,on:pa,once:ma}=jt}),ze=pe((a,e)=>{le(),ue(),ce();var t=(Be(),Pe(Ue)),{format:r,inspect:i}=ca(),{codes:{ERR_INVALID_ARG_TYPE:n}}=We(),{kResistStopPropagation:o,AggregateError:s,SymbolDispose:l}=je(),c=globalThis.AbortSignal||er().AbortSignal,u=globalThis.AbortController||er().AbortController,h=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,b=typeof p<"u"?function(y){return y instanceof p}:function(y){return!1},f=(y,w)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new n(w,"AbortSignal",y)},g=(y,w)=>{if(typeof y!="function")throw new n(w,"Function",y)};e.exports={AggregateError:s,kEmptyObject:Object.freeze({}),once(y){let w=!1;return function(...m){w||(w=!0,y.apply(this,m))}},createDeferredPromise:function(){let y,w;return{promise:new Promise((m,_)=>{y=m,w=_}),resolve:y,reject:w}},promisify(y){return new Promise((w,m)=>{y((_,...x)=>_?m(_):w(...x))})},debuglog(){return function(){}},format:r,inspect:i,types:{isAsyncFunction(y){return y instanceof h},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:b,deprecate(y,w){return y},addAbortListener:(Ct(),Pe(wt)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);f(y,"signal"),g(w,"listener");let m;return y.aborted?queueMicrotask(()=>w()):(y.addEventListener("abort",w,{__proto__:null,once:!0,[o]:!0}),m=()=>{y.removeEventListener("abort",w)}),{__proto__:null,[l](){var _;(_=m)===null||_===void 0||_()}}},AbortSignalAny:c.any||function(y){if(y.length===1)return y[0];let w=new u,m=()=>w.abort();return y.forEach(_=>{f(_,"signals"),_.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{y.forEach(_=>_.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),tr=pe((a,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:i,ArrayPrototypeMap:n,NumberIsInteger:o,NumberIsNaN:s,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:h,RegExpPrototypeExec:p,String:b,StringPrototypeToUpperCase:f,StringPrototypeTrim:g}=je(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:_,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=We(),{normalizeEncoding:E}=ze(),{isAsyncFunction:S,isArrayBufferView:I}=ze().types,O={};function P(H){return H===(H|0)}function N(H){return H===H>>>0}var T=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function D(H,me,ve){if(typeof H>"u"&&(H=ve),typeof H=="string"){if(p(T,H)===null)throw new _(me,H,q);H=u(H,8)}return Y(H,me),H}var U=y((H,me,ve=c,se=l)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),ae=y((H,me,ve=-2147483648,se=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),Y=y((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new x(me,"an integer",H);let se=ve?1:0,Te=4294967295;if(H<se||H>Te)throw new x(me,`>= ${se} && <= ${Te}`,H)});function V(H,me){if(typeof H!="string")throw new m(me,"string",H)}function re(H,me,ve=void 0,se){if(typeof H!="number")throw new m(me,"number",H);if(ve!=null&&H<ve||se!=null&&H>se||(ve!=null||se!=null)&&s(H))throw new x(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&se!=null?" && ":""}${se!=null?`<= ${se}`:""}`,H)}var F=y((H,me,ve)=>{if(!r(ve,H)){let se="must be one of: "+i(n(ve,Te=>typeof Te=="string"?`'${Te}'`:b(Te)),", ");throw new _(me,H,se)}});function Z(H,me){if(typeof H!="boolean")throw new m(me,"boolean",H)}function M(H,me,ve){return H==null||!h(H,me)?ve:H[me]}var J=y((H,me,ve=null)=>{let se=M(ve,"allowArray",!1),Te=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!se&&t(H)||typeof H!="object"&&(!Te||typeof H!="function"))throw new m(me,"Object",H)}),be=y((H,me)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(me,"a dictionary",H)}),te=y((H,me,ve=0)=>{if(!t(H))throw new m(me,"Array",H);if(H.length<ve){let se=`must be longer than ${ve}`;throw new _(me,H,se)}});function we(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)V(H[ve],`${me}[${ve}]`)}function G(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)Z(H[ve],`${me}[${ve}]`)}function j(H,me){te(H,me);for(let ve=0;ve<H.length;ve++){let se=H[ve],Te=`${me}[${ve}]`;if(se==null)throw new m(Te,"AbortSignal",se);ge(se,Te)}}function ne(H,me="signal"){if(V(H,me),O[H]===void 0)throw O[f(H)]!==void 0?new v(H+" (signals must use all capital letters)"):new v(H)}var W=y((H,me="buffer")=>{if(!I(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function K(H,me){let ve=E(me),se=H.length;if(ve==="hex"&&se%2!==0)throw new _("encoding",me,`is invalid for data of length ${se}`)}function Q(H,me="Port",ve=!0){if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&g(H).length===0||+H!==+H>>>0||H>65535||H===0&&!ve)throw new w(me,H,ve);return H|0}var ge=y((H,me)=>{if(H!==void 0&&(H===null||typeof H!="object"||!("aborted"in H)))throw new m(me,"AbortSignal",H)}),oe=y((H,me)=>{if(typeof H!="function")throw new m(me,"Function",H)}),R=y((H,me)=>{if(typeof H!="function"||S(H))throw new m(me,"Function",H)}),$=y((H,me)=>{if(H!==void 0)throw new m(me,"undefined",H)});function ee(H,me,ve){if(!r(ve,H))throw new m(me,`('${i(ve,"|")}')`,H)}var de=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!p(de,H))throw new _(me,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(H){if(typeof H=="string")return fe(H,"hints"),H;if(t(H)){let me=H.length,ve="";if(me===0)return ve;for(let se=0;se<me;se++){let Te=H[se];fe(Te,"hints"),ve+=Te,se!==me-1&&(ve+=", ")}return ve}throw new _("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:P,isUint32:N,parseFileMode:D,validateArray:te,validateStringArray:we,validateBooleanArray:G,validateAbortSignalArray:j,validateBoolean:Z,validateBuffer:W,validateDictionary:be,validateEncoding:K,validateFunction:oe,validateInt32:ae,validateInteger:U,validateNumber:re,validateObject:J,validateOneOf:F,validatePlainFunction:R,validatePort:Q,validateSignalName:ne,validateString:V,validateUint32:Y,validateUndefined:$,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:ye}}),Ot=pe((a,e)=>{le(),ue(),ce();var t=e.exports={},r,i;function n(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?r=setTimeout:r=n}catch{r=n}try{typeof clearTimeout=="function"?i=clearTimeout:i=o}catch{i=o}})();function s(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(i===clearTimeout)return clearTimeout(w);if((i===o||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(w);try{return i(w)}catch{try{return i.call(null,w)}catch{return i.call(this,w)}}}var c=[],u=!1,h,p=-1;function b(){!u||!h||(u=!1,h.length?c=h.concat(c):p=-1,c.length&&f())}function f(){if(!u){var w=s(b);u=!0;for(var m=c.length;m;){for(h=c,c=[];++p<m;)h&&h[p].run();p=-1,m=c.length}h=null,u=!1,l(w)}}t.nextTick=function(w){var m=new Array(arguments.length-1);if(arguments.length>1)for(var _=1;_<arguments.length;_++)m[_-1]=arguments[_];c.push(new g(w,m)),c.length===1&&!u&&s(f)};function g(w,m){this.fun=w,this.array=m}g.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function y(){}t.on=y,t.addListener=y,t.once=y,t.off=y,t.removeListener=y,t.removeAllListeners=y,t.emit=y,t.prependListener=y,t.prependOnceListener=y,t.listeners=function(w){return[]},t.binding=function(w){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(w){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),dt=pe((a,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:i}=je(),n=i("nodejs.stream.destroyed"),o=i("nodejs.stream.errored"),s=i("nodejs.stream.readable"),l=i("nodejs.stream.writable"),c=i("nodejs.stream.disturbed"),u=i("nodejs.webstream.isClosedPromise"),h=i("nodejs.webstream.controllerErrorFunction");function p(M,J=!1){var be;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!J||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((be=M._readableState)===null||be===void 0?void 0:be.readable)!==!1)&&(!M._writableState||M._readableState))}function b(M){var J;return!!(M&&typeof M.write=="function"&&typeof M.on=="function"&&(!M._readableState||((J=M._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function f(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function g(M){return M&&(M._readableState||M._writableState||typeof M.write=="function"&&typeof M.on=="function"||typeof M.pipe=="function"&&typeof M.on=="function")}function y(M){return!!(M&&!g(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function w(M){return!!(M&&!g(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!g(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function _(M){return y(M)||w(M)||m(M)}function x(M,J){return M==null?!1:J===!0?typeof M[t]=="function":J===!1?typeof M[r]=="function":typeof M[t]=="function"||typeof M[r]=="function"}function v(M){if(!g(M))return null;let J=M._writableState,be=M._readableState,te=J||be;return!!(M.destroyed||M[n]||te!=null&&te.destroyed)}function E(M){if(!b(M))return null;if(M.writableEnded===!0)return!0;let J=M._writableState;return J!=null&&J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function S(M,J){if(!b(M))return null;if(M.writableFinished===!0)return!0;let be=M._writableState;return be!=null&&be.errored?!1:typeof be?.finished!="boolean"?null:!!(be.finished||J===!1&&be.ended===!0&&be.length===0)}function I(M){if(!p(M))return null;if(M.readableEnded===!0)return!0;let J=M._readableState;return!J||J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function O(M,J){if(!p(M))return null;let be=M._readableState;return be!=null&&be.errored?!1:typeof be?.endEmitted!="boolean"?null:!!(be.endEmitted||J===!1&&be.ended===!0&&be.length===0)}function P(M){return M&&M[s]!=null?M[s]:typeof M?.readable!="boolean"?null:v(M)?!1:p(M)&&M.readable&&!O(M)}function N(M){return M&&M[l]!=null?M[l]:typeof M?.writable!="boolean"?null:v(M)?!1:b(M)&&M.writable&&!E(M)}function T(M,J){return g(M)?v(M)?!0:!(J?.readable!==!1&&P(M)||J?.writable!==!1&&N(M)):null}function q(M){var J,be;return g(M)?M.writableErrored?M.writableErrored:(J=(be=M._writableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function D(M){var J,be;return g(M)?M.readableErrored?M.readableErrored:(J=(be=M._readableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function U(M){if(!g(M))return null;if(typeof M.closed=="boolean")return M.closed;let J=M._writableState,be=M._readableState;return typeof J?.closed=="boolean"||typeof be?.closed=="boolean"?J?.closed||be?.closed:typeof M._closed=="boolean"&&ae(M)?M._closed:null}function ae(M){return typeof M._closed=="boolean"&&typeof M._defaultKeepAlive=="boolean"&&typeof M._removedConnection=="boolean"&&typeof M._removedContLen=="boolean"}function Y(M){return typeof M._sent100=="boolean"&&ae(M)}function V(M){var J;return typeof M._consuming=="boolean"&&typeof M._dumped=="boolean"&&((J=M.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function re(M){if(!g(M))return null;let J=M._writableState,be=M._readableState,te=J||be;return!te&&Y(M)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function F(M){var J;return!!(M&&((J=M[c])!==null&&J!==void 0?J:M.readableDidRead||M.readableAborted))}function Z(M){var J,be,te,we,G,j,ne,W,K,Q;return!!(M&&((J=(be=(te=(we=(G=(j=M[o])!==null&&j!==void 0?j:M.readableErrored)!==null&&G!==void 0?G:M.writableErrored)!==null&&we!==void 0?we:(ne=M._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&te!==void 0?te:(W=M._writableState)===null||W===void 0?void 0:W.errorEmitted)!==null&&be!==void 0?be:(K=M._readableState)===null||K===void 0?void 0:K.errored)!==null&&J!==void 0?J:!((Q=M._writableState)===null||Q===void 0)&&Q.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:F,kIsDisturbed:c,isErrored:Z,kIsErrored:o,isReadable:P,kIsReadable:s,kIsClosedPromise:u,kControllerErrorFunction:h,kIsWritable:l,isClosed:U,isDuplexNodeStream:f,isFinished:T,isIterable:x,isReadableNodeStream:p,isReadableStream:y,isReadableEnded:I,isReadableFinished:O,isReadableErrored:D,isNodeStream:g,isWebStream:_,isWritable:N,isWritableNodeStream:b,isWritableStream:w,isWritableEnded:E,isWritableFinished:S,isWritableErrored:q,isServerRequest:V,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),_t=pe((a,e)=>{le(),ue(),ce();var t=Ot(),{AbortError:r,codes:i}=We(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:o}=i,{kEmptyObject:s,once:l}=ze(),{validateAbortSignal:c,validateFunction:u,validateObject:h,validateBoolean:p}=tr(),{Promise:b,PromisePrototypeThen:f,SymbolDispose:g}=je(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:_,isReadableFinished:x,isReadableErrored:v,isWritable:E,isWritableNodeStream:S,isWritableStream:I,isWritableFinished:O,isWritableErrored:P,isNodeStream:N,willEmitClose:T,kIsClosedPromise:q}=dt(),D;function U(F){return F.setHeader&&typeof F.abort=="function"}var ae=()=>{};function Y(F,Z,M){var J,be;if(arguments.length===2?(M=Z,Z=s):Z==null?Z=s:h(Z,"options"),u(M,"callback"),c(Z.signal,"options.signal"),M=l(M),_(F)||I(F))return V(F,Z,M);if(!N(F))throw new n("stream",["ReadableStream","WritableStream","Stream"],F);let te=(J=Z.readable)!==null&&J!==void 0?J:m(F),we=(be=Z.writable)!==null&&be!==void 0?be:S(F),G=F._writableState,j=F._readableState,ne=()=>{F.writable||Q()},W=T(F)&&m(F)===te&&S(F)===we,K=O(F,!1),Q=()=>{K=!0,F.destroyed&&(W=!1),!(W&&(!F.readable||te))&&(!te||ge)&&M.call(F)},ge=x(F,!1),oe=()=>{ge=!0,F.destroyed&&(W=!1),!(W&&(!F.writable||we))&&(!we||K)&&M.call(F)},R=H=>{M.call(F,H)},$=y(F),ee=()=>{$=!0;let H=P(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);if(te&&!ge&&m(F,!0)&&!x(F,!1))return M.call(F,new o);if(we&&!K&&!O(F,!1))return M.call(F,new o);M.call(F)},de=()=>{$=!0;let H=P(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);M.call(F)},fe=()=>{F.req.on("finish",Q)};U(F)?(F.on("complete",Q),W||F.on("abort",ee),F.req?fe():F.on("request",fe)):we&&!G&&(F.on("end",ne),F.on("close",ne)),!W&&typeof F.aborted=="boolean"&&F.on("aborted",ee),F.on("end",oe),F.on("finish",Q),Z.error!==!1&&F.on("error",R),F.on("close",ee),$?t.nextTick(ee):G!=null&&G.errorEmitted||j!=null&&j.errorEmitted?W||t.nextTick(de):(!te&&(!W||w(F))&&(K||E(F)===!1)||!we&&(!W||E(F))&&(ge||w(F)===!1)||j&&F.req&&F.aborted)&&t.nextTick(de);let ye=()=>{M=ae,F.removeListener("aborted",ee),F.removeListener("complete",Q),F.removeListener("abort",ee),F.removeListener("request",fe),F.req&&F.req.removeListener("finish",Q),F.removeListener("end",ne),F.removeListener("close",ne),F.removeListener("finish",Q),F.removeListener("end",oe),F.removeListener("error",R),F.removeListener("close",ee)};if(Z.signal&&!$){let H=()=>{let me=M;ye(),me.call(F,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(H);else{D=D||ze().addAbortListener;let me=D(Z.signal,H),ve=M;M=l((...se)=>{me[g](),ve.apply(F,se)})}}return ye}function V(F,Z,M){let J=!1,be=ae;if(Z.signal)if(be=()=>{J=!0,M.call(F,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(be);else{D=D||ze().addAbortListener;let we=D(Z.signal,be),G=M;M=l((...j)=>{we[g](),G.apply(F,j)})}let te=(...we)=>{J||t.nextTick(()=>M.apply(F,we))};return f(F[q].promise,te,te),ae}function re(F,Z){var M;let J=!1;return Z===null&&(Z=s),(M=Z)!==null&&M!==void 0&&M.cleanup&&(p(Z.cleanup,"cleanup"),J=Z.cleanup),new b((be,te)=>{let we=Y(F,Z,G=>{J&&we(),G?te(G):be()})})}e.exports=Y,e.exports.finished=re}),Ft=pe((a,e)=>{le(),ue(),ce();var t=Ot(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:i},AbortError:n}=We(),{Symbol:o}=je(),{kIsDestroyed:s,isDestroyed:l,isFinished:c,isServerRequest:u}=dt(),h=o("kDestroy"),p=o("kConstruct");function b(T,q,D){T&&(T.stack,q&&!q.errored&&(q.errored=T),D&&!D.errored&&(D.errored=T))}function f(T,q){let D=this._readableState,U=this._writableState,ae=U||D;return U!=null&&U.destroyed||D!=null&&D.destroyed?(typeof q=="function"&&q(),this):(b(T,U,D),U&&(U.destroyed=!0),D&&(D.destroyed=!0),ae.constructed?g(this,T,q):this.once(h,function(Y){g(this,r(Y,T),q)}),this)}function g(T,q,D){let U=!1;function ae(Y){if(U)return;U=!0;let V=T._readableState,re=T._writableState;b(Y,re,V),re&&(re.closed=!0),V&&(V.closed=!0),typeof D=="function"&&D(Y),Y?t.nextTick(y,T,Y):t.nextTick(w,T)}try{T._destroy(q||null,ae)}catch(Y){ae(Y)}}function y(T,q){m(T,q),w(T)}function w(T){let q=T._readableState,D=T._writableState;D&&(D.closeEmitted=!0),q&&(q.closeEmitted=!0),(D!=null&&D.emitClose||q!=null&&q.emitClose)&&T.emit("close")}function m(T,q){let D=T._readableState,U=T._writableState;U!=null&&U.errorEmitted||D!=null&&D.errorEmitted||(U&&(U.errorEmitted=!0),D&&(D.errorEmitted=!0),T.emit("error",q))}function _(){let T=this._readableState,q=this._writableState;T&&(T.constructed=!0,T.closed=!1,T.closeEmitted=!1,T.destroyed=!1,T.errored=null,T.errorEmitted=!1,T.reading=!1,T.ended=T.readable===!1,T.endEmitted=T.readable===!1),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function x(T,q,D){let U=T._readableState,ae=T._writableState;if(ae!=null&&ae.destroyed||U!=null&&U.destroyed)return this;U!=null&&U.autoDestroy||ae!=null&&ae.autoDestroy?T.destroy(q):q&&(q.stack,ae&&!ae.errored&&(ae.errored=q),U&&!U.errored&&(U.errored=q),D?t.nextTick(m,T,q):m(T,q))}function v(T,q){if(typeof T._construct!="function")return;let D=T._readableState,U=T._writableState;D&&(D.constructed=!1),U&&(U.constructed=!1),T.once(p,q),!(T.listenerCount(p)>1)&&t.nextTick(E,T)}function E(T){let q=!1;function D(U){if(q){x(T,U??new i);return}q=!0;let ae=T._readableState,Y=T._writableState,V=Y||ae;ae&&(ae.constructed=!0),Y&&(Y.constructed=!0),V.destroyed?T.emit(h,U):U?x(T,U,!0):t.nextTick(S,T)}try{T._construct(U=>{t.nextTick(D,U)})}catch(U){t.nextTick(D,U)}}function S(T){T.emit(p)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function O(T){T.emit("close")}function P(T,q){T.emit("error",q),t.nextTick(O,T)}function N(T,q){!T||l(T)||(!q&&!c(T)&&(q=new n),u(T)?(T.socket=null,T.destroy(q)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(q):typeof T.close=="function"?T.close():q?t.nextTick(P,T,q):t.nextTick(O,T),T.destroyed||(T[s]=!0))}e.exports={construct:v,destroyer:N,destroy:f,undestroy:_,errorOrDestroy:x}}),so=pe((a,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=je(),{EventEmitter:i}=(Ct(),Pe(wt));function n(s){i.call(this,s)}r(n.prototype,i.prototype),r(n,i),n.prototype.pipe=function(s,l){let c=this;function u(w){s.writable&&s.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function h(){c.readable&&c.resume&&c.resume()}s.on("drain",h),!s._isStdio&&(!l||l.end!==!1)&&(c.on("end",b),c.on("close",f));let p=!1;function b(){p||(p=!0,s.end())}function f(){p||(p=!0,typeof s.destroy=="function"&&s.destroy())}function g(w){y(),i.listenerCount(this,"error")===0&&this.emit("error",w)}o(c,"error",g),o(s,"error",g);function y(){c.removeListener("data",u),s.removeListener("drain",h),c.removeListener("end",b),c.removeListener("close",f),c.removeListener("error",g),s.removeListener("error",g),c.removeListener("end",y),c.removeListener("close",y),s.removeListener("close",y)}return c.on("end",y),c.on("close",y),s.on("close",y),s.emit("pipe",c),s};function o(s,l,c){if(typeof s.prependListener=="function")return s.prependListener(l,c);!s._events||!s._events[l]?s.on(l,c):t(s._events[l])?s._events[l].unshift(c):s._events[l]=[c,s._events[l]]}e.exports={Stream:n,prependListener:o}}),Dr=pe((a,e)=>{le(),ue(),ce();var{SymbolDispose:t}=je(),{AbortError:r,codes:i}=We(),{isNodeStream:n,isWebStream:o,kControllerErrorFunction:s}=dt(),l=_t(),{ERR_INVALID_ARG_TYPE:c}=i,u,h=(p,b)=>{if(typeof p!="object"||!("aborted"in p))throw new c(b,"AbortSignal",p)};e.exports.addAbortSignal=function(p,b){if(h(p,"signal"),!n(b)&&!o(b))throw new c("stream",["ReadableStream","WritableStream","Stream"],b);return e.exports.addAbortSignalNoValidate(p,b)},e.exports.addAbortSignalNoValidate=function(p,b){if(typeof p!="object"||!("aborted"in p))return b;let f=n(b)?()=>{b.destroy(new r(void 0,{cause:p.reason}))}:()=>{b[s](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||ze().addAbortListener;let g=u(p,f);l(b,g[t])}return b}}),Dc=pe((a,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:i,Uint8Array:n}=je(),{Buffer:o}=(Be(),Pe(Ue)),{inspect:s}=ze();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 o.alloc(0);let c=o.allocUnsafe(l>>>0),u=this.head,h=0;for(;u;)i(c,u.data,h),h+=u.data.length,u=u.next;return c}consume(l,c){let u=this.head.data;if(l<u.length){let h=u.slice(0,l);return this.head.data=u.slice(l),h}return l===u.length?this.shift():c?this._getString(l):this._getBuffer(l)}first(){return this.head.data}*[r](){for(let l=this.head;l;l=l.next)yield l.data}_getString(l){let c="",u=this.head,h=0;do{let p=u.data;if(l>p.length)c+=p,l-=p.length;else{l===p.length?(c+=p,++h,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,l),this.head=u,u.data=t(p,l));break}++h}while((u=u.next)!==null);return this.length-=h,c}_getBuffer(l){let c=o.allocUnsafe(l),u=l,h=this.head,p=0;do{let b=h.data;if(l>b.length)i(c,b,u-l),l-=b.length;else{l===b.length?(i(c,b,u-l),++p,h.next?this.head=h.next:this.head=this.tail=null):(i(c,new n(b.buffer,b.byteOffset,l),u-l),this.head=h,h.data=b.slice(l));break}++p}while((h=h.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return s(this,{...c,depth:0,customInspect:!1})}}}),Fr=pe((a,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=je(),{validateInteger:i}=tr(),{ERR_INVALID_ARG_VALUE:n}=We().codes,o=16*1024,s=16;function l(p,b,f){return p.highWaterMark!=null?p.highWaterMark:b?p[f]:null}function c(p){return p?s:o}function u(p,b){i(b,"value",0),p?s=b:o=b}function h(p,b,f,g){let y=l(b,g,f);if(y!=null){if(!r(y)||y<0){let w=g?`options.${f}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(p.objectMode)}e.exports={getHighWaterMark:h,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),Fc=pe((a,e)=>{le(),ue(),ce();var t=(Be(),Pe(Ue)),r=t.Buffer;function i(o,s){for(var l in o)s[l]=o[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(i(t,a),a.Buffer=n);function n(o,s,l){return r(o,s,l)}n.prototype=Object.create(r.prototype),i(r,n),n.from=function(o,s,l){if(typeof o=="number")throw new TypeError("Argument must not be a number");return r(o,s,l)},n.alloc=function(o,s,l){if(typeof o!="number")throw new TypeError("Argument must be a number");var c=r(o);return s!==void 0?typeof l=="string"?c.fill(s,l):c.fill(s):c.fill(0),c},n.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r(o)},n.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(o)}}),$c=pe(a=>{le(),ue(),ce();var e=Fc().Buffer,t=e.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(m){if(!m)return"utf8";for(var _;;)switch(m){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return m;default:if(_)return;m=(""+m).toLowerCase(),_=!0}}function i(m){var _=r(m);if(typeof _!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return _||m}a.StringDecoder=n;function n(m){this.encoding=i(m);var _;switch(this.encoding){case"utf16le":this.text=p,this.end=b,_=4;break;case"utf8":this.fillLast=c,_=4;break;case"base64":this.text=f,this.end=g,_=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(_)}n.prototype.write=function(m){if(m.length===0)return"";var _,x;if(this.lastNeed){if(_=this.fillLast(m),_===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?_?_+this.text(m,x):this.text(m,x):_||""},n.prototype.end=h,n.prototype.text=u,n.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length};function o(m){return m<=127?0:m>>5===6?2:m>>4===14?3:m>>3===30?4:m>>6===2?-1:-2}function s(m,_,x){var v=_.length-1;if(v<x)return 0;var E=o(_[v]);return E>=0?(E>0&&(m.lastNeed=E-1),E):--v<x||E===-2?0:(E=o(_[v]),E>=0?(E>0&&(m.lastNeed=E-2),E):--v<x||E===-2?0:(E=o(_[v]),E>=0?(E>0&&(E===2?E=0:m.lastNeed=E-3),E):0))}function l(m,_,x){if((_[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&_.length>1){if((_[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&_.length>2&&(_[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var _=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,_,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,_,0,m.length),this.lastNeed-=m.length}function u(m,_){var x=s(this,m,_);if(!this.lastNeed)return m.toString("utf8",_);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",_,v)}function h(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+"�":_}function p(m,_){if((m.length-_)%2===0){var x=m.toString("utf16le",_);if(x){var v=x.charCodeAt(x.length-1);if(v>=55296&&v<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1],x.slice(0,-1)}return x}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",_,m.length-1)}function b(m){var _=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return _+this.lastChar.toString("utf16le",0,x)}return _}function f(m,_){var x=(m.length-_)%3;return x===0?m.toString("base64",_):(this.lastNeed=3-x,this.lastTotal=3,x===1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",_,m.length-x))}function g(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+this.lastChar.toString("base64",0,3-this.lastNeed):_}function y(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),ga=pe((a,e)=>{le(),ue(),ce();var t=Ot(),{PromisePrototypeThen:r,SymbolAsyncIterator:i,SymbolIterator:n}=je(),{Buffer:o}=(Be(),Pe(Ue)),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_NULL_VALUES:l}=We().codes;function c(u,h,p){let b;if(typeof h=="string"||h instanceof o)return new u({objectMode:!0,...p,read(){this.push(h),this.push(null)}});let f;if(h&&h[i])f=!0,b=h[i]();else if(h&&h[n])f=!1,b=h[n]();else throw new s("iterable",["Iterable"],h);let g=new u({objectMode:!0,highWaterMark:1,...p}),y=!1;g._read=function(){y||(y=!0,m())},g._destroy=function(_,x){r(w(_),()=>t.nextTick(x,_),v=>t.nextTick(x,v||_))};async function w(_){let x=_!=null,v=typeof b.throw=="function";if(x&&v){let{value:E,done:S}=await b.throw(_);if(await E,S)return}if(typeof b.return=="function"){let{value:E}=await b.return();await E}}async function m(){for(;;){try{let{value:_,done:x}=f?await b.next():b.next();if(x)g.push(null);else{let v=_&&typeof _.then=="function"?await _:_;if(v===null)throw y=!1,new l;if(g.push(v))continue;y=!1}}catch(_){g.destroy(_)}break}}return g}e.exports=c}),$r=pe((a,e)=>{le(),ue(),ce();var t=Ot(),{ArrayPrototypeIndexOf:r,NumberIsInteger:i,NumberIsNaN:n,NumberParseInt:o,ObjectDefineProperties:s,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:h,SymbolAsyncDispose:p,SymbolAsyncIterator:b,Symbol:f}=je();e.exports=se,se.ReadableState=ve;var{EventEmitter:g}=(Ct(),Pe(wt)),{Stream:y,prependListener:w}=so(),{Buffer:m}=(Be(),Pe(Ue)),{addAbortSignal:_}=Dr(),x=_t(),v=ze().debuglog("stream",C=>{v=C}),E=Dc(),S=Ft(),{getHighWaterMark:I,getDefaultHighWaterMark:O}=Fr(),{aggregateTwoErrors:P,codes:{ERR_INVALID_ARG_TYPE:N,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:q,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:ae}=We(),{validateObject:Y}=tr(),V=f("kPaused"),{StringDecoder:re}=$c(),F=ga();c(se.prototype,y.prototype),c(se,y);var Z=()=>{},{errorOrDestroy:M}=S,J=1,be=2,te=4,we=8,G=16,j=32,ne=64,W=128,K=256,Q=512,ge=1024,oe=2048,R=4096,$=8192,ee=16384,de=32768,fe=65536,ye=1<<17,H=1<<18;function me(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(L){L?this.state|=C:this.state&=~C}}}s(ve.prototype,{objectMode:me(J),ended:me(be),endEmitted:me(te),reading:me(we),constructed:me(G),sync:me(j),needReadable:me(ne),emittedReadable:me(W),readableListening:me(K),resumeScheduled:me(Q),errorEmitted:me(ge),emitClose:me(oe),autoDestroy:me(R),destroyed:me($),closed:me(ee),closeEmitted:me(de),multiAwaitDrain:me(fe),readingMore:me(ye),dataEmitted:me(H)});function ve(C,L,_e){typeof _e!="boolean"&&(_e=L instanceof ut()),this.state=oe|R|G|j,C&&C.objectMode&&(this.state|=J),_e&&C&&C.readableObjectMode&&(this.state|=J),this.highWaterMark=C?I(this,C,"readableHighWaterMark",_e):O(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[V]=null,C&&C.emitClose===!1&&(this.state&=~oe),C&&C.autoDestroy===!1&&(this.state&=~R),this.errored=null,this.defaultEncoding=C&&C.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,C&&C.encoding&&(this.decoder=new re(C.encoding),this.encoding=C.encoding)}function se(C){if(!(this instanceof se))return new se(C);let L=this instanceof ut();this._readableState=new ve(C,this,L),C&&(typeof C.read=="function"&&(this._read=C.read),typeof C.destroy=="function"&&(this._destroy=C.destroy),typeof C.construct=="function"&&(this._construct=C.construct),C.signal&&!L&&_(C.signal,this)),y.call(this,C),S.construct(this,()=>{this._readableState.needReadable&&z(this,this._readableState)})}se.prototype.destroy=S.destroy,se.prototype._undestroy=S.undestroy,se.prototype._destroy=function(C,L){L(C)},se.prototype[g.captureRejectionSymbol]=function(C){this.destroy(C)},se.prototype[p]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new ae,this.destroy(C)),new u((L,_e)=>x(this,xe=>xe&&xe!==C?_e(xe):L(null)))},se.prototype.push=function(C,L){return Te(this,C,L,!1)},se.prototype.unshift=function(C,L){return Te(this,C,L,!0)};function Te(C,L,_e,xe){v("readableAddChunk",L);let Se=C._readableState,Ne;if((Se.state&J)===0&&(typeof L=="string"?(_e=_e||Se.defaultEncoding,Se.encoding!==_e&&(xe&&Se.encoding?L=m.from(L,_e).toString(Se.encoding):(L=m.from(L,_e),_e=""))):L instanceof m?_e="":y._isUint8Array(L)?(L=y._uint8ArrayToBuffer(L),_e=""):L!=null&&(Ne=new N("chunk",["string","Buffer","Uint8Array"],L))),Ne)M(C,Ne);else if(L===null)Se.state&=~we,X(C,Se);else if((Se.state&J)!==0||L&&L.length>0)if(xe)if((Se.state&te)!==0)M(C,new U);else{if(Se.destroyed||Se.errored)return!1;d(C,Se,L,!0)}else if(Se.ended)M(C,new D);else{if(Se.destroyed||Se.errored)return!1;Se.state&=~we,Se.decoder&&!_e?(L=Se.decoder.write(L),Se.objectMode||L.length!==0?d(C,Se,L,!1):z(C,Se)):d(C,Se,L,!1)}else xe||(Se.state&=~we,z(C,Se));return!Se.ended&&(Se.length<Se.highWaterMark||Se.length===0)}function d(C,L,_e,xe){L.flowing&&L.length===0&&!L.sync&&C.listenerCount("data")>0?((L.state&fe)!==0?L.awaitDrainWriters.clear():L.awaitDrainWriters=null,L.dataEmitted=!0,C.emit("data",_e)):(L.length+=L.objectMode?1:_e.length,xe?L.buffer.unshift(_e):L.buffer.push(_e),(L.state&ne)!==0&&he(C)),z(C,L)}se.prototype.isPaused=function(){let C=this._readableState;return C[V]===!0||C.flowing===!1},se.prototype.setEncoding=function(C){let L=new re(C);this._readableState.decoder=L,this._readableState.encoding=this._readableState.decoder.encoding;let _e=this._readableState.buffer,xe="";for(let Se of _e)xe+=L.write(Se);return _e.clear(),xe!==""&&_e.push(xe),this._readableState.length=xe.length,this};var k=1073741824;function A(C){if(C>k)throw new q("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function B(C,L){return C<=0||L.length===0&&L.ended?0:(L.state&J)!==0?1:n(C)?L.flowing&&L.length?L.buffer.first().length:L.length:C<=L.length?C:L.ended?L.length:0}se.prototype.read=function(C){v("read",C),C===void 0?C=NaN:i(C)||(C=o(C,10));let L=this._readableState,_e=C;if(C>L.highWaterMark&&(L.highWaterMark=A(C)),C!==0&&(L.state&=~W),C===0&&L.needReadable&&((L.highWaterMark!==0?L.length>=L.highWaterMark:L.length>0)||L.ended))return v("read: emitReadable",L.length,L.ended),L.length===0&&L.ended?et(this):he(this),null;if(C=B(C,L),C===0&&L.ended)return L.length===0&&et(this),null;let xe=(L.state&ne)!==0;if(v("need readable",xe),(L.length===0||L.length-C<L.highWaterMark)&&(xe=!0,v("length less than watermark",xe)),L.ended||L.reading||L.destroyed||L.errored||!L.constructed)xe=!1,v("reading, ended or constructing",xe);else if(xe){v("do read"),L.state|=we|j,L.length===0&&(L.state|=ne);try{this._read(L.highWaterMark)}catch(Ne){M(this,Ne)}L.state&=~j,L.reading||(C=B(_e,L))}let Se;return C>0?Se=Mt(C,L):Se=null,Se===null?(L.needReadable=L.length<=L.highWaterMark,C=0):(L.length-=C,L.multiAwaitDrain?L.awaitDrainWriters.clear():L.awaitDrainWriters=null),L.length===0&&(L.ended||(L.needReadable=!0),_e!==C&&L.ended&&et(this)),Se!==null&&!L.errorEmitted&&!L.closeEmitted&&(L.dataEmitted=!0,this.emit("data",Se)),Se};function X(C,L){if(v("onEofChunk"),!L.ended){if(L.decoder){let _e=L.decoder.end();_e&&_e.length&&(L.buffer.push(_e),L.length+=L.objectMode?1:_e.length)}L.ended=!0,L.sync?he(C):(L.needReadable=!1,L.emittedReadable=!0,ke(C))}}function he(C){let L=C._readableState;v("emitReadable",L.needReadable,L.emittedReadable),L.needReadable=!1,L.emittedReadable||(v("emitReadable",L.flowing),L.emittedReadable=!0,t.nextTick(ke,C))}function ke(C){let L=C._readableState;v("emitReadable_",L.destroyed,L.length,L.ended),!L.destroyed&&!L.errored&&(L.length||L.ended)&&(C.emit("readable"),L.emittedReadable=!1),L.needReadable=!L.flowing&&!L.ended&&L.length<=L.highWaterMark,Xe(C)}function z(C,L){!L.readingMore&&L.constructed&&(L.readingMore=!0,t.nextTick(ie,C,L))}function ie(C,L){for(;!L.reading&&!L.ended&&(L.length<L.highWaterMark||L.flowing&&L.length===0);){let _e=L.length;if(v("maybeReadMore read 0"),C.read(0),_e===L.length)break}L.readingMore=!1}se.prototype._read=function(C){throw new T("_read()")},se.prototype.pipe=function(C,L){let _e=this,xe=this._readableState;xe.pipes.length===1&&(xe.multiAwaitDrain||(xe.multiAwaitDrain=!0,xe.awaitDrainWriters=new h(xe.awaitDrainWriters?[xe.awaitDrainWriters]:[]))),xe.pipes.push(C),v("pipe count=%d opts=%j",xe.pipes.length,L);let Se=(!L||L.end!==!1)&&C!==t.stdout&&C!==t.stderr?He:xt;xe.endEmitted?t.nextTick(Se):_e.once("end",Se),C.on("unpipe",Ne);function Ne(rt,ot){v("onunpipe"),rt===_e&&ot&&ot.hasUnpiped===!1&&(ot.hasUnpiped=!0,zt())}function He(){v("onend"),C.end()}let Qe,Wt=!1;function zt(){v("cleanup"),C.removeListener("close",tt),C.removeListener("finish",mt),Qe&&C.removeListener("drain",Qe),C.removeListener("error",kt),C.removeListener("unpipe",Ne),_e.removeListener("end",He),_e.removeListener("end",xt),_e.removeListener("data",ir),Wt=!0,Qe&&xe.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&Qe()}function Vt(){Wt||(xe.pipes.length===1&&xe.pipes[0]===C?(v("false write response, pause",0),xe.awaitDrainWriters=C,xe.multiAwaitDrain=!1):xe.pipes.length>1&&xe.pipes.includes(C)&&(v("false write response, pause",xe.awaitDrainWriters.size),xe.awaitDrainWriters.add(C)),_e.pause()),Qe||(Qe=Ee(_e,C),C.on("drain",Qe))}_e.on("data",ir);function ir(rt){v("ondata");let ot=C.write(rt);v("dest.write",ot),ot===!1&&Vt()}function kt(rt){if(v("onerror",rt),xt(),C.removeListener("error",kt),C.listenerCount("error")===0){let ot=C._writableState||C._readableState;ot&&!ot.errorEmitted?M(C,rt):C.emit("error",rt)}}w(C,"error",kt);function tt(){C.removeListener("finish",mt),xt()}C.once("close",tt);function mt(){v("onfinish"),C.removeListener("close",tt),xt()}C.once("finish",mt);function xt(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?Vt():xe.flowing||(v("pipe resume"),_e.resume()),C};function Ee(C,L){return function(){let _e=C._readableState;_e.awaitDrainWriters===L?(v("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(v("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(L)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}se.prototype.unpipe=function(C){let L=this._readableState,_e={hasUnpiped:!1};if(L.pipes.length===0)return this;if(!C){let Se=L.pipes;L.pipes=[],this.pause();for(let Ne=0;Ne<Se.length;Ne++)Se[Ne].emit("unpipe",this,{hasUnpiped:!1});return this}let xe=r(L.pipes,C);return xe===-1?this:(L.pipes.splice(xe,1),L.pipes.length===0&&this.pause(),C.emit("unpipe",this,_e),this)},se.prototype.on=function(C,L){let _e=y.prototype.on.call(this,C,L),xe=this._readableState;return C==="data"?(xe.readableListening=this.listenerCount("readable")>0,xe.flowing!==!1&&this.resume()):C==="readable"&&!xe.endEmitted&&!xe.readableListening&&(xe.readableListening=xe.needReadable=!0,xe.flowing=!1,xe.emittedReadable=!1,v("on readable",xe.length,xe.reading),xe.length?he(this):xe.reading||t.nextTick(Ie,this)),_e},se.prototype.addListener=se.prototype.on,se.prototype.removeListener=function(C,L){let _e=y.prototype.removeListener.call(this,C,L);return C==="readable"&&t.nextTick(Ae,this),_e},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(C){let L=y.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Ae,this),L};function Ae(C){let L=C._readableState;L.readableListening=C.listenerCount("readable")>0,L.resumeScheduled&&L[V]===!1?L.flowing=!0:C.listenerCount("data")>0?C.resume():L.readableListening||(L.flowing=null)}function Ie(C){v("readable nexttick read 0"),C.read(0)}se.prototype.resume=function(){let C=this._readableState;return C.flowing||(v("resume"),C.flowing=!C.readableListening,Ce(this,C)),C[V]=!1,this};function Ce(C,L){L.resumeScheduled||(L.resumeScheduled=!0,t.nextTick(Je,C,L))}function Je(C,L){v("resume",L.reading),L.reading||C.read(0),L.resumeScheduled=!1,C.emit("resume"),Xe(C),L.flowing&&!L.reading&&C.read(0)}se.prototype.pause=function(){return v("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(v("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[V]=!0,this};function Xe(C){let L=C._readableState;for(v("flow",L.flowing);L.flowing&&C.read()!==null;);}se.prototype.wrap=function(C){let L=!1;C.on("data",xe=>{!this.push(xe)&&C.pause&&(L=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",xe=>{M(this,xe)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{L&&C.resume&&(L=!1,C.resume())};let _e=l(C);for(let xe=1;xe<_e.length;xe++){let Se=_e[xe];this[Se]===void 0&&typeof C[Se]=="function"&&(this[Se]=C[Se].bind(C))}return this},se.prototype[b]=function(){return De(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),De(this,C)};function De(C,L){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let _e=Ze(C,L);return _e.stream=C,_e}async function*Ze(C,L){let _e=Z;function xe(He){this===C?(_e(),_e=Z):_e=He}C.on("readable",xe);let Se,Ne=x(C,{writable:!1},He=>{Se=He?P(Se,He):null,_e(),_e=Z});try{for(;;){let He=C.destroyed?null:C.read();if(He!==null)yield He;else{if(Se)throw Se;if(Se===null)return;await new u(xe)}}}catch(He){throw Se=P(Se,He),Se}finally{(Se||L?.destroyOnReturn!==!1)&&(Se===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",xe),Ne())}}s(se.prototype,{readable:{__proto__:null,get(){let C=this._readableState;return!!C&&C.readable!==!1&&!C.destroyed&&!C.errorEmitted&&!C.endEmitted},set(C){this._readableState&&(this._readableState.readable=!!C)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(C){this._readableState&&(this._readableState.flowing=C)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(C){this._readableState&&(this._readableState.destroyed=C)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),s(ve.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[V]!==!1},set(C){this[V]=!!C}}}),se._fromList=Mt;function Mt(C,L){if(L.length===0)return null;let _e;return L.objectMode?_e=L.buffer.shift():!C||C>=L.length?(L.decoder?_e=L.buffer.join(""):L.buffer.length===1?_e=L.buffer.first():_e=L.buffer.concat(L.length),L.buffer.clear()):_e=L.buffer.consume(C,L.decoder),_e}function et(C){let L=C._readableState;v("endReadable",L.endEmitted),L.endEmitted||(L.ended=!0,t.nextTick(Ge,L,C))}function Ge(C,L){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,L.emit("end"),L.writable&&L.allowHalfOpen===!1)t.nextTick(nr,L);else if(C.autoDestroy){let _e=L._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&L.destroy()}}}function nr(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,L){return F(se,C,L)};var Rt;function Ht(){return Rt===void 0&&(Rt={}),Rt}se.fromWeb=function(C,L){return Ht().newStreamReadableFromReadableStream(C,L)},se.toWeb=function(C,L){return Ht().newReadableStreamFromStreamReadable(C,L)},se.wrap=function(C,L){var _e,xe;return new se({objectMode:(_e=(xe=C.readableObjectMode)!==null&&xe!==void 0?xe:C.objectMode)!==null&&_e!==void 0?_e:!0,...L,destroy(Se,Ne){S.destroyer(C,Se),Ne(Se)}}).wrap(C)}}),ao=pe((a,e)=>{le(),ue(),ce();var t=Ot(),{ArrayPrototypeSlice:r,Error:i,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:o,ObjectDefineProperties:s,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:h}=je();e.exports=Y,Y.WritableState=U;var{EventEmitter:p}=(Ct(),Pe(wt)),b=so().Stream,{Buffer:f}=(Be(),Pe(Ue)),g=Ft(),{addAbortSignal:y}=Dr(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=Fr(),{ERR_INVALID_ARG_TYPE:_,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:E,ERR_STREAM_DESTROYED:S,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:O,ERR_STREAM_WRITE_AFTER_END:P,ERR_UNKNOWN_ENCODING:N}=We().codes,{errorOrDestroy:T}=g;l(Y.prototype,b.prototype),l(Y,b);function q(){}var D=u("kOnFinished");function U(R,$,ee){typeof ee!="boolean"&&(ee=$ instanceof ut()),this.objectMode=!!(R&&R.objectMode),ee&&(this.objectMode=this.objectMode||!!(R&&R.writableObjectMode)),this.highWaterMark=R?w(this,R,"writableHighWaterMark",ee):m(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let de=!!(R&&R.decodeStrings===!1);this.decodeStrings=!de,this.defaultEncoding=R&&R.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=M.bind(void 0,$),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,ae(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!R||R.emitClose!==!1,this.autoDestroy=!R||R.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[D]=[]}function ae(R){R.buffered=[],R.bufferedIndex=0,R.allBuffers=!0,R.allNoop=!0}U.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},o(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Y(R){let $=this instanceof ut();if(!$&&!n(Y,this))return new Y(R);this._writableState=new U(R,this,$),R&&(typeof R.write=="function"&&(this._write=R.write),typeof R.writev=="function"&&(this._writev=R.writev),typeof R.destroy=="function"&&(this._destroy=R.destroy),typeof R.final=="function"&&(this._final=R.final),typeof R.construct=="function"&&(this._construct=R.construct),R.signal&&y(R.signal,this)),b.call(this,R),g.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),W(this,ee)})}o(Y,h,{__proto__:null,value:function(R){return n(this,R)?!0:this!==Y?!1:R&&R._writableState instanceof U}}),Y.prototype.pipe=function(){T(this,new E)};function V(R,$,ee,de){let fe=R._writableState;if(typeof ee=="function")de=ee,ee=fe.defaultEncoding;else{if(!ee)ee=fe.defaultEncoding;else if(ee!=="buffer"&&!f.isEncoding(ee))throw new N(ee);typeof de!="function"&&(de=q)}if($===null)throw new O;if(!fe.objectMode)if(typeof $=="string")fe.decodeStrings!==!1&&($=f.from($,ee),ee="buffer");else if($ instanceof f)ee="buffer";else if(b._isUint8Array($))$=b._uint8ArrayToBuffer($),ee="buffer";else throw new _("chunk",["string","Buffer","Uint8Array"],$);let ye;return fe.ending?ye=new P:fe.destroyed&&(ye=new S("write")),ye?(t.nextTick(de,ye),T(R,ye,!0),ye):(fe.pendingcb++,re(R,fe,$,ee,de))}Y.prototype.write=function(R,$,ee){return V(this,R,$,ee)===!0},Y.prototype.cork=function(){this._writableState.corked++},Y.prototype.uncork=function(){let R=this._writableState;R.corked&&(R.corked--,R.writing||we(this,R))},Y.prototype.setDefaultEncoding=function(R){if(typeof R=="string"&&(R=c(R)),!f.isEncoding(R))throw new N(R);return this._writableState.defaultEncoding=R,this};function re(R,$,ee,de,fe){let ye=$.objectMode?1:ee.length;$.length+=ye;let H=$.length<$.highWaterMark;return H||($.needDrain=!0),$.writing||$.corked||$.errored||!$.constructed?($.buffered.push({chunk:ee,encoding:de,callback:fe}),$.allBuffers&&de!=="buffer"&&($.allBuffers=!1),$.allNoop&&fe!==q&&($.allNoop=!1)):($.writelen=ye,$.writecb=fe,$.writing=!0,$.sync=!0,R._write(ee,de,$.onwrite),$.sync=!1),H&&!$.errored&&!$.destroyed}function F(R,$,ee,de,fe,ye,H){$.writelen=de,$.writecb=H,$.writing=!0,$.sync=!0,$.destroyed?$.onwrite(new S("write")):ee?R._writev(fe,$.onwrite):R._write(fe,ye,$.onwrite),$.sync=!1}function Z(R,$,ee,de){--$.pendingcb,de(ee),te($),T(R,ee)}function M(R,$){let ee=R._writableState,de=ee.sync,fe=ee.writecb;if(typeof fe!="function"){T(R,new v);return}ee.writing=!1,ee.writecb=null,ee.length-=ee.writelen,ee.writelen=0,$?($.stack,ee.errored||(ee.errored=$),R._readableState&&!R._readableState.errored&&(R._readableState.errored=$),de?t.nextTick(Z,R,ee,$,fe):Z(R,ee,$,fe)):(ee.buffered.length>ee.bufferedIndex&&we(R,ee),de?ee.afterWriteTickInfo!==null&&ee.afterWriteTickInfo.cb===fe?ee.afterWriteTickInfo.count++:(ee.afterWriteTickInfo={count:1,cb:fe,stream:R,state:ee},t.nextTick(J,ee.afterWriteTickInfo)):be(R,ee,1,fe))}function J({stream:R,state:$,count:ee,cb:de}){return $.afterWriteTickInfo=null,be(R,$,ee,de)}function be(R,$,ee,de){for(!$.ending&&!R.destroyed&&$.length===0&&$.needDrain&&($.needDrain=!1,R.emit("drain"));ee-- >0;)$.pendingcb--,de();$.destroyed&&te($),W(R,$)}function te(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var $;let{chunk:ye,callback:H}=R.buffered[fe],me=R.objectMode?1:ye.length;R.length-=me,H(($=R.errored)!==null&&$!==void 0?$:new S("write"))}let ee=R[D].splice(0);for(let fe=0;fe<ee.length;fe++){var de;ee[fe]((de=R.errored)!==null&&de!==void 0?de:new S("end"))}ae(R)}function we(R,$){if($.corked||$.bufferProcessing||$.destroyed||!$.constructed)return;let{buffered:ee,bufferedIndex:de,objectMode:fe}=$,ye=ee.length-de;if(!ye)return;let H=de;if($.bufferProcessing=!0,ye>1&&R._writev){$.pendingcb-=ye-1;let me=$.allNoop?q:se=>{for(let Te=H;Te<ee.length;++Te)ee[Te].callback(se)},ve=$.allNoop&&H===0?ee:r(ee,H);ve.allBuffers=$.allBuffers,F(R,$,!0,$.length,ve,"",me),ae($)}else{do{let{chunk:me,encoding:ve,callback:se}=ee[H];ee[H++]=null;let Te=fe?1:me.length;F(R,$,!1,Te,me,ve,se)}while(H<ee.length&&!$.writing);H===ee.length?ae($):H>256?(ee.splice(0,H),$.bufferedIndex=0):$.bufferedIndex=H}$.bufferProcessing=!1}Y.prototype._write=function(R,$,ee){if(this._writev)this._writev([{chunk:R,encoding:$}],ee);else throw new x("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,$,ee){let de=this._writableState;typeof R=="function"?(ee=R,R=null,$=null):typeof $=="function"&&(ee=$,$=null);let fe;if(R!=null){let ye=V(this,R,$);ye instanceof i&&(fe=ye)}return de.corked&&(de.corked=1,this.uncork()),fe||(!de.errored&&!de.ending?(de.ending=!0,W(this,de,!0),de.ended=!0):de.finished?fe=new I("end"):de.destroyed&&(fe=new S("end"))),typeof ee=="function"&&(fe||de.finished?t.nextTick(ee,fe):de[D].push(ee)),this};function G(R){return R.ending&&!R.destroyed&&R.constructed&&R.length===0&&!R.errored&&R.buffered.length===0&&!R.finished&&!R.writing&&!R.errorEmitted&&!R.closeEmitted}function j(R,$){let ee=!1;function de(fe){if(ee){T(R,fe??v());return}if(ee=!0,$.pendingcb--,fe){let ye=$[D].splice(0);for(let H=0;H<ye.length;H++)ye[H](fe);T(R,fe,$.sync)}else G($)&&($.prefinished=!0,R.emit("prefinish"),$.pendingcb++,t.nextTick(K,R,$))}$.sync=!0,$.pendingcb++;try{R._final(de)}catch(fe){de(fe)}$.sync=!1}function ne(R,$){!$.prefinished&&!$.finalCalled&&(typeof R._final=="function"&&!$.destroyed?($.finalCalled=!0,j(R,$)):($.prefinished=!0,R.emit("prefinish")))}function W(R,$,ee){G($)&&(ne(R,$),$.pendingcb===0&&(ee?($.pendingcb++,t.nextTick((de,fe)=>{G(fe)?K(de,fe):fe.pendingcb--},R,$)):G($)&&($.pendingcb++,K(R,$))))}function K(R,$){$.pendingcb--,$.finished=!0;let ee=$[D].splice(0);for(let de=0;de<ee.length;de++)ee[de]();if(R.emit("finish"),$.autoDestroy){let de=R._readableState;(!de||de.autoDestroy&&(de.endEmitted||de.readable===!1))&&R.destroy()}}s(Y.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(R){this._writableState&&(this._writableState.destroyed=R)}},writable:{__proto__:null,get(){let R=this._writableState;return!!R&&R.writable!==!1&&!R.destroyed&&!R.errored&&!R.ending&&!R.ended},set(R){this._writableState&&(this._writableState.writable=!!R)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let R=this._writableState;return R?!R.destroyed&&!R.ending&&R.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var Q=g.destroy;Y.prototype.destroy=function(R,$){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[D].length)&&t.nextTick(te,ee),Q.call(this,R,$),this},Y.prototype._undestroy=g.undestroy,Y.prototype._destroy=function(R,$){$(R)},Y.prototype[p.captureRejectionSymbol]=function(R){this.destroy(R)};var ge;function oe(){return ge===void 0&&(ge={}),ge}Y.fromWeb=function(R,$){return oe().newStreamWritableFromWritableStream(R,$)},Y.toWeb=function(R){return oe().newWritableStreamFromStreamWritable(R)}}),qc=pe((a,e)=>{le(),ue(),ce();var t=Ot(),r=(Be(),Pe(Ue)),{isReadable:i,isWritable:n,isIterable:o,isNodeStream:s,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:h,isWritableStream:p}=dt(),b=_t(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:g,ERR_INVALID_RETURN_VALUE:y}}=We(),{destroyer:w}=Ft(),m=ut(),_=$r(),x=ao(),{createDeferredPromise:v}=ze(),E=ga(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},O=globalThis.AbortController||er().AbortController,{FunctionPrototypeCall:P}=je(),N=class extends m{constructor(D){super(D),D?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),D?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function D(U,ae){if(u(U))return U;if(l(U))return q({readable:U});if(c(U))return q({writable:U});if(s(U))return q({writable:!1,readable:!1});if(h(U))return q({readable:_.fromWeb(U)});if(p(U))return q({writable:x.fromWeb(U)});if(typeof U=="function"){let{value:V,write:re,final:F,destroy:Z}=T(U);if(o(V))return E(N,V,{objectMode:!0,write:re,final:F,destroy:Z});let M=V?.then;if(typeof M=="function"){let J,be=P(M,V,te=>{if(te!=null)throw new y("nully","body",te)},te=>{w(J,te)});return J=new N({objectMode:!0,readable:!1,write:re,final(te){F(async()=>{try{await be,t.nextTick(te,null)}catch(we){t.nextTick(te,we)}})},destroy:Z})}throw new y("Iterable, AsyncIterable or AsyncFunction",ae,V)}if(I(U))return D(U.arrayBuffer());if(o(U))return E(N,U,{objectMode:!0,writable:!1});if(h(U?.readable)&&p(U?.writable))return N.fromWeb(U);if(typeof U?.writable=="object"||typeof U?.readable=="object"){let V=U!=null&&U.readable?l(U?.readable)?U?.readable:D(U.readable):void 0,re=U!=null&&U.writable?c(U?.writable)?U?.writable:D(U.writable):void 0;return q({readable:V,writable:re})}let Y=U?.then;if(typeof Y=="function"){let V;return P(Y,U,re=>{re!=null&&V.push(re),V.push(null)},re=>{w(V,re)}),V=new N({objectMode:!0,writable:!1,read(){}})}throw new g(ae,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(D){let{promise:U,resolve:ae}=v(),Y=new O,V=Y.signal;return{value:D((async function*(){for(;;){let re=U;U=null;let{chunk:F,done:Z,cb:M}=await re;if(t.nextTick(M),Z)return;if(V.aborted)throw new f(void 0,{cause:V.reason});({promise:U,resolve:ae}=v()),yield F}})(),{signal:V}),write(re,F,Z){let M=ae;ae=null,M({chunk:re,done:!1,cb:Z})},final(re){let F=ae;ae=null,F({done:!0,cb:re})},destroy(re,F){Y.abort(),F(re)}}}function q(D){let U=D.readable&&typeof D.readable.read!="function"?_.wrap(D.readable):D.readable,ae=D.writable,Y=!!i(U),V=!!n(ae),re,F,Z,M,J;function be(te){let we=M;M=null,we?we(te):te&&J.destroy(te)}return J=new N({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(ae!=null&&ae.writableObjectMode),readable:Y,writable:V}),V&&(b(ae,te=>{V=!1,te&&w(U,te),be(te)}),J._write=function(te,we,G){ae.write(te,we)?G():re=G},J._final=function(te){ae.end(),F=te},ae.on("drain",function(){if(re){let te=re;re=null,te()}}),ae.on("finish",function(){if(F){let te=F;F=null,te()}})),Y&&(b(U,te=>{Y=!1,te&&w(U,te),be(te)}),U.on("readable",function(){if(Z){let te=Z;Z=null,te()}}),U.on("end",function(){J.push(null)}),J._read=function(){for(;;){let te=U.read();if(te===null){Z=J._read;return}if(!J.push(te))return}}),J._destroy=function(te,we){!te&&M!==null&&(te=new f),Z=null,re=null,F=null,M===null?we(te):(M=we,w(ae,te),w(U,te))},J}}),ut=pe((a,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:i,ObjectSetPrototypeOf:n}=je();e.exports=l;var o=$r(),s=ao();n(l.prototype,o.prototype),n(l,o);{let p=i(s.prototype);for(let b=0;b<p.length;b++){let f=p[b];l.prototype[f]||(l.prototype[f]=s.prototype[f])}}function l(p){if(!(this instanceof l))return new l(p);o.call(this,p),s.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(s.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(s.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(s.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(s.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(s.prototype,"writableLength")},writableFinished:{__proto__:null,...r(s.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(s.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(s.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(s.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(p){this._readableState&&this._writableState&&(this._readableState.destroyed=p,this._writableState.destroyed=p)}}});var c;function u(){return c===void 0&&(c={}),c}l.fromWeb=function(p,b){return u().newStreamDuplexFromReadableWritablePair(p,b)},l.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var h;l.from=function(p){return h||(h=qc()),h(p,"body")}}),ba=pe((a,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=je();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:i}=We().codes,n=ut(),{getHighWaterMark:o}=Fr();t(l.prototype,n.prototype),t(l,n);var s=r("kCallback");function l(h){if(!(this instanceof l))return new l(h);let p=h?o(this,h,"readableHighWaterMark",!0):null;p===0&&(h={...h,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:h.writableHighWaterMark||0}),n.call(this,h),this._readableState.sync=!1,this[s]=null,h&&(typeof h.transform=="function"&&(this._transform=h.transform),typeof h.flush=="function"&&(this._flush=h.flush)),this.on("prefinish",u)}function c(h){typeof this._flush=="function"&&!this.destroyed?this._flush((p,b)=>{if(p){h?h(p):this.destroy(p);return}b!=null&&this.push(b),this.push(null),h&&h()}):(this.push(null),h&&h())}function u(){this._final!==c&&c.call(this)}l.prototype._final=c,l.prototype._transform=function(h,p,b){throw new i("_transform()")},l.prototype._write=function(h,p,b){let f=this._readableState,g=this._writableState,y=f.length;this._transform(h,p,(w,m)=>{if(w){b(w);return}m!=null&&this.push(m),g.ended||y===f.length||f.length<f.highWaterMark?b():this[s]=b})},l.prototype._read=function(){if(this[s]){let h=this[s];this[s]=null,h()}}}),ya=pe((a,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=je();e.exports=i;var r=ba();t(i.prototype,r.prototype),t(i,r);function i(n){if(!(this instanceof i))return new i(n);r.call(this,n)}i.prototype._transform=function(n,o,s){s(null,n)}}),lo=pe((a,e)=>{le(),ue(),ce();var t=Ot(),{ArrayIsArray:r,Promise:i,SymbolAsyncIterator:n,SymbolDispose:o}=je(),s=_t(),{once:l}=ze(),c=Ft(),u=ut(),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:b,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:g,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=We(),{validateFunction:m,validateAbortSignal:_}=tr(),{isIterable:x,isReadable:v,isReadableNodeStream:E,isNodeStream:S,isTransformStream:I,isWebStream:O,isReadableStream:P,isReadableFinished:N}=dt(),T=globalThis.AbortController||er().AbortController,q,D,U;function ae(te,we,G){let j=!1;te.on("close",()=>{j=!0});let ne=s(te,{readable:we,writable:G},W=>{j=!W});return{destroy:W=>{j||(j=!0,c.destroyer(te,W||new g("pipe")))},cleanup:ne}}function Y(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function V(te){if(x(te))return te;if(E(te))return re(te);throw new p("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){D||(D=$r()),yield*D.prototype[n].call(te)}async function F(te,we,G,{end:j}){let ne,W=null,K=oe=>{if(oe&&(ne=oe),W){let R=W;W=null,R()}},Q=()=>new i((oe,R)=>{ne?R(ne):W=()=>{ne?R(ne):oe()}});we.on("drain",K);let ge=s(we,{readable:!1},K);try{we.writableNeedDrain&&await Q();for await(let oe of te)we.write(oe)||await Q();j&&(we.end(),await Q()),G()}catch(oe){G(ne!==oe?h(ne,oe):oe)}finally{ge(),we.off("drain",K)}}async function Z(te,we,G,{end:j}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let W of te)await ne.ready,ne.write(W).catch(()=>{});await ne.ready,j&&await ne.close(),G()}catch(W){try{await ne.abort(W),G(W)}catch(K){G(K)}}}function M(...te){return J(te,l(Y(te)))}function J(te,we,G){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new f("streams");let j=new T,ne=j.signal,W=G?.signal,K=[];_(W,"options.signal");function Q(){fe(new w)}U=U||ze().addAbortListener;let ge;W&&(ge=U(W,Q));let oe,R,$=[],ee=0;function de(ve){fe(ve,--ee===0)}function fe(ve,se){var Te;if(ve&&(!oe||oe.code==="ERR_STREAM_PREMATURE_CLOSE")&&(oe=ve),!(!oe&&!se)){for(;$.length;)$.shift()(oe);(Te=ge)===null||Te===void 0||Te[o](),j.abort(),se&&(oe||K.forEach(d=>d()),t.nextTick(we,oe,R))}}let ye;for(let ve=0;ve<te.length;ve++){let se=te[ve],Te=ve<te.length-1,d=ve>0,k=Te||G?.end!==!1,A=ve===te.length-1;if(S(se)){let B=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&de(X)};if(k){let{destroy:X,cleanup:he}=ae(se,Te,d);$.push(X),v(se)&&A&&K.push(he)}se.on("error",B),v(se)&&A&&K.push(()=>{se.removeListener("error",B)})}if(ve===0)if(typeof se=="function"){if(ye=se({signal:ne}),!x(ye))throw new b("Iterable, AsyncIterable or Stream","source",ye)}else x(se)||E(se)||I(se)?ye=se:ye=u.from(se);else if(typeof se=="function"){if(I(ye)){var H;ye=V((H=ye)===null||H===void 0?void 0:H.readable)}else ye=V(ye);if(ye=se(ye,{signal:ne}),Te){if(!x(ye,!0))throw new b("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;q||(q=ya());let B=new q({objectMode:!0}),X=(me=ye)===null||me===void 0?void 0:me.then;if(typeof X=="function")ee++,X.call(ye,z=>{R=z,z!=null&&B.write(z),k&&B.end(),t.nextTick(de)},z=>{B.destroy(z),t.nextTick(de,z)});else if(x(ye,!0))ee++,F(ye,B,de,{end:k});else if(P(ye)||I(ye)){let z=ye.readable||ye;ee++,F(z,B,de,{end:k})}else throw new b("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:he,cleanup:ke}=ae(ye,!1,!0);$.push(he),A&&K.push(ke)}}else if(S(se)){if(E(ye)){ee+=2;let B=be(ye,se,de,{end:k});v(se)&&A&&K.push(B)}else if(I(ye)||P(ye)){let B=ye.readable||ye;ee++,F(B,se,de,{end:k})}else if(x(ye))ee++,F(ye,se,de,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else if(O(se)){if(E(ye))ee++,Z(V(ye),se,de,{end:k});else if(P(ye)||x(ye))ee++,Z(ye,se,de,{end:k});else if(I(ye))ee++,Z(ye.readable,se,de,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else ye=u.from(se)}return(ne!=null&&ne.aborted||W!=null&&W.aborted)&&t.nextTick(Q),ye}function be(te,we,G,{end:j}){let ne=!1;if(we.on("close",()=>{ne||G(new y)}),te.pipe(we,{end:!1}),j){let W=function(){ne=!0,we.end()};N(te)?t.nextTick(W):te.once("end",W)}else G();return s(te,{readable:!0,writable:!1},W=>{let K=te._readableState;W&&W.code==="ERR_STREAM_PREMATURE_CLOSE"&&K&&K.ended&&!K.errored&&!K.errorEmitted?te.once("end",G).once("error",G):G(W)}),s(we,{readable:!1,writable:!0},G)}e.exports={pipelineImpl:J,pipeline:M}}),va=pe((a,e)=>{le(),ue(),ce();var{pipeline:t}=lo(),r=ut(),{destroyer:i}=Ft(),{isNodeStream:n,isReadable:o,isWritable:s,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:h}=dt(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:b,ERR_MISSING_ARGS:f}}=We(),g=_t();e.exports=function(...y){if(y.length===0)throw new f("streams");if(y.length===1)return r.from(y[0]);let w=[...y];if(typeof y[0]=="function"&&(y[0]=r.from(y[0])),typeof y[y.length-1]=="function"){let T=y.length-1;y[T]=r.from(y[T])}for(let T=0;T<y.length;++T)if(!(!n(y[T])&&!l(y[T]))){if(T<y.length-1&&!(o(y[T])||h(y[T])||c(y[T])))throw new b(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(s(y[T])||u(y[T])||c(y[T])))throw new b(`streams[${T}]`,w[T],"must be writable")}let m,_,x,v,E;function S(T){let q=v;v=null,q?q(T):T?E.destroy(T):!N&&!P&&E.destroy()}let I=y[0],O=t(y,S),P=!!(s(I)||u(I)||c(I)),N=!!(o(O)||h(O)||c(O));if(E=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(O!=null&&O.readableObjectMode),writable:P,readable:N}),P){if(n(I))E._write=function(q,D,U){I.write(q,D)?U():m=U},E._final=function(q){I.end(),_=q},I.on("drain",function(){if(m){let q=m;m=null,q()}});else if(l(I)){let q=(c(I)?I.writable:I).getWriter();E._write=async function(D,U,ae){try{await q.ready,q.write(D).catch(()=>{}),ae()}catch(Y){ae(Y)}},E._final=async function(D){try{await q.ready,q.close().catch(()=>{}),_=D}catch(U){D(U)}}}let T=c(O)?O.readable:O;g(T,()=>{if(_){let q=_;_=null,q()}})}if(N){if(n(O))O.on("readable",function(){if(x){let T=x;x=null,T()}}),O.on("end",function(){E.push(null)}),E._read=function(){for(;;){let T=O.read();if(T===null){x=E._read;return}if(!E.push(T))return}};else if(l(O)){let T=(c(O)?O.readable:O).getReader();E._read=async function(){for(;;)try{let{value:q,done:D}=await T.read();if(!E.push(q))return;if(D){E.push(null);return}}catch{return}}}}return E._destroy=function(T,q){!T&&v!==null&&(T=new p),x=null,m=null,_=null,v===null?q(T):(v=q,n(O)&&i(O,T))},E}}),Hc=pe((a,e)=>{le(),ue(),ce();var t=globalThis.AbortController||er().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:i,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:o},AbortError:s}=We(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=tr(),h=je().Symbol("kWeak"),p=je().Symbol("kResistStopPropagation"),{finished:b}=_t(),f=va(),{addAbortSignalNoValidate:g}=Dr(),{isWritable:y,isNodeStream:w}=dt(),{deprecate:m}=ze(),{ArrayPrototypePush:_,Boolean:x,MathFloor:v,Number:E,NumberIsNaN:S,Promise:I,PromiseReject:O,PromiseResolve:P,PromisePrototypeThen:N,Symbol:T}=je(),q=T("kEmpty"),D=T("kEof");function U(W,K){if(K!=null&&u(K,"options"),K?.signal!=null&&l(K.signal,"options.signal"),w(W)&&!y(W))throw new r("stream",W,"must be writable");let Q=f(this,W);return K!=null&&K.signal&&g(K.signal,Q),Q}function ae(W,K){if(typeof W!="function")throw new i("fn",["Function","AsyncFunction"],W);K!=null&&u(K,"options"),K?.signal!=null&&l(K.signal,"options.signal");let Q=1;K?.concurrency!=null&&(Q=v(K.concurrency));let ge=Q-1;return K?.highWaterMark!=null&&(ge=v(K.highWaterMark)),c(Q,"options.concurrency",1),c(ge,"options.highWaterMark",0),ge+=Q,(async function*(){let oe=ze().AbortSignalAny([K?.signal].filter(x)),R=this,$=[],ee={signal:oe},de,fe,ye=!1,H=0;function me(){ye=!0,ve()}function ve(){H-=1,se()}function se(){fe&&!ye&&H<Q&&$.length<ge&&(fe(),fe=null)}async function Te(){try{for await(let d of R){if(ye)return;if(oe.aborted)throw new s;try{if(d=W(d,ee),d===q)continue;d=P(d)}catch(k){d=O(k)}H+=1,N(d,ve,me),$.push(d),de&&(de(),de=null),!ye&&($.length>=ge||H>=Q)&&await new I(k=>{fe=k})}$.push(D)}catch(d){let k=O(d);N(k,ve,me),$.push(k)}finally{ye=!0,de&&(de(),de=null)}}Te();try{for(;;){for(;$.length>0;){let d=await $[0];if(d===D)return;if(oe.aborted)throw new s;d!==q&&(yield d),$.shift(),se()}await new I(d=>{de=d})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function Y(W=void 0){return W!=null&&u(W,"options"),W?.signal!=null&&l(W.signal,"options.signal"),(async function*(){let K=0;for await(let ge of this){var Q;if(W!=null&&(Q=W.signal)!==null&&Q!==void 0&&Q.aborted)throw new s({cause:W.signal.reason});yield[K++,ge]}}).call(this)}async function V(W,K=void 0){for await(let Q of M.call(this,W,K))return!0;return!1}async function re(W,K=void 0){if(typeof W!="function")throw new i("fn",["Function","AsyncFunction"],W);return!await V.call(this,async(...Q)=>!await W(...Q),K)}async function F(W,K){for await(let Q of M.call(this,W,K))return Q}async function Z(W,K){if(typeof W!="function")throw new i("fn",["Function","AsyncFunction"],W);async function Q(ge,oe){return await W(ge,oe),q}for await(let ge of ae.call(this,Q,K));}function M(W,K){if(typeof W!="function")throw new i("fn",["Function","AsyncFunction"],W);async function Q(ge,oe){return await W(ge,oe)?ge:q}return ae.call(this,Q,K)}var J=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function be(W,K,Q){var ge;if(typeof W!="function")throw new i("reducer",["Function","AsyncFunction"],W);Q!=null&&u(Q,"options"),Q?.signal!=null&&l(Q.signal,"options.signal");let oe=arguments.length>1;if(Q!=null&&(ge=Q.signal)!==null&&ge!==void 0&&ge.aborted){let fe=new s(void 0,{cause:Q.signal.reason});throw this.once("error",()=>{}),await b(this.destroy(fe)),fe}let R=new t,$=R.signal;if(Q!=null&&Q.signal){let fe={once:!0,[h]:this,[p]:!0};Q.signal.addEventListener("abort",()=>R.abort(),fe)}let ee=!1;try{for await(let fe of this){var de;if(ee=!0,Q!=null&&(de=Q.signal)!==null&&de!==void 0&&de.aborted)throw new s;oe?K=await W(K,fe,{signal:$}):(K=fe,oe=!0)}if(!ee&&!oe)throw new J}finally{R.abort()}return K}async function te(W){W!=null&&u(W,"options"),W?.signal!=null&&l(W.signal,"options.signal");let K=[];for await(let ge of this){var Q;if(W!=null&&(Q=W.signal)!==null&&Q!==void 0&&Q.aborted)throw new s(void 0,{cause:W.signal.reason});_(K,ge)}return K}function we(W,K){let Q=ae.call(this,W,K);return(async function*(){for await(let ge of Q)yield*ge}).call(this)}function G(W){if(W=E(W),S(W))return 0;if(W<0)throw new o("number",">= 0",W);return W}function j(W,K=void 0){return K!=null&&u(K,"options"),K?.signal!=null&&l(K.signal,"options.signal"),W=G(W),(async function*(){var Q;if(K!=null&&(Q=K.signal)!==null&&Q!==void 0&&Q.aborted)throw new s;for await(let oe of this){var ge;if(K!=null&&(ge=K.signal)!==null&&ge!==void 0&&ge.aborted)throw new s;W--<=0&&(yield oe)}}).call(this)}function ne(W,K=void 0){return K!=null&&u(K,"options"),K?.signal!=null&&l(K.signal,"options.signal"),W=G(W),(async function*(){var Q;if(K!=null&&(Q=K.signal)!==null&&Q!==void 0&&Q.aborted)throw new s;for await(let oe of this){var ge;if(K!=null&&(ge=K.signal)!==null&&ge!==void 0&&ge.aborted)throw new s;if(W-- >0&&(yield oe),W<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(Y,"readable.asIndexedPairs will be removed in a future version."),drop:j,filter:M,flatMap:we,map:ae,take:ne,compose:U},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:be,toArray:te,some:V,find:F}}),wa=pe((a,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=je(),{isIterable:i,isNodeStream:n,isWebStream:o}=dt(),{pipelineImpl:s}=lo(),{finished:l}=_t();_a();function c(...u){return new r((h,p)=>{let b,f,g=u[u.length-1];if(g&&typeof g=="object"&&!n(g)&&!i(g)&&!o(g)){let y=t(u);b=y.signal,f=y.end}s(u,(y,w)=>{y?p(y):h(w)},{signal:b,end:f})})}e.exports={finished:l,pipeline:c}}),_a=pe((a,e)=>{le(),ue(),ce();var{Buffer:t}=(Be(),Pe(Ue)),{ObjectDefineProperty:r,ObjectKeys:i,ReflectApply:n}=je(),{promisify:{custom:o}}=ze(),{streamReturningOperators:s,promiseReturningOperators:l}=Hc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=We(),u=va(),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:p}=Fr(),{pipeline:b}=lo(),{destroyer:f}=Ft(),g=_t(),y=wa(),w=dt(),m=e.exports=so().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=$r();for(let x of i(s)){let v=function(...S){if(new.target)throw c();return m.Readable.from(n(E,this,S))},E=s[x];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let x of i(l)){let v=function(...S){if(new.target)throw c();return n(E,this,S)},E=l[x];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=ao(),m.Duplex=ut(),m.Transform=ba(),m.PassThrough=ya(),m.pipeline=b;var{addAbortSignal:_}=Dr();m.addAbortSignal=_,m.finished=g,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=h,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(b,o,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(g,o,{__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)}}),Pt=pe((a,e)=>{le(),ue(),ce();var t=_a(),r=wa(),i=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=i,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get(){return r}}),e.exports.Stream=t.Stream,e.exports.default=e.exports}),Wc=pe((a,e)=>{le(),ue(),ce(),typeof Object.create=="function"?e.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(t,r){if(r){t.super_=r;var i=function(){};i.prototype=r.prototype,t.prototype=new i,t.prototype.constructor=t}}}),zc=pe((a,e)=>{le(),ue(),ce();var{Buffer:t}=(Be(),Pe(Ue)),r=Symbol.for("BufferList");function i(n){if(!(this instanceof i))return new i(n);i._init.call(this,n)}i._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},i.prototype._new=function(n){return new i(n)},i.prototype._offset=function(n){if(n===0)return[0,0];let o=0;for(let s=0;s<this._bufs.length;s++){let l=o+this._bufs[s].length;if(n<l||s===this._bufs.length-1)return[s,n-o];o=l}},i.prototype._reverseOffset=function(n){let o=n[0],s=n[1];for(let l=0;l<o;l++)s+=this._bufs[l].length;return s},i.prototype.getBuffers=function(){return this._bufs},i.prototype.get=function(n){if(n>this.length||n<0)return;let o=this._offset(n);return this._bufs[o[0]][o[1]]},i.prototype.slice=function(n,o){return typeof n=="number"&&n<0&&(n+=this.length),typeof o=="number"&&o<0&&(o+=this.length),this.copy(null,0,n,o)},i.prototype.copy=function(n,o,s,l){if((typeof s!="number"||s<0)&&(s=0),(typeof l!="number"||l>this.length)&&(l=this.length),s>=this.length||l<=0)return n||t.alloc(0);let c=!!n,u=this._offset(s),h=l-s,p=h,b=c&&o||0,f=u[1];if(s===0&&l===this.length){if(!c)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let g=0;g<this._bufs.length;g++)this._bufs[g].copy(n,b),b+=this._bufs[g].length;return n}if(p<=this._bufs[u[0]].length-f)return c?this._bufs[u[0]].copy(n,o,f,f+p):this._bufs[u[0]].slice(f,f+p);c||(n=t.allocUnsafe(h));for(let g=u[0];g<this._bufs.length;g++){let y=this._bufs[g].length-f;if(p>y)this._bufs[g].copy(n,b,f),b+=y;else{this._bufs[g].copy(n,b,f,f+p),b+=y;break}p-=y,f&&(f=0)}return n.length>b?n.slice(0,b):n},i.prototype.shallowSlice=function(n,o){if(n=n||0,o=typeof o!="number"?this.length:o,n<0&&(n+=this.length),o<0&&(o+=this.length),n===o)return this._new();let s=this._offset(n),l=this._offset(o),c=this._bufs.slice(s[0],l[0]+1);return l[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,l[1]),s[1]!==0&&(c[0]=c[0].slice(s[1])),this._new(c)},i.prototype.toString=function(n,o,s){return this.slice(o,s).toString(n)},i.prototype.consume=function(n){if(n=Math.trunc(n),Number.isNaN(n)||n<=0)return this;for(;this._bufs.length;)if(n>=this._bufs[0].length)n-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(n),this.length-=n;break}return this},i.prototype.duplicate=function(){let n=this._new();for(let o=0;o<this._bufs.length;o++)n.append(this._bufs[o]);return n},i.prototype.append=function(n){return this._attach(n,i.prototype._appendBuffer)},i.prototype.prepend=function(n){return this._attach(n,i.prototype._prependBuffer,!0)},i.prototype._attach=function(n,o,s){if(n==null)return this;if(n.buffer)o.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[l,c]=s?[n.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n.length;u+=c)this._attach(n[u],o,s)}else if(this._isBufferList(n)){let[l,c]=s?[n._bufs.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],o,s)}else typeof n=="number"&&(n=n.toString()),o.call(this,t.from(n));return this},i.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},i.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},i.prototype.indexOf=function(n,o,s){if(s===void 0&&typeof o=="string"&&(s=o,o=void 0),typeof n=="function"||Array.isArray(n))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof n=="number"?n=t.from([n]):typeof n=="string"?n=t.from(n,s):this._isBufferList(n)?n=n.slice():Array.isArray(n.buffer)?n=t.from(n.buffer,n.byteOffset,n.byteLength):t.isBuffer(n)||(n=t.from(n)),o=Number(o||0),isNaN(o)&&(o=0),o<0&&(o=this.length+o),o<0&&(o=0),n.length===0)return o>this.length?this.length:o;let l=this._offset(o),c=l[0],u=l[1];for(;c<this._bufs.length;c++){let h=this._bufs[c];for(;u<h.length;)if(h.length-u>=n.length){let p=h.indexOf(n,u);if(p!==-1)return this._reverseOffset([c,p]);u=h.length-n.length+1}else{let p=this._reverseOffset([c,u]);if(this._match(p,n))return p;u++}u=0}return-1},i.prototype._match=function(n,o){if(this.length-n<o.length)return!1;for(let s=0;s<o.length;s++)if(this.get(n+s)!==o[s])return!1;return!0},(function(){let n={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let o in n)(function(s){n[s]===null?i.prototype[s]=function(l,c){return this.slice(l,l+c)[s](0,c)}:i.prototype[s]=function(l=0){return this.slice(l,l+n[s])[s](0)}})(o)})(),i.prototype._isBufferList=function(n){return n instanceof i||i.isBufferList(n)},i.isBufferList=function(n){return n!=null&&n[r]},e.exports=i}),Vc=pe((a,e)=>{le(),ue(),ce();var t=Pt().Duplex,r=Wc(),i=zc();function n(o){if(!(this instanceof n))return new n(o);if(typeof o=="function"){this._callback=o;let s=(function(l){this._callback&&(this._callback(l),this._callback=null)}).bind(this);this.on("pipe",function(l){l.on("error",s)}),this.on("unpipe",function(l){l.removeListener("error",s)}),o=null}i._init.call(this,o),t.call(this)}r(n,t),Object.assign(n.prototype,i.prototype),n.prototype._new=function(o){return new n(o)},n.prototype._write=function(o,s,l){this._appendBuffer(o),typeof l=="function"&&l()},n.prototype._read=function(o){if(!this.length)return this.push(null);o=Math.min(o,this.length),this.push(this.slice(0,o)),this.consume(o)},n.prototype.end=function(o){t.prototype.end.call(this,o),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(o,s){this._bufs.length=0,this.length=0,s(o)},n.prototype._isBufferList=function(o){return o instanceof n||o instanceof i||n.isBufferList(o)},n.isBufferList=i.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=i}),Gc=pe((a,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}),ka=pe((a,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(Be(),Pe(Ue));t.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},t.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0},t.requiredHeaderFlagsErrors={};for(let n in t.requiredHeaderFlags){let o=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+o.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let o=t.types[n];t.codes[o]=n}t.CMD_SHIFT=4,t.CMD_MASK=240,t.DUP_MASK=8,t.QOS_MASK=3,t.QOS_SHIFT=1,t.RETAIN_MASK=1,t.VARBYTEINT_MASK=127,t.VARBYTEINT_FIN_MASK=128,t.VARBYTEINT_MAX=268435455,t.SESSIONPRESENT_MASK=1,t.SESSIONPRESENT_HEADER=r.from([t.SESSIONPRESENT_MASK]),t.CONNACK_HEADER=r.from([t.codes.connack<<t.CMD_SHIFT]),t.USERNAME_MASK=128,t.PASSWORD_MASK=64,t.WILL_RETAIN_MASK=32,t.WILL_QOS_MASK=24,t.WILL_QOS_SHIFT=3,t.WILL_FLAG_MASK=4,t.CLEAN_SESSION_MASK=2,t.CONNECT_HEADER=r.from([t.codes.connect<<t.CMD_SHIFT]),t.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},t.propertiesCodes={};for(let n in t.properties){let o=t.properties[n];t.propertiesCodes[o]=n}t.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function i(n){return[0,1,2].map(o=>[0,1].map(s=>[0,1].map(l=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(s?t.DUP_MASK:0)|o<<t.QOS_SHIFT|l,0,!0),c})))}t.PUBLISH_HEADER=i("publish"),t.SUBSCRIBE_HEADER=i("subscribe"),t.SUBSCRIBE_OPTIONS_QOS_MASK=3,t.SUBSCRIBE_OPTIONS_NL_MASK=1,t.SUBSCRIBE_OPTIONS_NL_SHIFT=2,t.SUBSCRIBE_OPTIONS_RAP_MASK=1,t.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,t.SUBSCRIBE_OPTIONS_RH_MASK=3,t.SUBSCRIBE_OPTIONS_RH_SHIFT=4,t.SUBSCRIBE_OPTIONS_RH=[0,16,32],t.SUBSCRIBE_OPTIONS_NL=4,t.SUBSCRIBE_OPTIONS_RAP=8,t.SUBSCRIBE_OPTIONS_QOS=[0,1,2],t.UNSUBSCRIBE_HEADER=i("unsubscribe"),t.ACKS={unsuback:i("unsuback"),puback:i("puback"),pubcomp:i("pubcomp"),pubrel:i("pubrel"),pubrec:i("pubrec")},t.SUBACK_HEADER=r.from([t.codes.suback<<t.CMD_SHIFT]),t.VERSION3=r.from([3]),t.VERSION4=r.from([4]),t.VERSION5=r.from([5]),t.VERSION131=r.from([131]),t.VERSION132=r.from([132]),t.QOS=[0,1,2].map(n=>r.from([n])),t.EMPTY={pingreq:r.from([t.codes.pingreq<<4,0]),pingresp:r.from([t.codes.pingresp<<4,0]),disconnect:r.from([t.codes.disconnect<<4,0])},t.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},t.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},t.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},t.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}}),Kc=pe((a,e)=>{le(),ue(),ce();var t=1e3,r=t*60,i=r*60,n=i*24,o=n*7,s=n*365.25;e.exports=function(p,b){b=b||{};var f=typeof p;if(f==="string"&&p.length>0)return l(p);if(f==="number"&&isFinite(p))return b.long?u(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function l(p){if(p=String(p),!(p.length>100)){var b=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(b){var f=parseFloat(b[1]),g=(b[2]||"ms").toLowerCase();switch(g){case"years":case"year":case"yrs":case"yr":case"y":return f*s;case"weeks":case"week":case"w":return f*o;case"days":case"day":case"d":return f*n;case"hours":case"hour":case"hrs":case"hr":case"h":return f*i;case"minutes":case"minute":case"mins":case"min":case"m":return f*r;case"seconds":case"second":case"secs":case"sec":case"s":return f*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function c(p){var b=Math.abs(p);return b>=n?Math.round(p/n)+"d":b>=i?Math.round(p/i)+"h":b>=r?Math.round(p/r)+"m":b>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var b=Math.abs(p);return b>=n?h(p,b,n,"day"):b>=i?h(p,b,i,"hour"):b>=r?h(p,b,r,"minute"):b>=t?h(p,b,t,"second"):p+" ms"}function h(p,b,f,g){var y=b>=f*1.5;return Math.round(p/f)+" "+g+(y?"s":"")}}),Yc=pe((a,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=h,n.disable=c,n.enable=s,n.enabled=u,n.humanize=Kc(),n.destroy=p,Object.keys(r).forEach(b=>{n[b]=r[b]}),n.names=[],n.skips=[],n.formatters={};function i(b){let f=0;for(let g=0;g<b.length;g++)f=(f<<5)-f+b.charCodeAt(g),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=i;function n(b){let f,g=null,y,w;function m(..._){if(!m.enabled)return;let x=m,v=Number(new Date),E=v-(f||v);x.diff=E,x.prev=f,x.curr=v,f=v,_[0]=n.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let S=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(I,O)=>{if(I==="%%")return"%";S++;let P=n.formatters[O];if(typeof P=="function"){let N=_[S];I=P.call(x,N),_.splice(S,1),S--}return I}),n.formatArgs.call(x,_),(x.log||n.log).apply(x,_)}return m.namespace=b,m.useColors=n.useColors(),m.color=n.selectColor(b),m.extend=o,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(y!==n.namespaces&&(y=n.namespaces,w=n.enabled(b)),w),set:_=>{g=_}}),typeof n.init=="function"&&n.init(m),m}function o(b,f){let g=n(this.namespace+(typeof f>"u"?":":f)+b);return g.log=this.log,g}function s(b){n.save(b),n.namespaces=b,n.names=[],n.skips=[];let f=(typeof b=="string"?b:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let g of f)g[0]==="-"?n.skips.push(g.slice(1)):n.names.push(g)}function l(b,f){let g=0,y=0,w=-1,m=0;for(;g<b.length;)if(y<f.length&&(f[y]===b[g]||f[y]==="*"))f[y]==="*"?(w=y,m=g,y++):(g++,y++);else if(w!==-1)y=w+1,m++,g=m;else return!1;for(;y<f.length&&f[y]==="*";)y++;return y===f.length}function c(){let b=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),b}function u(b){for(let f of n.skips)if(l(b,f))return!1;for(let f of n.names)if(l(b,f))return!0;return!1}function h(b){return b instanceof Error?b.stack||b.message:b}function p(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}e.exports=t}),ht=pe((a,e)=>{le(),ue(),ce(),a.formatArgs=r,a.save=i,a.load=n,a.useColors=t,a.storage=o(),a.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`."))}})(),a.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;l.splice(1,0,c,"color: inherit");let u=0,h=0;l[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(h=u))}),l.splice(h,0,c)}a.log=console.debug||console.log||(()=>{});function i(l){try{l?a.storage.setItem("debug",l):a.storage.removeItem("debug")}catch{}}function n(){let l;try{l=a.storage.getItem("debug")||a.storage.getItem("DEBUG")}catch{}return!l&&typeof Re<"u"&&"env"in Re&&(l=Re.env.DEBUG),l}function o(){try{return localStorage}catch{}}e.exports=Yc()(a);var{formatters:s}=e.exports;s.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),Qc=pe((a,e)=>{le(),ue(),ce();var t=Vc(),{EventEmitter:r}=(Ct(),Pe(wt)),i=Gc(),n=ka(),o=ht()("mqtt-packet:parser"),s=class ui extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof ui?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new ui().parser(c)}_resetState(){o("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new i,this.error=null,this._list=t(),this._stateCounter=0}parse(c){for(this.error&&this._resetState(),this._list.append(c),o("parse: current state: %s",this._states[this._stateCounter]);(this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,o("parse: state complete. _stateCounter is now: %d",this._stateCounter),o("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return o("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let c=this._list.readUInt8(0),u=c>>n.CMD_SHIFT;this.packet.cmd=n.types[u];let h=c&15,p=n.requiredHeaderFlags[u];return p!=null&&h!==p?this._emitError(new Error(n.requiredHeaderFlagsErrors[u])):(this.packet.retain=(c&n.RETAIN_MASK)!==0,this.packet.qos=c>>n.QOS_SHIFT&n.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=(c&n.DUP_MASK)!==0,o("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){let c=this._parseVarByteNum(!0);return c&&(this.packet.length=c.value,this._list.consume(c.bytes)),o("_parseLength %d",c.value),!!c}_parsePayload(){o("_parsePayload: payload %O",this._list);let c=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}c=!0}return o("_parsePayload complete result: %s",c),c}_parseConnect(){o("_parseConnect");let c,u,h,p,b={},f=this.packet,g=this._parseString();if(g===null)return this._emitError(new Error("Cannot parse protocolId"));if(g!=="MQTT"&&g!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=g,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(f.protocolVersion=this._list.readUInt8(this._pos),f.protocolVersion>=128&&(f.bridgeMode=!0,f.protocolVersion=f.protocolVersion-128),f.protocolVersion!==3&&f.protocolVersion!==4&&f.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));b.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,b.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,b.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let y=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),w=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(b.will)f.will={},f.will.retain=y,f.will.qos=w;else{if(y)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(w)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(f.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,f.keepalive=this._parseNum(),f.keepalive===-1)return this._emitError(new Error("Packet too short"));if(f.protocolVersion===5){let _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(f.properties=_)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(f.clientId=m,o("_parseConnect: packet.clientId: %s",f.clientId),b.will){if(f.protocolVersion===5){let _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(f.will.properties=_)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=c,o("_parseConnect: packet.will.topic: %s",f.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));f.will.payload=u,o("_parseConnect: packet.will.paylaod: %s",f.will.payload)}if(b.username){if(p=this._parseString(),p===null)return this._emitError(new Error("Cannot parse username"));f.username=p,o("_parseConnect: packet.username: %s",f.username)}if(b.password){if(h=this._parseBuffer(),h===null)return this._emitError(new Error("Cannot parse password"));f.password=h}return this.settings=f,o("_parseConnect: complete"),f}_parseConnack(){o("_parseConnack");let c=this.packet;if(this._list.length<1)return null;let u=this._list.readUInt8(this._pos++);if(u>1)return this._emitError(new Error("Invalid connack flags, bits 7-1 must be set to 0"));if(c.sessionPresent=!!(u&n.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?c.reasonCode=this._list.readUInt8(this._pos++):c.reasonCode=0;else{if(this._list.length<2)return null;c.returnCode=this._list.readUInt8(this._pos++)}if(c.returnCode===-1||c.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let h=this._parseProperties();Object.getOwnPropertyNames(h).length&&(c.properties=h)}o("_parseConnack: complete")}_parsePublish(){o("_parsePublish");let c=this.packet;if(c.topic=this._parseString(),c.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(c.qos>0&&!this._parseMessageId())){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}c.payload=this._list.slice(this._pos,c.length),o("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){o("_parseSubscribe");let c=this.packet,u,h,p,b,f,g,y;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(c.properties=w)}if(c.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<c.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=c.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(h=this._parseByte(),this.settings.protocolVersion===5){if(h&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(h&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=h&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(g=(h>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(h>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,b=h>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,b>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));y={topic:u,qos:p},this.settings.protocolVersion===5?(y.nl=g,y.rap=f,y.rh=b):this.settings.bridgeMode&&(y.rh=0,y.rap=!0,y.nl=!0),o("_parseSubscribe: push subscription `%s` to subscription",y),c.subscriptions.push(y)}}}_parseSuback(){o("_parseSuback");let c=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos<this.packet.length;){let u=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!n.MQTT5_SUBACK_CODES[u])return this._emitError(new Error("Invalid suback code"))}else if(u>2&&u!==128)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(u)}}}_parseUnsubscribe(){o("_parseUnsubscribe");let c=this.packet;if(c.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<c.length;){let u=this._parseString();if(u===null)return this._emitError(new Error("Cannot parse topic"));o("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){o("_parseUnsuback");let c=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&c.length!==2)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(c.length<=0)return this._emitError(new Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let u=this._parseProperties();for(Object.getOwnPropertyNames(u).length&&(c.properties=u),c.granted=[];this._pos<this.packet.length;){let h=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[h])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(h)}}}_parseConfirmation(){o("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let c=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(c.length>2){switch(c.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!n.MQTT5_PUBACK_PUBREC_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!n.MQTT5_PUBREL_PUBCOMP_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break}o("_parseConfirmation: packet.reasonCode `%d`",c.reasonCode)}else c.reasonCode=0;if(c.length>3){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}}return!0}_parseDisconnect(){let c=this.packet;if(o("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?(c.reasonCode=this._parseByte(),n.MQTT5_DISCONNECT_CODES[c.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):c.reasonCode=0;let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}return o("_parseDisconnect result: true"),!0}_parseAuth(){o("_parseAuth");let c=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(c.reasonCode=this._parseByte(),!n.MQTT5_AUTH_CODES[c.reasonCode])return this._emitError(new Error("Invalid auth reason code"));let u=this._parseProperties();return Object.getOwnPropertyNames(u).length&&(c.properties=u),o("_parseAuth: result: true"),!0}_parseMessageId(){let c=this.packet;return c.messageId=this._parseNum(),c.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(o("_parseMessageId: packet.messageId %d",c.messageId),!0)}_parseString(c){let u=this._parseNum(),h=u+this._pos;if(u===-1||h>this._list.length||h>this.packet.length)return null;let p=this._list.toString("utf8",this._pos,h);return this._pos+=u,o("_parseString: result: %s",p),p}_parseStringPair(){return o("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let c=this._parseNum(),u=c+this._pos;if(c===-1||u>this._list.length||u>this.packet.length)return null;let h=this._list.slice(this._pos,u);return this._pos+=c,o("_parseBuffer: result: %o",h),h}_parseNum(){if(this._list.length-this._pos<2)return-1;let c=this._list.readUInt16BE(this._pos);return this._pos+=2,o("_parseNum: result: %s",c),c}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let c=this._list.readUInt32BE(this._pos);return this._pos+=4,o("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){o("_parseVarByteNum");let u=4,h=0,p=1,b=0,f=!1,g,y=this._pos?this._pos:0;for(;h<u&&y+h<this._list.length;){if(g=this._list.readUInt8(y+h++),b+=p*(g&n.VARBYTEINT_MASK),p*=128,(g&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=h)break}return!f&&h===u&&this._list.length>=h&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=h),f?c?f={bytes:h,value:b}:f=b:f=!1,o("_parseVarByteNum: result: %o",f),f}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),o("_parseByte: result: %o",c),c}_parseByType(c){switch(o("_parseByType: type: %s",c),c){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){o("_parseProperties");let c=this._parseVarByteNum(),u=this._pos+c,h={};for(;this._pos<u;){let p=this._parseByte();if(!p)return this._emitError(new Error("Cannot parse property code type")),!1;let b=n.propertiesCodes[p];if(!b)return this._emitError(new Error("Unknown property")),!1;if(b==="userProperties"){h[b]||(h[b]=Object.create(null));let f=this._parseByType(n.propertiesTypes[b]);if(h[b][f.name])if(Array.isArray(h[b][f.name]))h[b][f.name].push(f.value);else{let g=h[b][f.name];h[b][f.name]=[g],h[b][f.name].push(f.value)}else h[b][f.name]=f.value;continue}h[b]?Array.isArray(h[b])?h[b].push(this._parseByType(n.propertiesTypes[b])):(h[b]=[h[b]],h[b].push(this._parseByType(n.propertiesTypes[b]))):h[b]=this._parseByType(n.propertiesTypes[b])}return h}_newPacket(){return o("_newPacket"),this.packet&&(this._list.consume(this.packet.length),o("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),o("_newPacket: new packet"),this.packet=new i,this._pos=0,!0}_emitError(c){o("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=s}),Jc=pe((a,e)=>{le(),ue(),ce();var{Buffer:t}=(Be(),Pe(Ue)),r=65536,i={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function o(u){let h=t.allocUnsafe(2);return h.writeUInt8(u>>8,0),h.writeUInt8(u&255,1),h}function s(){for(let u=0;u<r;u++)i[u]=o(u)}function l(u){let h=0,p=0,b=t.allocUnsafe(4);do h=u%128|0,u=u/128|0,u>0&&(h=h|128),b.writeUInt8(h,p++);while(u>0&&p<4);return u>0&&(p=0),n?b.subarray(0,p):b.slice(0,p)}function c(u){let h=t.allocUnsafe(4);return h.writeUInt32BE(u,0),h}e.exports={cache:i,generateCache:s,generateNumber:o,genBufVariableByteInt:l,generate4ByteBuffer:c}}),Xc=pe((a,e)=>{le(),ue(),ce(),typeof Re>"u"||!Re.version||Re.version.indexOf("v0.")===0||Re.version.indexOf("v1.")===0&&Re.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Re;function t(r,i,n,o){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var s=arguments.length,l,c;switch(s){case 0:case 1:return Re.nextTick(r);case 2:return Re.nextTick(function(){r.call(null,i)});case 3:return Re.nextTick(function(){r.call(null,i,n)});case 4:return Re.nextTick(function(){r.call(null,i,n,o)});default:for(l=new Array(s-1),c=0;c<l.length;)l[c++]=arguments[c];return Re.nextTick(function(){r.apply(null,l)})}}}),xa=pe((a,e)=>{le(),ue(),ce();var t=ka(),{Buffer:r}=(Be(),Pe(Ue)),i=r.allocUnsafe(0),n=r.from([0]),o=Jc(),s=Xc().nextTick,l=ht()("mqtt-packet:writeToStream"),c=o.cache,u=o.generateNumber,h=o.generateCache,p=o.genBufVariableByteInt,b=o.generate4ByteBuffer,f=Y,g=!0;function y(G,j,ne){switch(l("generate called"),j.cork&&(j.cork(),s(w,j)),g&&(g=!1,h()),l("generate: packet.cmd: %s",G.cmd),G.cmd){case"connect":return m(G,j);case"connack":return _(G,j,ne);case"publish":return x(G,j,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(G,j,ne);case"subscribe":return E(G,j,ne);case"suback":return S(G,j,ne);case"unsubscribe":return I(G,j,ne);case"unsuback":return O(G,j,ne);case"pingreq":case"pingresp":return P(G,j);case"disconnect":return N(G,j,ne);case"auth":return T(G,j,ne);default:return j.destroy(new Error("Unknown command")),!1}}Object.defineProperty(y,"cacheNumbers",{get(){return f===Y},set(G){G?((!c||Object.keys(c).length===0)&&(g=!0),f=Y):(g=!1,f=V)}});function w(G){G.uncork()}function m(G,j,ne){let W=G||{},K=W.protocolId||"MQTT",Q=W.protocolVersion||4,ge=W.will,oe=W.clean,R=W.keepalive||0,$=W.clientId||"",ee=W.username,de=W.password,fe=W.properties;oe===void 0&&(oe=!0);let ye=0;if(typeof K!="string"&&!r.isBuffer(K))return j.destroy(new Error("Invalid protocolId")),!1;if(ye+=K.length+2,Q!==3&&Q!==4&&Q!==5)return j.destroy(new Error("Invalid protocol version")),!1;if(ye+=1,(typeof $=="string"||r.isBuffer($))&&($||Q>=4)&&($||oe))ye+=r.byteLength($)+2;else{if(Q<4)return j.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(oe*1===0)return j.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof R!="number"||R<0||R>65535||R%1!==0)return j.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let H,me;if(Q===5){if(H=Z(j,fe),!H)return!1;ye+=H.length}if(ge){if(typeof ge!="object")return j.destroy(new Error("Invalid will")),!1;if(!ge.topic||typeof ge.topic!="string")return j.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(ge.topic)+2,ye+=2,ge.payload)if(ge.payload.length>=0)typeof ge.payload=="string"?ye+=r.byteLength(ge.payload):ye+=ge.payload.length;else return j.destroy(new Error("Invalid will payload")),!1;if(me={},Q===5){if(me=Z(j,ge.properties),!me)return!1;ye+=me.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,ye+=r.byteLength(ee)+2;else return j.destroy(new Error("Invalid username")),!1;if(de!=null){if(!ve)return j.destroy(new Error("Username is required to use password")),!1;if(we(de))ye+=te(de)+2;else return j.destroy(new Error("Invalid password")),!1}j.write(t.CONNECT_HEADER),D(j,ye),F(j,K),W.bridgeMode&&(Q+=128),j.write(Q===131?t.VERSION131:Q===132?t.VERSION132:Q===4?t.VERSION4:Q===5?t.VERSION5:t.VERSION3);let se=0;return se|=ee!=null?t.USERNAME_MASK:0,se|=de!=null?t.PASSWORD_MASK:0,se|=ge&&ge.retain?t.WILL_RETAIN_MASK:0,se|=ge&&ge.qos?ge.qos<<t.WILL_QOS_SHIFT:0,se|=ge?t.WILL_FLAG_MASK:0,se|=oe?t.CLEAN_SESSION_MASK:0,j.write(r.from([se])),f(j,R),Q===5&&H.write(),F(j,$),ge&&(Q===5&&me.write(),U(j,ge.topic),F(j,ge.payload)),ee!=null&&F(j,ee),de!=null&&F(j,de),!0}function _(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=W===5?K.reasonCode:K.returnCode,ge=K.properties,oe=2;if(typeof Q!="number")return j.destroy(new Error("Invalid return code")),!1;let R=null;if(W===5){if(R=Z(j,ge),!R)return!1;oe+=R.length}return j.write(t.CONNACK_HEADER),D(j,oe),j.write(K.sessionPresent?t.SESSIONPRESENT_HEADER:n),j.write(r.from([Q])),R?.write(),!0}function x(G,j,ne){l("publish: packet: %o",G);let W=ne?ne.protocolVersion:4,K=G||{},Q=K.qos||0,ge=K.retain?t.RETAIN_MASK:0,oe=K.topic,R=K.payload||i,$=K.messageId,ee=K.properties,de=0;if(typeof oe=="string")de+=r.byteLength(oe)+2;else if(r.isBuffer(oe))de+=oe.length+2;else return j.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?de+=R.length:de+=r.byteLength(R),Q&&typeof $!="number")return j.destroy(new Error("Invalid messageId")),!1;Q&&(de+=2);let fe=null;if(W===5){if(fe=Z(j,ee),!fe)return!1;de+=fe.length}return j.write(t.PUBLISH_HEADER[Q][K.dup?1:0][ge?1:0]),D(j,de),f(j,te(oe)),j.write(oe),Q>0&&f(j,$),fe?.write(),l("publish: payload: %o",R),j.write(R)}function v(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.cmd||"puback",ge=K.messageId,oe=K.dup&&Q==="pubrel"?t.DUP_MASK:0,R=0,$=K.reasonCode,ee=K.properties,de=W===5?3:2;if(Q==="pubrel"&&(R=1),typeof ge!="number")return j.destroy(new Error("Invalid messageId")),!1;let fe=null;if(W===5&&typeof ee=="object"){if(fe=M(j,ee,ne,de),!fe)return!1;de+=fe.length}return j.write(t.ACKS[Q][R][oe][0]),de===3&&(de+=$!==0?1:-1),D(j,de),f(j,ge),W===5&&de!==2&&j.write(r.from([$])),fe!==null?fe.write():de===4&&j.write(r.from([0])),!0}function E(G,j,ne){l("subscribe: packet: ");let W=ne?ne.protocolVersion:4,K=G||{},Q=K.dup?t.DUP_MASK:0,ge=K.messageId,oe=K.subscriptions,R=K.properties,$=0;if(typeof ge!="number")return j.destroy(new Error("Invalid messageId")),!1;$+=2;let ee=null;if(W===5){if(ee=Z(j,R),!ee)return!1;$+=ee.length}if(typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){let ye=oe[fe].topic,H=oe[fe].qos;if(typeof ye!="string")return j.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return j.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(W===5){if(typeof(oe[fe].nl||!1)!="boolean")return j.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(oe[fe].rap||!1)!="boolean")return j.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=oe[fe].rh||0;if(typeof me!="number"||me>2)return j.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}$+=r.byteLength(ye)+2+1}else return j.destroy(new Error("Invalid subscriptions")),!1;l("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),j.write(t.SUBSCRIBE_HEADER[1][Q?1:0][0]),D(j,$),f(j,ge),ee!==null&&ee.write();let de=!0;for(let fe of oe){let ye=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,se=fe.rh,Te;U(j,ye),Te=t.SUBSCRIBE_OPTIONS_QOS[H],W===5&&(Te|=me?t.SUBSCRIBE_OPTIONS_NL:0,Te|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Te|=se?t.SUBSCRIBE_OPTIONS_RH[se]:0),de=j.write(r.from([Te]))}return de}function S(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ge=K.granted,oe=K.properties,R=0;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(R+=2,typeof ge=="object"&&ge.length)for(let ee=0;ee<ge.length;ee+=1){if(typeof ge[ee]!="number")return j.destroy(new Error("Invalid qos vector")),!1;R+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let $=null;if(W===5){if($=M(j,oe,ne,R),!$)return!1;R+=$.length}return j.write(t.SUBACK_HEADER),D(j,R),f(j,Q),$!==null&&$.write(),j.write(r.from(ge))}function I(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ge=K.dup?t.DUP_MASK:0,oe=K.unsubscriptions,R=K.properties,$=0;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if($+=2,typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){if(typeof oe[fe]!="string")return j.destroy(new Error("Invalid unsubscriptions")),!1;$+=r.byteLength(oe[fe])+2}else return j.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(W===5){if(ee=Z(j,R),!ee)return!1;$+=ee.length}j.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),D(j,$),f(j,Q),ee!==null&&ee.write();let de=!0;for(let fe=0;fe<oe.length;fe++)de=U(j,oe[fe]);return de}function O(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ge=K.dup?t.DUP_MASK:0,oe=K.granted,R=K.properties,$=K.cmd,ee=0,de=2;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(W===5)if(typeof oe=="object"&&oe.length)for(let ye=0;ye<oe.length;ye+=1){if(typeof oe[ye]!="number")return j.destroy(new Error("Invalid qos vector")),!1;de+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(W===5){if(fe=M(j,R,ne,de),!fe)return!1;de+=fe.length}return j.write(t.ACKS[$][ee][ge][0]),D(j,de),f(j,Q),fe!==null&&fe.write(),W===5&&j.write(r.from(oe)),!0}function P(G,j,ne){return j.write(t.EMPTY[G.cmd])}function N(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.reasonCode,ge=K.properties,oe=W===5?1:0,R=null;if(W===5){if(R=M(j,ge,ne,oe),!R)return!1;oe+=R.length}return j.write(r.from([t.codes.disconnect<<4])),D(j,oe),W===5&&j.write(r.from([Q])),R!==null&&R.write(),!0}function T(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.reasonCode,ge=K.properties,oe=W===5?1:0;W!==5&&j.destroy(new Error("Invalid mqtt version for auth packet"));let R=M(j,ge,ne,oe);return R?(oe+=R.length,j.write(r.from([t.codes.auth<<4])),D(j,oe),j.write(r.from([Q])),R!==null&&R.write(),!0):!1}var q={};function D(G,j){if(j>t.VARBYTEINT_MAX)return G.destroy(new Error(`Invalid variable byte integer: ${j}`)),!1;let ne=q[j];return ne||(ne=p(j),j<16384&&(q[j]=ne)),l("writeVarByteInt: writing to stream: %o",ne),G.write(ne)}function U(G,j){let ne=r.byteLength(j);return f(G,ne),l("writeString: %s",j),G.write(j,"utf8")}function ae(G,j,ne){U(G,j),U(G,ne)}function Y(G,j){return l("writeNumberCached: number: %d",j),l("writeNumberCached: %o",c[j]),G.write(c[j])}function V(G,j){let ne=u(j);return l("writeNumberGenerated: %o",ne),G.write(ne)}function re(G,j){let ne=b(j);return l("write4ByteNumber: %o",ne),G.write(ne)}function F(G,j){typeof j=="string"?U(G,j):j?(f(G,j.length),G.write(j)):f(G,0)}function Z(G,j){if(typeof j!="object"||j.length!=null)return{length:1,write(){be(G,{},0)}};let ne=0;function W(K,Q){let ge=t.propertiesTypes[K],oe=0;switch(ge){case"byte":{if(typeof Q!="boolean")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=2;break}case"int8":{if(typeof Q!="number"||Q<0||Q>255)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=2;break}case"binary":{if(Q&&Q===null)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=1+r.byteLength(Q)+2;break}case"int16":{if(typeof Q!="number"||Q<0||Q>65535)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=3;break}case"int32":{if(typeof Q!="number"||Q<0||Q>4294967295)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=5;break}case"var":{if(typeof Q!="number"||Q<0||Q>268435455)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=1+r.byteLength(p(Q));break}case"string":{if(typeof Q!="string")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=3+r.byteLength(Q.toString());break}case"pair":{if(typeof Q!="object")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=Object.getOwnPropertyNames(Q).reduce((R,$)=>{let ee=Q[$];return Array.isArray(ee)?R+=ee.reduce((de,fe)=>(de+=3+r.byteLength($.toString())+2+r.byteLength(fe.toString()),de),0):R+=3+r.byteLength($.toString())+2+r.byteLength(Q[$].toString()),R},0);break}default:return G.destroy(new Error(`Invalid property ${K}: ${Q}`)),!1}return oe}if(j)for(let K in j){let Q=0,ge=0,oe=j[K];if(oe!==void 0){if(Array.isArray(oe))for(let R=0;R<oe.length;R++){if(ge=W(K,oe[R]),!ge)return!1;Q+=ge}else{if(ge=W(K,oe),!ge)return!1;Q=ge}if(!Q)return!1;ne+=Q}}return{length:r.byteLength(p(ne))+ne,write(){be(G,j,ne)}}}function M(G,j,ne,W){let K=["reasonString","userProperties"],Q=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=Z(G,j);if(Q)for(;W+ge.length>Q;){let oe=K.shift();if(oe&&j[oe])delete j[oe],ge=Z(G,j);else return!1}return ge}function J(G,j,ne){switch(t.propertiesTypes[j]){case"byte":{G.write(r.from([t.properties[j]])),G.write(r.from([+ne]));break}case"int8":{G.write(r.from([t.properties[j]])),G.write(r.from([ne]));break}case"binary":{G.write(r.from([t.properties[j]])),F(G,ne);break}case"int16":{G.write(r.from([t.properties[j]])),f(G,ne);break}case"int32":{G.write(r.from([t.properties[j]])),re(G,ne);break}case"var":{G.write(r.from([t.properties[j]])),D(G,ne);break}case"string":{G.write(r.from([t.properties[j]])),U(G,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(W=>{let K=ne[W];Array.isArray(K)?K.forEach(Q=>{G.write(r.from([t.properties[j]])),ae(G,W.toString(),Q.toString())}):(G.write(r.from([t.properties[j]])),ae(G,W.toString(),K.toString()))});break}default:return G.destroy(new Error(`Invalid property ${j} value: ${ne}`)),!1}}function be(G,j,ne){D(G,ne);for(let W in j)if(Object.prototype.hasOwnProperty.call(j,W)&&j[W]!=null){let K=j[W];if(Array.isArray(K))for(let Q=0;Q<K.length;Q++)J(G,W,K[Q]);else J(G,W,K)}}function te(G){return G?G instanceof r?G.length:r.byteLength(G):0}function we(G){return typeof G=="string"||G instanceof r}e.exports=y}),Zc=pe((a,e)=>{le(),ue(),ce();var t=xa(),{EventEmitter:r}=(Ct(),Pe(wt)),{Buffer:i}=(Be(),Pe(Ue));function n(s,l){let c=new o;return t(s,c,l),c.concat()}var o=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(s){return this._array[this._i++]=s,!0}concat(){let s=0,l=new Array(this._array.length),c=this._array,u=0,h;for(h=0;h<c.length&&c[h]!==void 0;h++)typeof c[h]!="string"?l[h]=c[h].length:l[h]=i.byteLength(c[h]),s+=l[h];let p=i.allocUnsafe(s);for(h=0;h<c.length&&c[h]!==void 0;h++)typeof c[h]!="string"?(c[h].copy(p,u),u+=l[h]):(p.write(c[h],u),u+=l[h]);return p}destroy(s){s&&this.emit("error",s)}};e.exports=n}),eu=pe(a=>{le(),ue(),ce(),a.parser=Qc().parser,a.generate=Zc(),a.writeToStream=xa()}),tu=pe((a,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof Nr?Nr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return i(n);let o=new Map;if(o.set(Date,h=>new Date(h)),o.set(Map,(h,p)=>new Map(l(Array.from(h),p))),o.set(Set,(h,p)=>new Set(l(Array.from(h),p))),n.constructorHandlers)for(let h of n.constructorHandlers)o.set(h[0],h[1]);let s=null;return n.proto?u:c;function l(h,p){let b=Object.keys(h),f=new Array(b.length);for(let g=0;g<b.length;g++){let y=b[g],w=h[y];typeof w!="object"||w===null?f[y]=w:w.constructor!==Object&&(s=o.get(w.constructor))?f[y]=s(w,p):ArrayBuffer.isView(w)?f[y]=t(w):f[y]=p(w)}return f}function c(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return l(h,c);if(h.constructor!==Object&&(s=o.get(h.constructor)))return s(h,c);let p={};for(let b in h){if(Object.hasOwnProperty.call(h,b)===!1)continue;let f=h[b];typeof f!="object"||f===null?p[b]=f:f.constructor!==Object&&(s=o.get(f.constructor))?p[b]=s(f,c):ArrayBuffer.isView(f)?p[b]=t(f):p[b]=c(f)}return p}function u(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return l(h,u);if(h.constructor!==Object&&(s=o.get(h.constructor)))return s(h,u);let p={};for(let b in h){let f=h[b];typeof f!="object"||f===null?p[b]=f:f.constructor!==Object&&(s=o.get(f.constructor))?p[b]=s(f,u):ArrayBuffer.isView(f)?p[b]=t(f):p[b]=u(f)}return p}}function i(n){let o=[],s=[],l=new Map;if(l.set(Date,b=>new Date(b)),l.set(Map,(b,f)=>new Map(u(Array.from(b),f))),l.set(Set,(b,f)=>new Set(u(Array.from(b),f))),n.constructorHandlers)for(let b of n.constructorHandlers)l.set(b[0],b[1]);let c=null;return n.proto?p:h;function u(b,f){let g=Object.keys(b),y=new Array(g.length);for(let w=0;w<g.length;w++){let m=g[w],_=b[m];if(typeof _!="object"||_===null)y[m]=_;else if(_.constructor!==Object&&(c=l.get(_.constructor)))y[m]=c(_,f);else if(ArrayBuffer.isView(_))y[m]=t(_);else{let x=o.indexOf(_);x!==-1?y[m]=s[x]:y[m]=f(_)}}return y}function h(b){if(typeof b!="object"||b===null)return b;if(Array.isArray(b))return u(b,h);if(b.constructor!==Object&&(c=l.get(b.constructor)))return c(b,h);let f={};o.push(b),s.push(f);for(let g in b){if(Object.hasOwnProperty.call(b,g)===!1)continue;let y=b[g];if(typeof y!="object"||y===null)f[g]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))f[g]=c(y,h);else if(ArrayBuffer.isView(y))f[g]=t(y);else{let w=o.indexOf(y);w!==-1?f[g]=s[w]:f[g]=h(y)}}return o.pop(),s.pop(),f}function p(b){if(typeof b!="object"||b===null)return b;if(Array.isArray(b))return u(b,p);if(b.constructor!==Object&&(c=l.get(b.constructor)))return c(b,p);let f={};o.push(b),s.push(f);for(let g in b){let y=b[g];if(typeof y!="object"||y===null)f[g]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))f[g]=c(y,p);else if(ArrayBuffer.isView(y))f[g]=t(y);else{let w=o.indexOf(y);w!==-1?f[g]=s[w]:f[g]=p(y)}}return o.pop(),s.pop(),f}}}),ru=pe((a,e)=>{le(),ue(),ce(),e.exports=tu()()}),Sa=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0}),a.validateTopic=e,a.validateTopics=t;function e(r){let i=r.split("/");for(let n=0;n<i.length;n++)if(i[n]!=="+"){if(i[n]==="#")return n===i.length-1;if(i[n].indexOf("+")!==-1||i[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let i=0;i<r.length;i++)if(!e(r[i]))return r[i];return null}}),Ea=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=Pt(),t={objectMode:!0},r={clean:!0},i=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,o){return this._inflights.set(n.messageId,n),o&&o(),this}createStream(){let n=new e.Readable(t),o=[],s=!1,l=0;return this._inflights.forEach((c,u)=>{o.push(c)}),n._read=()=>{!s&&l<o.length?n.push(o[l++]):n.push(null)},n.destroy=c=>{if(!s)return s=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,o){let s=this._inflights.get(n.messageId);return s?(this._inflights.delete(n.messageId),o(null,s)):o&&o(new Error("missing packet")),this}get(n,o){let s=this._inflights.get(n.messageId);return s?o(null,s):o&&o(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};a.default=i}),nu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,i,n)=>{r.log("handlePublish: packet %o",i),n=typeof n<"u"?n:r.noop;let o=i.topic.toString(),s=i.payload,{qos:l}=i,{messageId:c}=i,{options:u}=r;if(r.options.protocolVersion===5){let h;if(i.properties&&(h=i.properties.topicAlias),typeof h<"u")if(o.length===0)if(h>0&&h<=65535){let p=r.topicAliasRecv.getTopicByAlias(h);if(p)o=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",o,h);else{r.log("handlePublish :: unregistered topic alias. alias: %d",h),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",h),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(o,h))r.log("handlePublish :: registered topic: %s - alias: %d",o,h);else{r.log("handlePublish :: topic alias out of range. alias: %d",h),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",l),l){case 2:{u.customHandleAcks(o,s,i,(h,p)=>{if(typeof h=="number"&&(p=h,h=null),h)return r.emit("error",h);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:p},n):r.incomingStore.put(i,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(o,s,i,(h,p)=>{if(typeof h=="number"&&(p=h,h=null),h)return r.emit("error",h);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",o,s,i),r.handleMessage(i,b=>{if(b)return n&&n(b);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",o,s,i),r.handleMessage(i,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};a.default=t}),iu=pe((a,e)=>{e.exports={version:"5.15.0"}}),$t=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0}),a.MQTTJS_VERSION=a.nextTick=a.ErrorWithSubackPacket=a.ErrorWithReasonCode=void 0,a.applyMixin=r;var e=class Aa extends Error{code;constructor(n,o){super(n),this.code=o,Object.setPrototypeOf(this,Aa.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};a.ErrorWithReasonCode=e;var t=class Ia extends Error{packet;constructor(n,o){super(n),this.packet=o,Object.setPrototypeOf(this,Ia.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};a.ErrorWithSubackPacket=t;function r(i,n,o=!1){let s=[n];for(;;){let l=s[0],c=Object.getPrototypeOf(l);if(c?.prototype)s.unshift(c);else break}for(let l of s)for(let c of Object.getOwnPropertyNames(l.prototype))(o||c!=="constructor")&&Object.defineProperty(i.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}a.nextTick=typeof Re?.nextTick=="function"?Re.nextTick:i=>{setTimeout(i,0)},a.MQTTJS_VERSION=iu().version}),qr=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0}),a.ReasonCodes=void 0;var e=$t();a.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var t=(r,i)=>{let{messageId:n}=i,o=i.cmd,s=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",o),o){case"pubcomp":case"puback":{let u=i.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${a.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,i)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{s={cmd:"pubrel",qos:2,messageId:n};let u=i.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${a.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,i)})):r._sendPacket(s);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=i.granted;for(let h=0;h<u.length;h++){let p=u[h];if((p&128)!==0){c=new Error(`Subscribe error: ${a.ReasonCodes[p]}`),c.code=p;let b=r.messageIdToTopic[n];b&&b.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),l(c,i);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,i);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};a.default=t}),ou=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=$t(),t=qr(),r=(i,n)=>{let{options:o}=i,s=o.protocolVersion,l=s===5?n.reasonCode:n.returnCode;if(s!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${s}`,l);i.emit("error",c);return}i.handleAuth(n,(c,u)=>{if(c){i.emit("error",c);return}if(l===24)i.reconnecting=!1,i._sendPacket(u);else{let h=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);i.emit("error",h)}})};a.default=r}),su=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0}),a.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof Re=="object"&&Re?Re:{},i=(b,f,g,y)=>{typeof r.emitWarning=="function"?r.emitWarning(b,f,g,y):console.error(`[${g}] ${f}: ${b}`)},n=globalThis.AbortController,o=globalThis.AbortSignal;if(typeof n>"u"){o=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(g,y){this._onabort.push(y)}},n=class{constructor(){f()}signal=new o;abort(g){if(!this.signal.aborted){this.signal.reason=g,this.signal.aborted=!0;for(let y of this.signal._onabort)y(g);this.signal.onabort?.(g)}}};let b=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{b&&(b=!1,i("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",f))}}var s=b=>!t.has(b),l=b=>b&&b===Math.floor(b)&&b>0&&isFinite(b),c=b=>l(b)?b<=Math.pow(2,8)?Uint8Array:b<=Math.pow(2,16)?Uint16Array:b<=Math.pow(2,32)?Uint32Array:b<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(b){super(b),this.fill(0)}},h=class Qt{heap;length;static#l=!1;static create(f){let g=c(f);if(!g)return[];Qt.#l=!0;let y=new Qt(f,g);return Qt.#l=!1,y}constructor(f,g){if(!Qt.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new g(f),this.length=0}push(f){this.heap[this.length++]=f}pop(){return this.heap[--this.length]}},p=class Ta{#l;#h;#m;#g;#O;#P;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#d;#a;#o;#y;#s;#v;#w;#f;#_;#A;#u;static unsafeExposeInternals(f){return{starts:f.#w,ttls:f.#f,sizes:f.#v,keyMap:f.#n,keyList:f.#r,valList:f.#e,next:f.#c,prev:f.#d,get head(){return f.#a},get tail(){return f.#o},free:f.#y,isBackgroundFetch:g=>f.#t(g),backgroundFetch:(g,y,w,m)=>f.#L(g,y,w,m),moveToTail:g=>f.#C(g),indexes:g=>f.#k(g),rindexes:g=>f.#x(g),isStale:g=>f.#p(g)}}get max(){return this.#l}get maxSize(){return this.#h}get calculatedSize(){return this.#b}get size(){return this.#i}get fetchMethod(){return this.#O}get memoMethod(){return this.#P}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(f){let{max:g=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:_,updateAgeOnHas:x,allowStale:v,dispose:E,disposeAfter:S,noDisposeOnSet:I,noUpdateTTL:O,maxSize:P=0,maxEntrySize:N=0,sizeCalculation:T,fetchMethod:q,memoMethod:D,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:V,ignoreFetchAbort:re}=f;if(g!==0&&!l(g))throw new TypeError("max option must be a nonnegative integer");let F=g?c(g):Array;if(!F)throw new Error("invalid max value: "+g);if(this.#l=g,this.#h=P,this.maxEntrySize=N||this.#h,this.sizeCalculation=T,this.sizeCalculation){if(!this.#h&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(D!==void 0&&typeof D!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#P=D,q!==void 0&&typeof q!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=q,this.#A=!!q,this.#n=new Map,this.#r=new Array(g).fill(void 0),this.#e=new Array(g).fill(void 0),this.#c=new F(g),this.#d=new F(g),this.#a=0,this.#o=0,this.#y=h.create(g),this.#i=0,this.#b=0,typeof E=="function"&&(this.#m=E),typeof S=="function"?(this.#g=S,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#_=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!O,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!V,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#h!==0&&!l(this.#h))throw new TypeError("maxSize must be a positive integer if specified");if(!l(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!ae,this.updateAgeOnGet=!!_,this.updateAgeOnHas=!!x,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=y||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#j()}if(this.#l===0&&this.ttl===0&&this.#h===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#l&&!this.#h){let Z="LRU_CACHE_UNBOUNDED";s(Z)&&(t.add(Z),i("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,Ta))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#j(){let f=new u(this.#l),g=new u(this.#l);this.#f=f,this.#w=g,this.#N=(m,_,x=e.now())=>{if(g[m]=_!==0?x:0,f[m]=_,_!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},_+1);v.unref&&v.unref()}},this.#I=m=>{g[m]=f[m]!==0?e.now():0},this.#E=(m,_)=>{if(f[_]){let x=f[_],v=g[_];if(!x||!v)return;m.ttl=x,m.start=v,m.now=y||w();let E=m.now-v;m.remainingTTL=x-E}};let y=0,w=()=>{let m=e.now();if(this.ttlResolution>0){y=m;let _=setTimeout(()=>y=0,this.ttlResolution);_.unref&&_.unref()}return m};this.getRemainingTTL=m=>{let _=this.#n.get(m);if(_===void 0)return 0;let x=f[_],v=g[_];if(!x||!v)return 1/0;let E=(y||w())-v;return x-E},this.#p=m=>{let _=g[m],x=f[m];return!!x&&!!_&&(y||w())-_>x}}#I=()=>{};#E=()=>{};#N=()=>{};#p=()=>!1;#$(){let f=new u(this.#l);this.#b=0,this.#v=f,this.#T=g=>{this.#b-=f[g],f[g]=0},this.#U=(g,y,w,m)=>{if(this.#t(y))return 0;if(!l(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(y,g),!l(w))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return w},this.#M=(g,y,w)=>{if(f[g]=y,this.#h){let m=this.#h-f[g];for(;this.#b>m;)this.#R(!0)}this.#b+=f[g],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=f=>{};#M=(f,g,y)=>{};#U=(f,g,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:f=this.allowStale}={}){if(this.#i)for(let g=this.#o;!(!this.#B(g)||((f||!this.#p(g))&&(yield g),g===this.#a));)g=this.#d[g]}*#x({allowStale:f=this.allowStale}={}){if(this.#i)for(let g=this.#a;!(!this.#B(g)||((f||!this.#p(g))&&(yield g),g===this.#o));)g=this.#c[g]}#B(f){return f!==void 0&&this.#n.get(this.#r[f])===f}*entries(){for(let f of this.#k())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*rentries(){for(let f of this.#x())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*keys(){for(let f of this.#k()){let g=this.#r[f];g!==void 0&&!this.#t(this.#e[f])&&(yield g)}}*rkeys(){for(let f of this.#x()){let g=this.#r[f];g!==void 0&&!this.#t(this.#e[f])&&(yield g)}}*values(){for(let f of this.#k())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}*rvalues(){for(let f of this.#x())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(f,g={}){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&f(m,this.#r[y],this))return this.get(this.#r[y],g)}}forEach(f,g=this){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(g,m,this.#r[y],this)}}rforEach(f,g=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(g,m,this.#r[y],this)}}purgeStale(){let f=!1;for(let g of this.#x({allowStale:!0}))this.#p(g)&&(this.#S(this.#r[g],"expire"),f=!0);return f}info(f){let g=this.#n.get(f);if(g===void 0)return;let y=this.#e[g],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let _=this.#f[g],x=this.#w[g];if(_&&x){let v=_-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[g]),m}dump(){let f=[];for(let g of this.#k({allowStale:!0})){let y=this.#r[g],w=this.#e[g],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||y===void 0)continue;let _={value:m};if(this.#f&&this.#w){_.ttl=this.#f[g];let x=e.now()-this.#w[g];_.start=Math.floor(Date.now()-x)}this.#v&&(_.size=this.#v[g]),f.unshift([y,_])}return f}load(f){this.clear();for(let[g,y]of f){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(g,y.value,y)}}set(f,g,y={}){if(g===void 0)return this.delete(f),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:_=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=y,{noUpdateTTL:E=this.noUpdateTTL}=y,S=this.#U(f,g,y.size||0,x);if(this.maxEntrySize&&S>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(f,"set"),this;let I=this.#i===0?void 0:this.#n.get(f);if(I===void 0)I=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#R(!1):this.#i,this.#r[I]=f,this.#e[I]=g,this.#n.set(f,I),this.#c[this.#o]=I,this.#d[I]=this.#o,this.#o=I,this.#i++,this.#M(I,S,v),v&&(v.set="add"),E=!1;else{this.#C(I);let O=this.#e[I];if(g!==O){if(this.#A&&this.#t(O)){O.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:P}=O;P!==void 0&&!_&&(this.#_&&this.#m?.(P,f,"set"),this.#u&&this.#s?.push([P,f,"set"]))}else _||(this.#_&&this.#m?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]));if(this.#T(I),this.#M(I,S,v),this.#e[I]=g,v){v.set="replace";let P=O&&this.#t(O)?O.__staleWhileFetching:O;P!==void 0&&(v.oldValue=P)}}else v&&(v.set="update")}if(w!==0&&!this.#f&&this.#j(),this.#f&&(E||this.#N(I,w,m),v&&this.#E(v,I)),!_&&this.#u&&this.#s){let O=this.#s,P;for(;P=O?.shift();)this.#g?.(...P)}return this}pop(){try{for(;this.#i;){let f=this.#e[this.#a];if(this.#R(!0),this.#t(f)){if(f.__staleWhileFetching)return f.__staleWhileFetching}else if(f!==void 0)return f}}finally{if(this.#u&&this.#s){let f=this.#s,g;for(;g=f?.shift();)this.#g?.(...g)}}}#R(f){let g=this.#a,y=this.#r[g],w=this.#e[g];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(g),f&&(this.#r[g]=void 0,this.#e[g]=void 0,this.#y.push(g)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[g],this.#n.delete(y),this.#i--,g}has(f,g={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=g,m=this.#n.get(f);if(m!==void 0){let _=this.#e[m];if(this.#t(_)&&_.__staleWhileFetching===void 0)return!1;if(this.#p(m))w&&(w.has="stale",this.#E(w,m));else return y&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(f,g={}){let{allowStale:y=this.allowStale}=g,w=this.#n.get(f);if(w===void 0||!y&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#L(f,g,y,w){let m=g===void 0?void 0:this.#e[g];if(this.#t(m))return m;let _=new n,{signal:x}=y;x?.addEventListener("abort",()=>_.abort(x.reason),{signal:_.signal});let v={signal:_.signal,options:y,context:w},E=(T,q=!1)=>{let{aborted:D}=_.signal,U=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(D&&!q?(y.status.fetchAborted=!0,y.status.fetchError=_.signal.reason,U&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),D&&!U&&!q)return I(_.signal.reason);let ae=P;return this.#e[g]===P&&(T===void 0?ae.__staleWhileFetching?this.#e[g]=ae.__staleWhileFetching:this.#S(f,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(f,T,v.options))),T},S=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:q}=_.signal,D=q&&y.allowStaleOnFetchAbort,U=D||y.allowStaleOnFetchRejection,ae=U||y.noDeleteOnFetchRejection,Y=P;if(this.#e[g]===P&&(!ae||Y.__staleWhileFetching===void 0?this.#S(f,"fetch"):D||(this.#e[g]=Y.__staleWhileFetching)),U)return y.status&&Y.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},O=(T,q)=>{let D=this.#O?.(f,m,v);D&&D instanceof Promise&&D.then(U=>T(U===void 0?void 0:U),q),_.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=U=>E(U,!0)))})};y.status&&(y.status.fetchDispatched=!0);let P=new Promise(O).then(E,S),N=Object.assign(P,{__abortController:_,__staleWhileFetching:m,__returned:void 0});return g===void 0?(this.set(f,N,{...v.options,status:void 0}),g=this.#n.get(f)):this.#e[g]=N,N}#t(f){if(!this.#A)return!1;let g=f;return!!g&&g instanceof Promise&&g.hasOwnProperty("__staleWhileFetching")&&g.__abortController instanceof n}async fetch(f,g={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:_=this.ttl,noDisposeOnSet:x=this.noDisposeOnSet,size:v=0,sizeCalculation:E=this.sizeCalculation,noUpdateTTL:S=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:O=this.allowStaleOnFetchRejection,ignoreFetchAbort:P=this.ignoreFetchAbort,allowStaleOnFetchAbort:N=this.allowStaleOnFetchAbort,context:T,forceRefresh:q=!1,status:D,signal:U}=g;if(!this.#A)return D&&(D.fetch="get"),this.get(f,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:D});let ae={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:_,noDisposeOnSet:x,size:v,sizeCalculation:E,noUpdateTTL:S,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:O,allowStaleOnFetchAbort:N,ignoreFetchAbort:P,status:D,signal:U},Y=this.#n.get(f);if(Y===void 0){D&&(D.fetch="miss");let V=this.#L(f,Y,ae,T);return V.__returned=V}else{let V=this.#e[Y];if(this.#t(V)){let M=y&&V.__staleWhileFetching!==void 0;return D&&(D.fetch="inflight",M&&(D.returnedStale=!0)),M?V.__staleWhileFetching:V.__returned=V}let re=this.#p(Y);if(!q&&!re)return D&&(D.fetch="hit"),this.#C(Y),w&&this.#I(Y),D&&this.#E(D,Y),V;let F=this.#L(f,Y,ae,T),Z=F.__staleWhileFetching!==void 0&&y;return D&&(D.fetch=re?"stale":"refresh",Z&&re&&(D.returnedStale=!0)),Z?F.__staleWhileFetching:F.__returned=F}}async forceFetch(f,g={}){let y=await this.fetch(f,g);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(f,g={}){let y=this.#P;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,..._}=g,x=this.get(f,_);if(!m&&x!==void 0)return x;let v=y(f,x,{options:_,context:w});return this.set(f,v,_),v}get(f,g={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:_}=g,x=this.#n.get(f);if(x!==void 0){let v=this.#e[x],E=this.#t(v);return _&&this.#E(_,x),this.#p(x)?(_&&(_.get="stale"),E?(_&&y&&v.__staleWhileFetching!==void 0&&(_.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(f,"expire"),_&&y&&(_.returnedStale=!0),y?v:void 0)):(_&&(_.get="hit"),E?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else _&&(_.get="miss")}#D(f,g){this.#d[g]=f,this.#c[f]=g}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#D(this.#d[f],this.#c[f]),this.#D(this.#o,f),this.#o=f)}delete(f){return this.#S(f,"delete")}#S(f,g){let y=!1;if(this.#i!==0){let w=this.#n.get(f);if(w!==void 0)if(y=!0,this.#i===1)this.#F(g);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(m,f,g),this.#u&&this.#s?.push([m,f,g])),this.#n.delete(f),this.#r[w]=void 0,this.#e[w]=void 0,w===this.#o)this.#o=this.#d[w];else if(w===this.#a)this.#a=this.#c[w];else{let _=this.#d[w];this.#c[_]=this.#c[w];let x=this.#c[w];this.#d[x]=this.#d[w]}this.#i--,this.#y.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.shift();)this.#g?.(...m)}return y}clear(){return this.#F("delete")}#F(f){for(let g of this.#x({allowStale:!0})){let y=this.#e[g];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let w=this.#r[g];this.#_&&this.#m?.(y,w,f),this.#u&&this.#s?.push([y,w,f])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#f&&this.#w&&(this.#f.fill(0),this.#w.fill(0)),this.#v&&this.#v.fill(0),this.#a=0,this.#o=0,this.#y.length=0,this.#b=0,this.#i=0,this.#u&&this.#s){let g=this.#s,y;for(;y=g?.shift();)this.#g?.(...y)}}};a.LRUCache=p}),ft=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.ContainerIterator=a.Container=a.Base=void 0;var e=class{constructor(i=0){this.iteratorType=i}equals(i){return this.o===i.o}};a.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};a.Base=t;var r=class extends t{};a.Container=r}),au=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=ft(),t=class extends e.Base{constructor(i=[]){super(),this.S=[];let n=this;i.forEach(function(o){n.push(o)})}clear(){this.i=0,this.S=[]}push(i){return this.S.push(i),this.i+=1,this.i}pop(){if(this.i!==0)return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}},r=t;a.default=r}),lu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=ft(),t=class extends e.Base{constructor(i=[]){super(),this.j=0,this.q=[];let n=this;i.forEach(function(o){n.push(o)})}clear(){this.q=[],this.i=this.j=0}push(i){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let o=this.i;for(let s=0;s<o;++s)this.q[s]=this.q[this.j+s];this.j=0,this.q[this.i]=i}else this.q[this.j+this.i]=i;return++this.i}pop(){if(this.i===0)return;let i=this.q[this.j++];return this.i-=1,i}front(){if(this.i!==0)return this.q[this.j]}},r=t;a.default=r}),cu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=ft(),t=class extends e.Base{constructor(i=[],n=function(s,l){return s>l?-1:s<l?1:0},o=!0){if(super(),this.v=n,Array.isArray(i))this.C=o?[...i]:i;else{this.C=[];let l=this;i.forEach(function(c){l.C.push(c)})}this.i=this.C.length;let s=this.i>>1;for(let l=this.i-1>>1;l>=0;--l)this.k(l,s)}m(i){let n=this.C[i];for(;i>0;){let o=i-1>>1,s=this.C[o];if(this.v(s,n)<=0)break;this.C[i]=s,i=o}this.C[i]=n}k(i,n){let o=this.C[i];for(;i<n;){let s=i<<1|1,l=s+1,c=this.C[s];if(l<this.i&&this.v(c,this.C[l])>0&&(s=l,c=this.C[l]),this.v(c,o)>=0)break;this.C[i]=c,i=s}this.C[i]=o}clear(){this.i=0,this.C.length=0}push(i){this.C.push(i),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let i=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),i}top(){return this.C[0]}find(i){return this.C.indexOf(i)>=0}remove(i){let n=this.C.indexOf(i);return n<0?!1:(n===0?this.pop():n===this.i-1?(this.C.pop(),this.i-=1):(this.C.splice(n,1,this.C.pop()),this.i-=1,this.m(n),this.k(n,this.i>>1)),!0)}updateItem(i){let n=this.C.indexOf(i);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;a.default=r}),co=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=ft(),t=class extends e.Container{},r=t;a.default=r}),pt=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),Ca=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.RandomIterator=void 0;var e=ft(),t=pt(),r=class extends e.ContainerIterator{constructor(i,n){super(n),this.o=i,this.iteratorType===0?(this.pre=function(){return this.o===0&&(0,t.throwIteratorAccessError)(),this.o-=1,this},this.next=function(){return this.o===this.container.size()&&(0,t.throwIteratorAccessError)(),this.o+=1,this}):(this.pre=function(){return this.o===this.container.size()-1&&(0,t.throwIteratorAccessError)(),this.o+=1,this},this.next=function(){return this.o===-1&&(0,t.throwIteratorAccessError)(),this.o-=1,this})}get pointer(){return this.container.getElementByPos(this.o)}set pointer(i){this.container.setElementByPos(this.o,i)}};a.RandomIterator=r}),uu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=r(co()),t=Ca();function r(s){return s&&s.t?s:{default:s}}var i=class Oa extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Oa(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(s=[],l=!0){if(super(),Array.isArray(s))this.J=l?[...s]:s,this.i=s.length;else{this.J=[];let c=this;s.forEach(function(u){c.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new i(0,this)}end(){return new i(this.i,this)}rBegin(){return new i(this.i-1,this,1)}rEnd(){return new i(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;return this.J[s]}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;return this.J.splice(s,1),this.i-=1,this.i}eraseElementByValue(s){let l=0;for(let c=0;c<this.i;++c)this.J[c]!==s&&(this.J[l++]=this.J[c]);return this.i=this.J.length=l,this.i}eraseElementByIterator(s){let l=s.o;return s=s.next(),this.eraseElementByPos(l),s}pushBack(s){return this.J.push(s),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(s,l){if(s<0||s>this.i-1)throw new RangeError;this.J[s]=l}insert(s,l,c=1){if(s<0||s>this.i)throw new RangeError;return this.J.splice(s,0,...new Array(c).fill(l)),this.i+=c,this.i}find(s){for(let l=0;l<this.i;++l)if(this.J[l]===s)return new i(l,this);return this.end()}reverse(){this.J.reverse()}unique(){let s=1;for(let l=1;l<this.i;++l)this.J[l]!==this.J[l-1]&&(this.J[s++]=this.J[l]);return this.i=this.J.length=s,this.i}sort(s){this.J.sort(s)}forEach(s){for(let l=0;l<this.i;++l)s(this.J[l],l,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},o=n;a.default=o}),hu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=i(co()),t=ft(),r=pt();function i(l){return l&&l.t?l:{default:l}}var n=class Pa extends t.ContainerIterator{constructor(c,u,h,p){super(p),this.o=c,this.h=u,this.container=h,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l}set pointer(c){this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l=c}copy(){return new Pa(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;l.forEach(function(u){c.pushBack(u)})}V(l){let{L:c,B:u}=l;c.B=u,u.L=c,l===this.p&&(this.p=u),l===this._&&(this._=c),this.i-=1}G(l,c){let u=c.B,h={l,L:c,B:u};c.B=h,u.L=h,c===this.h&&(this.p=h),u===this.h&&(this._=h),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return c.l}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return this.V(c),this.i}eraseElementByValue(l){let c=this.p;for(;c!==this.h;)c.l===l&&this.V(c),c=c.B;return this.i}eraseElementByIterator(l){let c=l.o;return c===this.h&&(0,r.throwIteratorAccessError)(),l=l.next(),this.V(c),l}pushBack(l){return this.G(l,this._),this.i}popBack(){if(this.i===0)return;let l=this._.l;return this.V(this._),l}pushFront(l){return this.G(l,this.h),this.i}popFront(){if(this.i===0)return;let l=this.p.l;return this.V(this.p),l}setElementByPos(l,c){if(l<0||l>this.i-1)throw new RangeError;let u=this.p;for(;l--;)u=u.B;u.l=c}insert(l,c,u=1){if(l<0||l>this.i)throw new RangeError;if(u<=0)return this.i;if(l===0)for(;u--;)this.pushFront(c);else if(l===this.i)for(;u--;)this.pushBack(c);else{let h=this.p;for(let b=1;b<l;++b)h=h.B;let p=h.B;for(this.i+=u;u--;)h.B={l:c,L:h},h.B.L=h,h=h.B;h.B=p,p.L=h}return this.i}find(l){let c=this.p;for(;c!==this.h;){if(c.l===l)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let l=this.p,c=this._,u=0;for(;u<<1<this.i;){let h=l.l;l.l=c.l,c.l=h,l=l.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let l=this.p;for(;l!==this.h;){let c=l;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;l.B=c.B,l.B.L=l,l=l.B}return this.i}sort(l){if(this.i<=1)return;let c=[];this.forEach(function(h){c.push(h)}),c.sort(l);let u=this.p;c.forEach(function(h){u.l=h,u=u.B})}merge(l){let c=this;if(this.i===0)l.forEach(function(u){c.pushBack(u)});else{let u=this.p;l.forEach(function(h){for(;u!==c.h&&u.l<=h;)u=u.B;c.G(h,u.L)})}return this.i}forEach(l){let c=this.p,u=0;for(;c!==this.h;)l(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let l=this.p;for(;l!==this.h;)yield l.l,l=l.B}).bind(this)()}},s=o;a.default=s}),du=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=r(co()),t=Ca();function r(s){return s&&s.t?s:{default:s}}var i=class Ma extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Ma(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(s=[],l=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof s.length=="number")return s.length;if(typeof s.size=="number")return s.size;if(typeof s.size=="function")return s.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=l,this.P=Math.max(Math.ceil(c/this.F),1);for(let p=0;p<this.P;++p)this.A.push(new Array(this.F));let u=Math.ceil(c/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-c%this.F>>1;let h=this;s.forEach(function(p){h.pushBack(p)})}T(){let s=[],l=Math.max(this.P>>1,1);for(let c=0;c<l;++c)s[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)s[s.length]=this.A[c];for(let c=0;c<this.R;++c)s[s.length]=this.A[c];s[s.length]=[...this.A[this.R]],this.j=l,this.R=s.length-1;for(let c=0;c<l;++c)s[s.length]=new Array(this.F);this.A=s,this.P=s.length}O(s){let l=this.D+s+1,c=l%this.F,u=c-1,h=this.j+(l-c)/this.F;return c===0&&(h-=1),h%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:h,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new i(0,this)}end(){return new i(this.i,this)}rBegin(){return new i(this.i-1,this,1)}rEnd(){return new i(-1,this,1)}front(){if(this.i!==0)return this.A[this.j][this.D]}back(){if(this.i!==0)return this.A[this.R][this.N]}pushBack(s){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]=s,this.i}popBack(){if(this.i===0)return;let s=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,s}pushFront(s){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]=s,this.i}popFront(){if(this.i===0)return;let s=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,s}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(s);return this.A[l][c]}setElementByPos(s,l){if(s<0||s>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(s);this.A[c][u]=l}insert(s,l,c=1){if(s<0||s>this.i)throw new RangeError;if(s===0)for(;c--;)this.pushFront(l);else if(s===this.i)for(;c--;)this.pushBack(l);else{let u=[];for(let h=s;h<this.i;++h)u.push(this.getElementByPos(h));this.cut(s-1);for(let h=0;h<c;++h)this.pushBack(l);for(let h=0;h<u.length;++h)this.pushBack(u[h])}return this.i}cut(s){if(s<0)return this.clear(),0;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(s);return this.R=l,this.N=c,this.i=s+1,this.i}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;if(s===0)this.popFront();else if(s===this.i-1)this.popBack();else{let l=[];for(let u=s+1;u<this.i;++u)l.push(this.getElementByPos(u));this.cut(s),this.popBack();let c=this;l.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(s){if(this.i===0)return 0;let l=[];for(let u=0;u<this.i;++u){let h=this.getElementByPos(u);h!==s&&l.push(h)}let c=l.length;for(let u=0;u<c;++u)this.setElementByPos(u,l[u]);return this.cut(c-1)}eraseElementByIterator(s){let l=s.o;return this.eraseElementByPos(l),s=s.next(),s}find(s){for(let l=0;l<this.i;++l)if(this.getElementByPos(l)===s)return new i(l,this);return this.end()}reverse(){let s=0,l=this.i-1;for(;s<l;){let c=this.getElementByPos(s);this.setElementByPos(s,this.getElementByPos(l)),this.setElementByPos(l,c),s+=1,l-=1}}unique(){if(this.i<=1)return this.i;let s=1,l=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==l&&(l=u,this.setElementByPos(s++,u))}for(;this.i>s;)this.popBack();return this.i}sort(s){let l=[];for(let c=0;c<this.i;++c)l.push(this.getElementByPos(c));l.sort(s);for(let c=0;c<this.i;++c)this.setElementByPos(c,l[c])}shrinkToFit(){if(this.i===0)return;let s=[];this.forEach(function(l){s.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<s.length;++l)this.pushBack(s[l])}forEach(s){for(let l=0;l<this.i;++l)s(this.getElementByPos(l),l,this)}[Symbol.iterator](){return(function*(){for(let s=0;s<this.i;++s)yield this.getElementByPos(s)}).bind(this)()}},o=n;a.default=o}),fu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.TreeNodeEnableIndex=a.TreeNode=void 0;var e=class{constructor(r,i){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=r,this.l=i}L(){let r=this;if(r.ee===1&&r.tt.tt===r)r=r.W;else if(r.U)for(r=r.U;r.W;)r=r.W;else{let i=r.tt;for(;i.U===r;)r=i,i=r.tt;r=i}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let i=r.tt;for(;i.W===r;)r=i,i=r.tt;return r.W!==i?i:r}}te(){let r=this.tt,i=this.W,n=i.U;return r.tt===this?r.tt=i:r.U===this?r.U=i:r.W=i,i.tt=r,i.U=this,this.tt=i,this.W=n,n&&(n.tt=this),i}se(){let r=this.tt,i=this.U,n=i.W;return r.tt===this?r.tt=i:r.U===this?r.U=i:r.W=i,i.tt=r,i.W=this,this.tt=i,this.U=n,n&&(n.tt=this),i}};a.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)}};a.TreeNodeEnableIndex=t}),Ra=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=fu(),t=ft(),r=pt(),i=class extends t.Container{constructor(o=function(l,c){return l<c?-1:l>c?1:0},s=!1){super(),this.Y=void 0,this.v=o,s?(this.re=e.TreeNodeEnableIndex,this.M=function(l,c,u){let h=this.ne(l,c,u);if(h){let p=h.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let b=this.he(h);if(b){let{parentNode:f,grandParent:g,curNode:y}=b;f.ie(),g.ie(),y.ie()}}return this.i},this.V=function(l){let c=this.fe(l);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(l,c,u){let h=this.ne(l,c,u);return h&&this.he(h),this.i},this.V=this.fe),this.h=new this.re}X(o,s){let l=this.h;for(;o;){let c=this.v(o.u,s);if(c<0)o=o.W;else if(c>0)l=o,o=o.U;else return o}return l}Z(o,s){let l=this.h;for(;o;)this.v(o.u,s)<=0?o=o.W:(l=o,o=o.U);return l}$(o,s){let l=this.h;for(;o;){let c=this.v(o.u,s);if(c<0)l=o,o=o.W;else if(c>0)o=o.U;else return o}return l}rr(o,s){let l=this.h;for(;o;)this.v(o.u,s)<0?(l=o,o=o.W):o=o.U;return l}ue(o){for(;;){let s=o.tt;if(s===this.h)return;if(o.ee===1){o.ee=0;return}if(o===s.U){let l=s.W;if(l.ee===1)l.ee=0,s.ee=1,s===this.Y?this.Y=s.te():s.te();else if(l.W&&l.W.ee===1){l.ee=s.ee,s.ee=0,l.W.ee=0,s===this.Y?this.Y=s.te():s.te();return}else l.U&&l.U.ee===1?(l.ee=1,l.U.ee=0,l.se()):(l.ee=1,o=s)}else{let l=s.U;if(l.ee===1)l.ee=0,s.ee=1,s===this.Y?this.Y=s.se():s.se();else if(l.U&&l.U.ee===1){l.ee=s.ee,s.ee=0,l.U.ee=0,s===this.Y?this.Y=s.se():s.se();return}else l.W&&l.W.ee===1?(l.ee=1,l.W.ee=0,l.te()):(l.ee=1,o=s)}}}fe(o){if(this.i===1)return this.clear(),this.h;let s=o;for(;s.U||s.W;){if(s.W)for(s=s.W;s.U;)s=s.U;else s=s.U;[o.u,s.u]=[s.u,o.u],[o.l,s.l]=[s.l,o.l],o=s}this.h.U===s?this.h.U=s.tt:this.h.W===s&&(this.h.W=s.tt),this.ue(s);let l=s.tt;return s===l.U?l.U=void 0:l.W=void 0,this.i-=1,this.Y.ee=0,l}oe(o,s){return o===void 0?!1:this.oe(o.U,s)||s(o)?!0:this.oe(o.W,s)}he(o){for(;;){let s=o.tt;if(s.ee===0)return;let l=s.tt;if(s===l.U){let c=l.W;if(c&&c.ee===1){if(c.ee=s.ee=0,l===this.Y)return;l.ee=1,o=l;continue}else if(o===s.W){if(o.ee=0,o.U&&(o.U.tt=s),o.W&&(o.W.tt=l),s.W=o.U,l.U=o.W,o.U=s,o.W=l,l===this.Y)this.Y=o,this.h.tt=o;else{let u=l.tt;u.U===l?u.U=o:u.W=o}return o.tt=l.tt,s.tt=o,l.tt=o,l.ee=1,{parentNode:s,grandParent:l,curNode:o}}else s.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=s.ee=0,l===this.Y)return;l.ee=1,o=l;continue}else if(o===s.U){if(o.ee=0,o.U&&(o.U.tt=l),o.W&&(o.W.tt=s),l.W=o.U,s.U=o.W,o.U=l,o.W=s,l===this.Y)this.Y=o,this.h.tt=o;else{let u=l.tt;u.U===l?u.U=o:u.W=o}return o.tt=l.tt,s.tt=o,l.tt=o,l.ee=1,{parentNode:s,grandParent:l,curNode:o}}else s.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(o,s,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(o,s),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let c,u=this.h.U,h=this.v(u.u,o);if(h===0){u.l=s;return}else if(h>0)u.U=new this.re(o,s),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,b=this.v(p.u,o);if(b===0){p.l=s;return}else if(b<0)p.W=new this.re(o,s),p.W.tt=p,c=p.W,this.h.W=c;else{if(l!==void 0){let f=l.o;if(f!==this.h){let g=this.v(f.u,o);if(g===0){f.l=s;return}else if(g>0){let y=f.L(),w=this.v(y.u,o);if(w===0){y.l=s;return}else w<0&&(c=new this.re(o,s),y.W===void 0?(y.W=c,c.tt=y):(f.U=c,c.tt=f))}}}if(c===void 0)for(c=this.Y;;){let f=this.v(c.u,o);if(f>0){if(c.U===void 0){c.U=new this.re(o,s),c.U.tt=c,c=c.U;break}c=c.U}else if(f<0){if(c.W===void 0){c.W=new this.re(o,s),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=s;return}}}}return this.i+=1,c}I(o,s){for(;o;){let l=this.v(o.u,s);if(l<0)o=o.W;else if(l>0)o=o.U;else return o}return o||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(o,s){let l=o.o;if(l===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return l.u=s,!0;if(l===this.h.U)return this.v(l.B().u,s)>0?(l.u=s,!0):!1;if(l===this.h.W)return this.v(l.L().u,s)<0?(l.u=s,!0):!1;let c=l.L().u;if(this.v(c,s)>=0)return!1;let u=l.B().u;return this.v(u,s)<=0?!1:(l.u=s,!0)}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let s=0,l=this;return this.oe(this.Y,function(c){return o===s?(l.V(c),!0):(s+=1,!1)}),this.i}eraseElementByKey(o){if(this.i===0)return!1;let s=this.I(this.Y,o);return s===this.h?!1:(this.V(s),!0)}eraseElementByIterator(o){let s=o.o;s===this.h&&(0,r.throwIteratorAccessError)();let l=s.W===void 0;return o.iteratorType===0?l&&o.next():(!l||s.U===void 0)&&o.next(),this.V(s),o}forEach(o){let s=0;for(let l of this)o(l,s++,this)}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let s,l=0;for(let c of this){if(l===o){s=c;break}l+=1}return s}getHeight(){if(this.i===0)return 0;let o=function(s){return s?Math.max(o(s.U),o(s.W))+1:0};return o(this.Y)}},n=i;a.default=n}),La=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=ft(),t=pt(),r=class extends e.ContainerIterator{constructor(n,o,s){super(s),this.o=n,this.h=o,this.iteratorType===0?(this.pre=function(){return this.o===this.h.U&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this}):(this.pre=function(){return this.o===this.h.W&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this})}get index(){let n=this.o,o=this.h.tt;if(n===this.h)return o?o.rt-1:0;let s=0;for(n.U&&(s+=n.U.rt);n!==o;){let l=n.tt;n===l.W&&(s+=1,l.U&&(s+=l.U.rt)),n=l}return s}},i=r;a.default=i}),pu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=i(Ra()),t=i(La()),r=pt();function i(l){return l&&l.t?l:{default:l}}var n=class ja extends t.default{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new ja(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[],c,u){super(c,u);let h=this;l.forEach(function(p){h.insert(p)})}*K(l){l!==void 0&&(yield*this.K(l.U),yield l.u,yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(l,c){return this.M(l,void 0,c)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}union(l){let c=this;return l.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},s=o;a.default=s}),mu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=i(Ra()),t=i(La()),r=pt();function i(l){return l&&l.t?l:{default:l}}var n=class Na extends t.default{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,h){if(h==="0")return c.o.u;if(h==="1")return c.o.l},set(u,h,p){if(h!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new Na(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[],c,u){super(c,u);let h=this;l.forEach(function(p){h.setElement(p[0],p[1])})}*K(l){l!==void 0&&(yield*this.K(l.U),yield[l.u,l.l],yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i===0)return;let l=this.h.U;return[l.u,l.l]}back(){if(this.i===0)return;let l=this.h.W;return[l.u,l.l]}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}setElement(l,c,u){return this.M(l,c,u)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}getElementByKey(l){return this.I(this.Y,l).l}union(l){let c=this;return l.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},s=o;a.default=s}),Ua=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),Ba=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.HashContainerIterator=a.HashContainer=void 0;var e=ft(),t=i(Ua()),r=pt();function i(s){return s&&s.t?s:{default:s}}var n=class extends e.ContainerIterator{constructor(s,l,c){super(c),this.o=s,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})}};a.HashContainerIterator=n;var o=class extends e.Container{constructor(){super(),this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(s){let{L:l,B:c}=s;l.B=c,c.L=l,s===this.p&&(this.p=c),s===this._&&(this._=l),this.i-=1}M(s,l,c){c===void 0&&(c=(0,t.default)(s));let u;if(c){let h=s[this.HASH_TAG];if(h!==void 0)return this.H[h].l=l,this.i;Object.defineProperty(s,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:s,l,L:this._,B:this.h},this.H.push(u)}else{let h=this.g[s];if(h)return h.l=l,this.i;u={u:s,l,L:this._,B:this.h},this.g[s]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(s,l){if(l===void 0&&(l=(0,t.default)(s)),l){let c=s[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[s]||this.h}clear(){let s=this.HASH_TAG;this.H.forEach(function(l){delete l.u[s]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(s,l){let c;if(l===void 0&&(l=(0,t.default)(s)),l){let u=s[this.HASH_TAG];if(u===void 0)return!1;delete s[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[s],c===void 0)return!1;delete this.g[s]}return this.V(c),!0}eraseElementByIterator(s){let l=s.o;return l===this.h&&(0,r.throwIteratorAccessError)(),this.V(l),s.next()}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let l=this.p;for(;s--;)l=l.B;return this.V(l),this.i}};a.HashContainer=o}),gu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=Ba(),t=pt(),r=class Da extends e.HashContainerIterator{constructor(s,l,c,u){super(s,l,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new Da(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(o=[]){super();let s=this;o.forEach(function(l){s.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(o,s){return this.M(o,void 0,s)}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let s=this.p;for(;o--;)s=s.B;return s.u}find(o,s){let l=this.I(o,s);return new r(l,this.h,this)}forEach(o){let s=0,l=this.p;for(;l!==this.h;)o(l.u,s++,this),l=l.B}[Symbol.iterator](){return(function*(){let o=this.p;for(;o!==this.h;)yield o.u,o=o.B}).bind(this)()}},n=i;a.default=n}),bu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),a.default=void 0;var e=Ba(),t=i(Ua()),r=pt();function i(l){return l&&l.t?l:{default:l}}var n=class Fa extends e.HashContainerIterator{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,h){if(h==="0")return c.o.u;if(h==="1")return c.o.l},set(u,h,p){if(h!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new Fa(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.HashContainer{constructor(l=[]){super();let c=this;l.forEach(function(u){c.setElement(u[0],u[1])})}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i!==0)return[this.p.u,this.p.l]}back(){if(this.i!==0)return[this._.u,this._.l]}setElement(l,c,u){return this.M(l,c,u)}getElementByKey(l,c){if(c===void 0&&(c=(0,t.default)(l)),c){let h=l[this.HASH_TAG];return h!==void 0?this.H[h].l:void 0}let u=this.g[l];return u?u.l:void 0}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return[c.u,c.l]}find(l,c){let u=this.I(l,c);return new n(u,this.h,this)}forEach(l){let c=0,u=this.p;for(;u!==this.h;)l([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let l=this.p;for(;l!==this.h;)yield[l.u,l.l],l=l.B}).bind(this)()}},s=o;a.default=s}),yu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"t",{value:!0}),Object.defineProperty(a,"Deque",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(a,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(a,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(a,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(a,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(a,"OrderedSet",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(a,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(a,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(a,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(a,"Vector",{enumerable:!0,get:function(){return i.default}});var e=h(au()),t=h(lu()),r=h(cu()),i=h(uu()),n=h(hu()),o=h(du()),s=h(pu()),l=h(mu()),c=h(gu()),u=h(bu());function h(p){return p&&p.t?p:{default:p}}}),vu=pe((a,e)=>{le(),ue(),ce();var t=yu().OrderedSet,r=ht()("number-allocator:trace"),i=ht()("number-allocator:error");function n(s,l){this.low=s,this.high=l}n.prototype.equals=function(s){return this.low===s.low&&this.high===s.high},n.prototype.compare=function(s){return this.low<s.low&&this.high<s.low?-1:s.low<this.low&&s.high<this.low?1:0};function o(s,l){if(!(this instanceof o))return new o(s,l);this.min=s,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}o.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},o.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let s=this.ss.begin(),l=s.pointer.low,c=s.pointer.high,u=l;return u+1<=c?this.ss.updateKeyByIterator(s,new n(l+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},o.prototype.use=function(s){let l=new n(s,s),c=this.ss.lowerBound(l);if(!c.equals(this.ss.end())){let u=c.pointer.low,h=c.pointer.high;return c.pointer.equals(l)?(this.ss.eraseElementByIterator(c),r("use():"+s),!0):u>s?!1:u===s?(this.ss.updateKeyByIterator(c,new n(u+1,h)),r("use():"+s),!0):h===s?(this.ss.updateKeyByIterator(c,new n(u,h-1)),r("use():"+s),!0):(this.ss.updateKeyByIterator(c,new n(s+1,h)),this.ss.insert(new n(u,s-1)),r("use():"+s),!0)}return r("use():failed"),!1},o.prototype.free=function(s){if(s<this.min||s>this.max){i("free():"+s+" is out of range");return}let l=new n(s,s),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===s?this.ss.updateKeyByIterator(c,new n(u,s)):this.ss.insert(l)}else if(c.equals(this.ss.begin()))if(s+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(s,u))}else this.ss.insert(l);else{let u=c.pointer.low,h=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===s?s+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,h))):this.ss.updateKeyByIterator(c,new n(p,s)):s+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(s,h))):this.ss.insert(l)}r("free():"+s)},o.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},o.prototype.intervalCount=function(){return this.ss.size()},o.prototype.dump=function(){console.log("length:"+this.ss.size());for(let s of this.ss)console.log(s)},e.exports=o}),$a=pe((a,e)=>{le(),ue(),ce();var t=vu();e.exports.NumberAllocator=t}),wu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=su(),t=$a(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(i){i>0&&(this.aliasToTopic=new e.LRUCache({max:i}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,i),this.max=i,this.length=0)}put(i,n){if(n===0||n>this.max)return!1;let o=this.aliasToTopic.get(n);return o&&delete this.topicToAlias[o],this.aliasToTopic.set(n,i),this.topicToAlias[i]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(i){return this.aliasToTopic.get(i)}getAliasByTopic(i){let n=this.topicToAlias[i];return typeof n<"u"&&this.aliasToTopic.get(n),n}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){return this.numberAllocator.firstVacant()||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}};a.default=r}),_u=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(a,"__esModule",{value:!0});var t=qr(),r=e(wu()),i=$t(),n=(o,s)=>{o.log("_handleConnack");let{options:l}=o,c=l.protocolVersion===5?s.reasonCode:s.returnCode;if(clearTimeout(o.connackTimer),delete o.topicAliasSend,s.properties){if(s.properties.topicAliasMaximum){if(s.properties.topicAliasMaximum>65535){o.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}s.properties.topicAliasMaximum>0&&(o.topicAliasSend=new r.default(s.properties.topicAliasMaximum))}s.properties.serverKeepAlive&&l.keepalive&&(l.keepalive=s.properties.serverKeepAlive),s.properties.maximumPacketSize&&(l.properties||(l.properties={}),l.properties.maximumPacketSize=s.properties.maximumPacketSize)}if(c===0)o.reconnecting=!1,o._onConnect(s);else if(c>0){let u=new i.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);o.emit("error",u),o.options.reconnectOnConnackError&&o._cleanUp(!0)}};a.default=n}),ku=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=(t,r,i)=>{t.log("handling pubrel packet");let n=typeof i<"u"?i:t.noop,{messageId:o}=r,s={cmd:"pubcomp",messageId:o};t.incomingStore.get(r,(l,c)=>{l?t._sendPacket(s,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(s,n)}))})};a.default=e}),xu=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(a,"__esModule",{value:!0});var t=e(nu()),r=e(ou()),i=e(_u()),n=e(qr()),o=e(ku()),s=(l,c,u)=>{let{options:h}=l;if(h.protocolVersion===5&&h.properties&&h.properties.maximumPacketSize&&h.properties.maximumPacketSize<c.length)return l.emit("error",new Error(`exceeding packets size ${c.cmd}`)),l.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),l;switch(l.log("_handlePacket :: emitting packetreceive"),l.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(l,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":l.reschedulePing(),(0,n.default)(l,c),u();break;case"pubrel":l.reschedulePing(),(0,o.default)(l,c,u);break;case"connack":(0,i.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}};a.default=s}),qa=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__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(){}};a.default=e}),Su=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__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={}}};a.default=e}),Eu=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(a,"__esModule",{value:!0}),a.TypedEventEmitter=void 0;var t=e((Ct(),Pe(wt))),r=$t(),i=class{};a.TypedEventEmitter=i,(0,r.applyMixin)(i,t.default)}),Hr=pe((a,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Au=pe((a,e)=>{le(),ue(),ce();var t=Hr().default;function r(i,n){if(t(i)!="object"||!i)return i;var o=i[Symbol.toPrimitive];if(o!==void 0){var s=o.call(i,n||"default");if(t(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(i)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Iu=pe((a,e)=>{le(),ue(),ce();var t=Hr().default,r=Au();function i(n){var o=r(n,"string");return t(o)=="symbol"?o:o+""}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),Tu=pe((a,e)=>{le(),ue(),ce();var t=Iu();function r(i,n,o){return(n=t(n))in i?Object.defineProperty(i,n,{value:o,enumerable:!0,configurable:!0,writable:!0}):i[n]=o,i}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Cu=pe((a,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}),Ou=pe((a,e)=>{le(),ue(),ce();function t(r,i){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var o,s,l,c,u=[],h=!0,p=!1;try{if(l=(n=n.call(r)).next,i===0){if(Object(n)!==n)return;h=!1}else for(;!(h=(o=l.call(n)).done)&&(u.push(o.value),u.length!==i);h=!0);}catch(b){p=!0,s=b}finally{try{if(!h&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw s}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Pu=pe((a,e)=>{le(),ue(),ce();function t(r,i){(i==null||i>r.length)&&(i=r.length);for(var n=0,o=Array(i);n<i;n++)o[n]=r[n];return o}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Mu=pe((a,e)=>{le(),ue(),ce();var t=Pu();function r(i,n){if(i){if(typeof i=="string")return t(i,n);var o={}.toString.call(i).slice(8,-1);return o==="Object"&&i.constructor&&(o=i.constructor.name),o==="Map"||o==="Set"?Array.from(i):o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?t(i,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ru=pe((a,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}),Lu=pe((a,e)=>{le(),ue(),ce();var t=Cu(),r=Ou(),i=Mu(),n=Ru();function o(s,l){return t(s)||r(s,l)||i(s,l)||n()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Ha=pe((a,e)=>{le(),ue(),ce(),(function(t,r){typeof a=="object"&&typeof e<"u"?r(a):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(a,function(t){var r=function(b){return function(f){var g=b(f);return f.add(g),g}},i=function(b){return function(f,g){return b.set(f,g),g}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,s=o*2,l=function(b,f){return function(g){var y=f.get(g),w=y===void 0?g.size:y<s?y+1:0;if(!g.has(w))return b(g,w);if(g.size<o){for(;g.has(w);)w=Math.floor(Math.random()*s);return b(g,w)}if(g.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;g.has(w);)w=Math.floor(Math.random()*n);return b(g,w)}},c=new WeakMap,u=i(c),h=l(u,c),p=r(h);t.addUniqueNumber=p,t.generateUniqueNumber=h})}),ju=pe((a,e)=>{le(),ue(),ce();function t(i,n,o,s,l,c,u){try{var h=i[c](u),p=h.value}catch(b){return void o(b)}h.done?n(p):Promise.resolve(p).then(s,l)}function r(i){return function(){var n=this,o=arguments;return new Promise(function(s,l){var c=i.apply(n,o);function u(p){t(c,s,l,u,h,"next",p)}function h(p){t(c,s,l,u,h,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Wa=pe((a,e)=>{le(),ue(),ce();function t(r,i){this.v=r,this.k=i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),za=pe((a,e)=>{le(),ue(),ce();function t(r,i,n,o){var s=Object.defineProperty;try{s({},"",{})}catch{s=0}e.exports=t=function(l,c,u,h){function p(b,f){t(l,b,function(g){return this._invoke(b,f,g)})}c?s?s(l,c,{value:u,enumerable:!h,configurable:!h,writable:!h}):l[c]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,i,n,o)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Va=pe((a,e)=>{le(),ue(),ce();var t=za();function r(){var i,n,o=typeof Symbol=="function"?Symbol:{},s=o.iterator||"@@iterator",l=o.toStringTag||"@@toStringTag";function c(w,m,_,x){var v=m&&m.prototype instanceof h?m:h,E=Object.create(v.prototype);return t(E,"_invoke",(function(S,I,O){var P,N,T,q=0,D=O||[],U=!1,ae={p:0,n:0,v:i,a:Y,f:Y.bind(i,4),d:function(V,re){return P=V,N=0,T=i,ae.n=re,u}};function Y(V,re){for(N=V,T=re,n=0;!U&&q&&!F&&n<D.length;n++){var F,Z=D[n],M=ae.p,J=Z[2];V>3?(F=J===re)&&(T=Z[(N=Z[4])?5:(N=3,3)],Z[4]=Z[5]=i):Z[0]<=M&&((F=V<2&&M<Z[1])?(N=0,ae.v=re,ae.n=Z[1]):M<J&&(F=V<3||Z[0]>re||re>J)&&(Z[4]=V,Z[5]=re,ae.n=J,N=0))}if(F||V>1)return u;throw U=!0,re}return function(V,re,F){if(q>1)throw TypeError("Generator is already running");for(U&&re===1&&Y(re,F),N=re,T=F;(n=N<2?i:T)||!U;){P||(N?N<3?(N>1&&(ae.n=-1),Y(N,T)):ae.n=T:ae.v=T);try{if(q=2,P){if(N||(V="next"),n=P[V]){if(!(n=n.call(P,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,N<2&&(N=0)}else N===1&&(n=P.return)&&n.call(P),N<2&&(T=TypeError("The iterator does not provide a '"+V+"' method"),N=1);P=i}else if((n=(U=ae.n<0)?T:S.call(I,ae))!==u)break}catch(Z){P=i,N=1,T=Z}finally{q=1}}return{value:n,done:U}}})(w,_,x),!0),E}var u={};function h(){}function p(){}function b(){}n=Object.getPrototypeOf;var f=[][s]?n(n([][s]())):(t(n={},s,function(){return this}),n),g=b.prototype=h.prototype=Object.create(f);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,b):(w.__proto__=b,t(w,l,"GeneratorFunction")),w.prototype=Object.create(g),w}return p.prototype=b,t(g,"constructor",b),t(b,"constructor",p),p.displayName="GeneratorFunction",t(b,l,"GeneratorFunction"),t(g),t(g,l,"Generator"),t(g,s,function(){return this}),t(g,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ga=pe((a,e)=>{le(),ue(),ce();var t=Wa(),r=za();function i(n,o){function s(c,u,h,p){try{var b=n[c](u),f=b.value;return f instanceof t?o.resolve(f.v).then(function(g){s("next",g,h,p)},function(g){s("throw",g,h,p)}):o.resolve(f).then(function(g){b.value=g,h(b)},function(g){return s("throw",g,h,p)})}catch(g){p(g)}}var l;this.next||(r(i.prototype),r(i.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,h){function p(){return new o(function(b,f){s(c,h,b,f)})}return l=l?l.then(p,p):p()},!0)}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),Ka=pe((a,e)=>{le(),ue(),ce();var t=Va(),r=Ga();function i(n,o,s,l,c){return new r(t().w(n,o,s,l),c||Promise)}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),Nu=pe((a,e)=>{le(),ue(),ce();var t=Ka();function r(i,n,o,s,l){var c=t(i,n,o,s,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}),Uu=pe((a,e)=>{le(),ue(),ce();function t(r){var i=Object(r),n=[];for(var o in i)n.unshift(o);return function s(){for(;n.length;)if((o=n.pop())in i)return s.value=o,s.done=!1,s;return s.done=!0,s}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Bu=pe((a,e)=>{le(),ue(),ce();var t=Hr().default;function r(i){if(i!=null){var n=i[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],o=0;if(n)return n.call(i);if(typeof i.next=="function")return i;if(!isNaN(i.length))return{next:function(){return i&&o>=i.length&&(i=void 0),{value:i&&i[o++],done:!i}}}}throw new TypeError(t(i)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Du=pe((a,e)=>{le(),ue(),ce();var t=Wa(),r=Va(),i=Nu(),n=Ka(),o=Ga(),s=Uu(),l=Bu();function c(){var u=r(),h=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(h):h.__proto__).constructor;function b(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function g(y){var w,m;return function(_){w||(w={stop:function(){return m(_.a,2)},catch:function(){return _.v},abrupt:function(x,v){return m(_.a,f[x],v)},delegateYield:function(x,v,E){return w.resultName=v,m(_.d,l(x),E)},finish:function(x){return m(_.f,x)}},m=function(x,v,E){_.p=w.prev,_.n=w.next;try{return x(v,E)}finally{w.next=_.n}}),w.resultName&&(w[w.resultName]=_.v,w.resultName=void 0),w.sent=_.v,w.next=_.n;try{return y.call(this,w)}finally{_.p=w.prev,_.n=w.next}}}return(e.exports=c=function(){return{wrap:function(y,w,m,_){return u.w(g(y),w,m,_&&_.reverse())},isGeneratorFunction:b,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:o,async:function(y,w,m,_,x){return(b(w)?n:i)(g(y),w,m,_,x)},keys:s,values:l}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),Fu=pe((a,e)=>{le(),ue(),ce();var t=Du()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),$u=pe((a,e)=>{le(),ue(),ce(),(function(t,r){typeof a=="object"&&typeof e<"u"?r(a,Tu(),Lu(),Ha(),ju(),Fu()):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))})(a,function(t,r,i,n,o,s){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,_){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);_&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function h(m){for(var _=1;_<arguments.length;_++){var x=arguments[_]!=null?arguments[_]:{};_%2?u(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):u(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var p=function(m){return h(h({},m),{},{connect:function(_){var x=_.call;return o(s.mark(function v(){var E,S,I,O;return s.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:return E=new MessageChannel,S=E.port1,I=E.port2,P.next=1,x("connect",{port:S},[S]);case 1:return O=P.sent,c.set(I,O),P.abrupt("return",I);case 2:case"end":return P.stop()}},v)}))},disconnect:function(_){var x=_.call;return(function(){var v=o(s.mark(function E(S){var I;return s.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:if(I=c.get(S),I!==void 0){O.next=1;break}throw new Error("The given port is not connected.");case 1:return O.next=2,x("disconnect",{portId:I});case 2:case"end":return O.stop()}},E)}));return function(E){return v.apply(this,arguments)}})()},isSupported:function(_){var x=_.call;return function(){return x("isSupported")}}})};function b(m,_){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);_&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function f(m){for(var _=1;_<arguments.length;_++){var x=arguments[_]!=null?arguments[_]:{};_%2?b(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):b(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var g=new WeakMap,y=function(m){if(g.has(m))return g.get(m);var _=new Map;return g.set(m,_),_},w=function(m){var _=p(m);return function(x){var v=y(x);x.addEventListener("message",function(D){var U=D.data,ae=U.id;if(ae!==null&&v.has(ae)){var Y=v.get(ae),V=Y.reject,re=Y.resolve;v.delete(ae),U.error===void 0?re(U.result):V(new Error(U.error.message))}}),l(x)&&x.start();for(var E=function(D){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(Y,V){var re=n.generateUniqueNumber(v);v.set(re,{reject:V,resolve:Y}),U===null?x.postMessage({id:re,method:D},ae):x.postMessage({id:re,method:D,params:U},ae)})},S=function(D,U){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:D,params:U},ae)},I={},O=0,P=Object.entries(_);O<P.length;O++){var N=i(P[O],2),T=N[0],q=N[1];I=f(f({},I),{},r({},T,q({call:E,notify:S})))}return f({},I)}};t.createBroker=w})}),qu=pe((a,e)=>{le(),ue(),ce(),(function(t,r){typeof a=="object"&&typeof e<"u"?r(a,Hr(),$u(),Ha()):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))})(a,function(t,r,i,n){var o=new Map([[0,null]]),s=new Map([[0,null]]),l=i.createBroker({clearInterval:function(u){var h=u.call;return function(p){r(o.get(p))==="symbol"&&(o.set(p,null),h("clear",{timerId:p,timerType:"interval"}).then(function(){o.delete(p)}))}},clearTimeout:function(u){var h=u.call;return function(p){r(s.get(p))==="symbol"&&(s.set(p,null),h("clear",{timerId:p,timerType:"timeout"}).then(function(){s.delete(p)}))}},setInterval:function(u){var h=u.call;return function(p){for(var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,g=new Array(f>2?f-2:0),y=2;y<f;y++)g[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(o);o.set(m,w);var _=function(){return h("set",{delay:b,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=o.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===w&&(p.apply(void 0,g),o.get(m)===w&&_())})};return _(),m}},setTimeout:function(u){var h=u.call;return function(p){for(var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,g=new Array(f>2?f-2:0),y=2;y<f;y++)g[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(s);return s.set(m,w),h("set",{delay:b,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var _=s.get(m);if(_===void 0)throw new Error("The timer is in an undefined state.");_===w&&(s.delete(m),p.apply(void 0,g))}),m}}}),c=function(u){var h=new Worker(u);return l(h)};t.load=c,t.wrap=l})}),Hu=pe((a,e)=>{le(),ue(),ce(),(function(t,r){typeof a=="object"&&typeof e<"u"?r(a,qu()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(a,function(t,r){var i=function(h,p){var b=null;return function(){if(b!==null)return b;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),g=URL.createObjectURL(f);return b=h(g),setTimeout(function(){return URL.revokeObjectURL(g)}),b}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,o=i(r.load,n),s=function(h){return o().clearInterval(h)},l=function(h){return o().clearTimeout(h)},c=function(){var h;return(h=o()).setInterval.apply(h,arguments)},u=function(){var h;return(h=o()).setTimeout.apply(h,arguments)};t.clearInterval=s,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Wr=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0}),a.isReactNativeBrowser=a.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&Re?.versions?!Object.prototype.hasOwnProperty.call(Re.versions,"electron"):typeof window.document<"u":!1,t=()=>!!(typeof self=="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),r=()=>typeof navigator<"u"&&navigator.product==="ReactNative",i=e()||t()||r();a.isWebWorker=t(),a.isReactNativeBrowser=r(),a.default=i}),Wu=pe(a=>{le(),ue(),ce();var e=a&&a.__createBinding||(Object.create?function(c,u,h,p){p===void 0&&(p=h);var b=Object.getOwnPropertyDescriptor(u,h);(!b||("get"in b?!u.__esModule:b.writable||b.configurable))&&(b={enumerable:!0,get:function(){return u[h]}}),Object.defineProperty(c,p,b)}:function(c,u,h,p){p===void 0&&(p=h),c[p]=u[h]}),t=a&&a.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=a&&a.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(h){var p=[];for(var b in h)Object.prototype.hasOwnProperty.call(h,b)&&(p[p.length]=b);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var h={};if(u!=null)for(var p=c(u),b=0;b<p.length;b++)p[b]!=="default"&&e(h,u,p[b]);return t(h,u),h}})();Object.defineProperty(a,"__esModule",{value:!0});var i=Hu(),n=r(Wr()),o={set:i.setInterval,clear:i.clearInterval},s={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return s;case"worker":return o;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?o:s}};a.default=l}),Ya=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(a,"__esModule",{value:!0});var t=e(Wu()),r=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(i,n){this.client=i,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(i.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(i){if(i*=1e3,isNaN(i)||i<=0||i>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${i}`);this._keepalive=i,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${i}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let i=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+i,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{this.destroyed||(this.counter+=1,this.counter===2?this.client.sendPing():this.counter>2&&this.client.onKeepaliveTimeout())},this._intervalEvery)}};a.default=r}),hi=pe(a=>{le(),ue(),ce();var e=a&&a.__createBinding||(Object.create?function(v,E,S,I){I===void 0&&(I=S);var O=Object.getOwnPropertyDescriptor(E,S);(!O||("get"in O?!E.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return E[S]}}),Object.defineProperty(v,I,O)}:function(v,E,S,I){I===void 0&&(I=S),v[I]=E[S]}),t=a&&a.__setModuleDefault||(Object.create?function(v,E){Object.defineProperty(v,"default",{enumerable:!0,value:E})}:function(v,E){v.default=E}),r=a&&a.__importStar||(function(){var v=function(E){return v=Object.getOwnPropertyNames||function(S){var I=[];for(var O in S)Object.prototype.hasOwnProperty.call(S,O)&&(I[I.length]=O);return I},v(E)};return function(E){if(E&&E.__esModule)return E;var S={};if(E!=null)for(var I=v(E),O=0;O<I.length;O++)I[O]!=="default"&&e(S,E,I[O]);return t(S,E),S}})(),i=a&&a.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(a,"__esModule",{value:!0});var n=i(eu()),o=Pt(),s=i(ru()),l=i(ht()),c=r(Sa()),u=i(Ea()),h=i(xu()),p=i(qa()),b=i(Su()),f=$t(),g=Eu(),y=i(Ya()),w=r(Wr()),m=globalThis.setImmediate||((...v)=>{let E=v.shift();(0,f.nextTick)(()=>{E(...v)})}),_={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},x=class di extends g.TypedEventEmitter{static VERSION=f.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(E,S){super(),this.options=S||{};for(let I in _)typeof this.options[I]>"u"?this.options[I]=_[I]:this.options[I]=S[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",di.VERSION),w.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",w.default?"browser":"node"),this.log("MqttClient :: options.protocol",S.protocol),this.log("MqttClient :: options.protocolVersion",S.protocolVersion),this.log("MqttClient :: options.username",S.username),this.log("MqttClient :: options.keepalive",S.keepalive),this.log("MqttClient :: options.reconnectPeriod",S.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",S.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",S.properties?S.properties.topicAliasMaximum:void 0),this.options.clientId=typeof S.clientId=="string"?S.clientId:di.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=S.protocolVersion===5&&S.customHandleAcks?S.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=E,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new p.default:this.options.messageIdProvider,this.outgoingStore=S.outgoingStore||new u.default,this.incomingStore=S.incomingStore||new u.default,this.queueQoSZero=S.queueQoSZero===void 0?!0:S.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,S.properties&&S.properties.topicAliasMaximum>0&&(S.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new b.default(S.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,O=()=>{let P=I.shift();this.log("deliver :: entry %o",P);let N=null;if(!P){this._resubscribe();return}N=P.packet,this.log("deliver :: call _sendPacket for %o",N);let T=!0;N.messageId&&N.messageId!==0&&(this.messageIdProvider.register(N.messageId)||(T=!1)),T?this._sendPacket(N,q=>{P.cb&&P.cb(q),O()}):(this.log("messageId: %d has already used. The message is skipped and removed.",N.messageId),O())};this.log("connect :: sending queued packets"),O()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(E,S){S()}handleMessage(E,S){S()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let E=new o.Writable,S=n.default.parser(this.options),I=null,O=[];this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting&&(this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1),this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),S.on("packet",D=>{this.log("parser :: on packet push to packets array."),O.push(D)});let P=()=>{this.log("work :: getting next packet in queue");let D=O.shift();if(D)this.log("work :: packet pulled from queue"),(0,h.default)(this,D,N);else{this.log("work :: no packets in queue");let U=I;I=null,this.log("work :: done flag is %s",!!U),U&&U()}},N=()=>{if(O.length)(0,f.nextTick)(P);else{let D=I;I=null,D()}};E._write=(D,U,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),S.parse(D),P()};let T=D=>{this.log("streamErrorHandler :: error",D.message),D.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",D)):this.noop(D)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(E),this.stream.on("error",T),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let q={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will&&(q.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(q.properties||(q.properties={}),this.topicAliasRecv&&(q.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(q),S.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"){let D={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(D)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(E,S,I,O){this.log("publish :: message `%s` to topic `%s`",S,E);let{options:P}=this;typeof I=="function"&&(O=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:N,retain:T,dup:q,properties:D,cbStorePut:U}=I;if(this._checkDisconnecting(O))return this;let ae=()=>{let Y=0;if((N===1||N===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let V={cmd:"publish",topic:E,payload:S,qos:N,retain:T,messageId:Y,dup:q};switch(P.protocolVersion===5&&(V.properties=D),this.log("publish :: qos",N),N){case 1:case 2:this.outgoing[V.messageId]={volatile:!1,cb:O||this.noop},this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,void 0,U);break;default:this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,O,U);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!ae())&&this._storeProcessingQueue.push({invoke:ae,cbStorePut:I.cbStorePut,callback:O}),this}publishAsync(E,S,I){return new Promise((O,P)=>{this.publish(E,S,I,(N,T)=>{N?P(N):O(T)})})}subscribe(E,S,I){let O=this.options.protocolVersion;typeof S=="function"&&(I=S),I=I||this.noop;let P=!1,N=[];typeof E=="string"?(E=[E],N=E):Array.isArray(E)?N=E:typeof E=="object"&&(P=E.resubscribe,delete E.resubscribe,N=Object.keys(E));let T=c.validateTopics(N);if(T!==null)return m(I,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(I))return this.log("subscribe: discconecting true"),this;let q={qos:0};O===5&&(q.nl=!1,q.rap=!1,q.rh=0),S={...q,...S};let{properties:D}=S,U=[],ae=(re,F)=>{if(F=F||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<F.qos||P){let Z={topic:re,qos:F.qos};O===5&&(Z.nl=F.nl,Z.rap=F.rap,Z.rh=F.rh,Z.properties=D),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",Z.topic,Z.qos),U.push(Z)}};if(Array.isArray(E)?E.forEach(re=>{this.log("subscribe: array topic %s",re),ae(re)}):Object.keys(E).forEach(re=>{this.log("subscribe: object topic %s, %o",re,E[re]),ae(re,E[re])}),!U.length)return I(null,[]),this;let Y=(re,F)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:F};if(D&&(Z.properties=D),this.options.resubscribe){this.log("subscribe :: resubscribe true");let J=[];re.forEach(be=>{if(this.options.reconnectPeriod>0){let te={qos:be.qos};O===5&&(te.nl=be.nl||!1,te.rap=be.rap||!1,te.rh=be.rh||0,te.properties=be.properties),this._resubscribeTopics[be.topic]=te,J.push(be.topic)}}),this.messageIdToTopic[Z.messageId]=J}let M=new Promise((J,be)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:G}=we;for(let j=0;j<G.length;j+=1)re[j].qos=G[j]}te?be(new f.ErrorWithSubackPacket(te.message,we)):J(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),M},V=()=>{let re=this.options.subscribeBatchSize??U.length,F=[];for(let Z=0;Z<U.length;Z+=re){let M=U.slice(Z,Z+re),J=this._nextId();if(J===null)return this.log("No messageId left"),!1;F.push(Y(M,J))}return Promise.all(F).then(Z=>{I(null,U,Z.at(-1))}).catch(Z=>{I(Z,U,Z.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!V())&&this._storeProcessingQueue.push({invoke:V,callback:I}),this}subscribeAsync(E,S){return new Promise((I,O)=>{this.subscribe(E,S,(P,N)=>{P?O(P):I(N)})})}unsubscribe(E,S,I){typeof E=="string"&&(E=[E]),typeof S=="function"&&(I=S),I=I||this.noop;let O=c.validateTopics(E);if(O!==null)return m(I,new Error(`Invalid topic ${O}`)),this;if(this._checkDisconnecting(I))return this;let P=()=>{let N=this._nextId();if(N===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:N,unsubscriptions:[]};return typeof E=="string"?T.unsubscriptions=[E]:Array.isArray(E)&&(T.unsubscriptions=E),this.options.resubscribe&&T.unsubscriptions.forEach(q=>{delete this._resubscribeTopics[q]}),typeof S=="object"&&S.properties&&(T.properties=S.properties),this.outgoing[T.messageId]={volatile:!0,cb:I},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!P())&&this._storeProcessingQueue.push({invoke:P,callback:I}),this}unsubscribeAsync(E,S){return new Promise((I,O)=>{this.unsubscribe(E,S,(P,N)=>{P?O(P):I(N)})})}end(E,S,I){this.log("end :: (%s)",this.options.clientId),(E==null||typeof E!="boolean")&&(I=I||S,S=E,E=!1),typeof S!="object"&&(I=I||S,S=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let O=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(N=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let q=N||T;this.log("end :: closeStores: invoking callback with args"),I(q)}})}),this._deferredReconnect?this._deferredReconnect():(this.options.reconnectPeriod===0||this.options.manualConnect)&&(this.disconnecting=!1)},P=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,E),this._cleanUp(E,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,f.nextTick)(O)},S)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!E&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,P,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),P()),this)}endAsync(E,S){return new Promise((I,O)=>{this.end(E,S,P=>{P?O(P):I()})})}removeOutgoingMessage(E){if(this.outgoing[E]){let{cb:S}=this.outgoing[E];this._removeOutgoingAndStoreMessage(E,()=>{S(new Error("Message removed"))})}return this}reconnect(E){this.log("client reconnect");let S=()=>{E?(this.options.incomingStore=E.incomingStore,this.options.outgoingStore=E.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=S:S(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(E=>{this.outgoing[E].volatile&&typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(E=>{typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_removeTopicAliasAndRecoverTopicName(E){let S;E.properties&&(S=E.properties.topicAlias);let I=E.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",S,I),I.length===0){if(typeof S>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(S),typeof I>"u")return new Error("Unregistered Topic Alias");E.topic=I}S&&delete E.properties.topicAlias}_checkDisconnecting(E){return this.disconnecting&&(E&&E!==this.noop?E(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(E,S,I={}){if(S&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",S)),this.log("_cleanUp :: forced? %s",E),E)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let O={cmd:"disconnect",...I};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(O,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),m(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}!this.disconnecting&&!this.reconnecting&&(this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this._destroyKeepaliveManager(),S&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",S),S())}_storeAndSend(E,S,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",E.cmd);let O=E,P;if(O.cmd==="publish"&&(O=(0,s.default)(E),P=this._removeTopicAliasAndRecoverTopicName(O),P))return S&&S(P);this.outgoingStore.put(O,N=>{if(N)return S&&S(N);I(),this._writePacket(E,S)})}_applyTopicAlias(E){if(this.options.protocolVersion===5&&E.cmd==="publish"){let S;E.properties&&(S=E.properties.topicAlias);let I=E.topic.toString();if(this.topicAliasSend)if(S){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,S),!this.topicAliasSend.put(I,S)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(S=this.topicAliasSend.getAliasByTopic(I),S?(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,S)):(S=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,S),E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,S))):this.options.autoUseTopicAlias&&(S=this.topicAliasSend.getAliasByTopic(I),S&&(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,S))));else if(S)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}}_noop(E){this.log("noop ::",E)}_writePacket(E,S){this.log("_writePacket :: packet: %O",E),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",E),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(E,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&S&&S!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",S)):S&&(this.log("_writePacket :: invoking cb"),S())}_sendPacket(E,S,I,O){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,S=S||this.noop;let P=this._applyTopicAlias(E);if(P){S(P);return}if(!this.connected){if(E.cmd==="auth"){this._writePacket(E,S);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(E,S,I);return}if(O){this._writePacket(E,S);return}switch(E.cmd){case"publish":break;case"pubrel":this._storeAndSend(E,S,I);return;default:this._writePacket(E,S);return}switch(E.qos){case 2:case 1:this._storeAndSend(E,S,I);break;default:this._writePacket(E,S);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(E,S,I){this.log("_storePacket :: packet: %o",E),this.log("_storePacket :: cb? %s",!!S),I=I||this.noop;let O=E;if(O.cmd==="publish"){O=(0,s.default)(E);let N=this._removeTopicAliasAndRecoverTopicName(O);if(N)return S&&S(N)}let P=O.qos||0;P===0&&this.queueQoSZero||O.cmd!=="publish"?this.queue.push({packet:O,cb:S}):P>0?(S=this.outgoing[O.messageId]?this.outgoing[O.messageId].cb:null,this.outgoingStore.put(O,N=>{if(N)return S&&S(N);I()})):S&&S(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new y.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(E=!1){this.keepaliveManager&&this.options.keepalive&&(E||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let E=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&E.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let S=0;S<E.length;S++){let I={};I[E[S]]=this._resubscribeTopics[E[S]],I.resubscribe=!0,this.subscribe(I,{properties:I[E[S]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(E){if(this.disconnected){this.emit("connect",E);return}this.connackPacket=E,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let S=()=>{let I=this.outgoingStore.createStream(),O=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),P()},P=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",O),I.on("error",T=>{P(),this._flushStoreProcessingQueue(),this.removeListener("close",O),this.emit("error",T)});let N=()=>{if(!I)return;let T=I.read(1),q;if(!T){I.once("readable",N);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){N();return}!this.disconnecting&&!this.reconnectTimer?(q=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(D,U){q&&q(D,U),N()}},this._packetIdsDuringStoreProcessing[T.messageId]=!0,this.messageIdProvider.register(T.messageId)?this._sendPacket(T,void 0,void 0,!0):this.log("messageId: %d has already used.",T.messageId)):I.destroy&&I.destroy()};I.on("end",()=>{let T=!0;for(let q in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[q]){T=!1;break}this.removeListener("close",O),T?(P(),this._invokeAllStoreProcessingQueue(),this.emit("connect",E)):S()}),N()};S()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let E=this._storeProcessingQueue[0];if(E&&E.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let E of this._storeProcessingQueue)E.cbStorePut&&E.cbStorePut(new Error("Connection closed")),E.callback&&E.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(E,S){delete this.outgoing[E],this.outgoingStore.del({messageId:E},(I,O)=>{S(I,O),this.messageIdProvider.deallocate(E),this._invokeStoreProcessingQueue()})}};a.default=x}),zu=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=$a(),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()}};a.default=t});function Vu(){if(fi)return dr;fi=!0;let a=2147483647,e=36,t=1,r=26,i=38,n=700,o=72,s=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,h=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},b=e-t,f=Math.floor,g=String.fromCharCode;function y(P){throw new RangeError(p[P])}function w(P,N){let T=[],q=P.length;for(;q--;)T[q]=N(P[q]);return T}function m(P,N){let T=P.split("@"),q="";T.length>1&&(q=T[0]+"@",P=T[1]),P=P.replace(h,".");let D=P.split("."),U=w(D,N).join(".");return q+U}function _(P){let N=[],T=0,q=P.length;for(;T<q;){let D=P.charCodeAt(T++);if(D>=55296&&D<=56319&&T<q){let U=P.charCodeAt(T++);(U&64512)==56320?N.push(((D&1023)<<10)+(U&1023)+65536):(N.push(D),T--)}else N.push(D)}return N}let x=P=>String.fromCodePoint(...P),v=function(P){return P>=48&&P<58?26+(P-48):P>=65&&P<91?P-65:P>=97&&P<123?P-97:e},E=function(P,N){return P+22+75*(P<26)-((N!=0)<<5)},S=function(P,N,T){let q=0;for(P=T?f(P/n):P>>1,P+=f(P/N);P>b*r>>1;q+=e)P=f(P/b);return f(q+(b+1)*P/(P+i))},I=function(P){let N=[],T=P.length,q=0,D=s,U=o,ae=P.lastIndexOf(l);ae<0&&(ae=0);for(let Y=0;Y<ae;++Y)P.charCodeAt(Y)>=128&&y("not-basic"),N.push(P.charCodeAt(Y));for(let Y=ae>0?ae+1:0;Y<T;){let V=q;for(let F=1,Z=e;;Z+=e){Y>=T&&y("invalid-input");let M=v(P.charCodeAt(Y++));M>=e&&y("invalid-input"),M>f((a-q)/F)&&y("overflow"),q+=M*F;let J=Z<=U?t:Z>=U+r?r:Z-U;if(M<J)break;let be=e-J;F>f(a/be)&&y("overflow"),F*=be}let re=N.length+1;U=S(q-V,re,V==0),f(q/re)>a-D&&y("overflow"),D+=f(q/re),q%=re,N.splice(q++,0,D)}return String.fromCodePoint(...N)},O=function(P){let N=[];P=_(P);let T=P.length,q=s,D=0,U=o;for(let V of P)V<128&&N.push(g(V));let ae=N.length,Y=ae;for(ae&&N.push(l);Y<T;){let V=a;for(let F of P)F>=q&&F<V&&(V=F);let re=Y+1;V-q>f((a-D)/re)&&y("overflow"),D+=(V-q)*re,q=V;for(let F of P)if(F<q&&++D>a&&y("overflow"),F===q){let Z=D;for(let M=e;;M+=e){let J=M<=U?t:M>=U+r?r:M-U;if(Z<J)break;let be=Z-J,te=e-J;N.push(g(E(J+be%te,0))),Z=f(be/te)}N.push(g(E(Z,0))),U=S(D,re,Y===ae),D=0,++Y}++D,++q}return N.join("")};return dr={version:"2.3.1",ucs2:{decode:_,encode:x},decode:I,encode:O,toASCII:function(P){return m(P,function(N){return u.test(N)?"xn--"+O(N):N})},toUnicode:function(P){return m(P,function(N){return c.test(N)?I(N.slice(4).toLowerCase()):N})}},dr}var dr,fi,yt,Gu=Ve(()=>{le(),ue(),ce(),dr={},fi=!1,yt=Vu(),yt.decode,yt.encode,yt.toASCII,yt.toUnicode,yt.ucs2,yt.version});function Ku(){return mi||(mi=!0,pi=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var a={},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;a[e]=r;for(e in a)return!1;if(typeof Object.keys=="function"&&Object.keys(a).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(a).length!==0)return!1;var i=Object.getOwnPropertySymbols(a);if(i.length!==1||i[0]!==e||!Object.prototype.propertyIsEnumerable.call(a,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(a,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),pi}function Yu(){return bi||(bi=!0,gi=Error),gi}function Qu(){return vi||(vi=!0,yi=EvalError),yi}function Ju(){return _i||(_i=!0,wi=RangeError),wi}function Xu(){return xi||(xi=!0,ki=ReferenceError),ki}function Qa(){return Ei||(Ei=!0,Si=SyntaxError),Si}function rr(){return Ii||(Ii=!0,Ai=TypeError),Ai}function Zu(){return Ci||(Ci=!0,Ti=URIError),Ti}function eh(){if(Oi)return fr;Oi=!0;var a=typeof Symbol<"u"&&Symbol,e=Ku();return fr=function(){return typeof a!="function"||typeof Symbol!="function"||typeof a("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},fr}function th(){if(Pi)return pr;Pi=!0;var a={__proto__:null,foo:{}},e=Object;return pr=function(){return{__proto__:a}.foo===a.foo&&!(a instanceof e)},pr}function rh(){if(Mi)return mr;Mi=!0;var a="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",i=function(s,l){for(var c=[],u=0;u<s.length;u+=1)c[u]=s[u];for(var h=0;h<l.length;h+=1)c[h+s.length]=l[h];return c},n=function(s,l){for(var c=[],u=l,h=0;u<s.length;u+=1,h+=1)c[h]=s[u];return c},o=function(s,l){for(var c="",u=0;u<s.length;u+=1)c+=s[u],u+1<s.length&&(c+=l);return c};return mr=function(s){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(a+l);for(var c=n(arguments,1),u,h=function(){if(this instanceof u){var y=l.apply(this,i(c,arguments));return Object(y)===y?y:this}return l.apply(s,i(c,arguments))},p=t(0,l.length-c.length),b=[],f=0;f<p;f++)b[f]="$"+f;if(u=Function("binder","return function ("+o(b,",")+"){ return binder.apply(this,arguments); }")(h),l.prototype){var g=function(){};g.prototype=l.prototype,u.prototype=new g,g.prototype=null}return u},mr}function uo(){if(Ri)return gr;Ri=!0;var a=rh();return gr=Function.prototype.bind||a,gr}function nh(){if(Li)return br;Li=!0;var a=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=uo();return br=t.call(a,e),br}function qt(){if(ji)return yr;ji=!0;var a,e=Yu(),t=Qu(),r=Ju(),i=Xu(),n=Qa(),o=rr(),s=Zu(),l=Function,c=function(Y){try{return l('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var h=function(){throw new o},p=u?(function(){try{return arguments.callee,h}catch{try{return u(arguments,"callee").get}catch{return h}}})():h,b=eh()(),f=th()(),g=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),y={},w=typeof Uint8Array>"u"||!g?a:g(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?a:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?a:ArrayBuffer,"%ArrayIteratorPrototype%":b&&g?g([][Symbol.iterator]()):a,"%AsyncFromSyncIteratorPrototype%":a,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":typeof Atomics>"u"?a:Atomics,"%BigInt%":typeof BigInt>"u"?a:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?a:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?a:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?a:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?a:Float32Array,"%Float64Array%":typeof Float64Array>"u"?a:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?a:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":y,"%Int8Array%":typeof Int8Array>"u"?a:Int8Array,"%Int16Array%":typeof Int16Array>"u"?a:Int16Array,"%Int32Array%":typeof Int32Array>"u"?a:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":b&&g?g(g([][Symbol.iterator]())):a,"%JSON%":typeof JSON=="object"?JSON:a,"%Map%":typeof Map>"u"?a:Map,"%MapIteratorPrototype%":typeof Map>"u"||!b||!g?a:g(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?a:Promise,"%Proxy%":typeof Proxy>"u"?a:Proxy,"%RangeError%":r,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?a:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?a:Set,"%SetIteratorPrototype%":typeof Set>"u"||!b||!g?a:g(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?a:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":b&&g?g(""[Symbol.iterator]()):a,"%Symbol%":b?Symbol:a,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":w,"%TypeError%":o,"%Uint8Array%":typeof Uint8Array>"u"?a:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?a:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?a:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?a:Uint32Array,"%URIError%":s,"%WeakMap%":typeof WeakMap>"u"?a:WeakMap,"%WeakRef%":typeof WeakRef>"u"?a:WeakRef,"%WeakSet%":typeof WeakSet>"u"?a:WeakSet};if(g)try{null.error}catch(Y){var _=g(g(Y));m["%Error.prototype%"]=_}var x=function Y(V){var re;if(V==="%AsyncFunction%")re=c("async function () {}");else if(V==="%GeneratorFunction%")re=c("function* () {}");else if(V==="%AsyncGeneratorFunction%")re=c("async function* () {}");else if(V==="%AsyncGenerator%"){var F=Y("%AsyncGeneratorFunction%");F&&(re=F.prototype)}else if(V==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&g&&(re=g(Z.prototype))}return m[V]=re,re},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},E=uo(),S=nh(),I=E.call(Function.call,Array.prototype.concat),O=E.call(Function.apply,Array.prototype.splice),P=E.call(Function.call,String.prototype.replace),N=E.call(Function.call,String.prototype.slice),T=E.call(Function.call,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,D=/\\(\\)?/g,U=function(Y){var V=N(Y,0,1),re=N(Y,-1);if(V==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&V!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var F=[];return P(Y,q,function(Z,M,J,be){F[F.length]=J?P(be,D,"$1"):M||Z}),F},ae=function(Y,V){var re=Y,F;if(S(v,re)&&(F=v[re],re="%"+F[0]+"%"),S(m,re)){var Z=m[re];if(Z===y&&(Z=x(re)),typeof Z>"u"&&!V)throw new o("intrinsic "+Y+" exists, but is not available. Please file an issue!");return{alias:F,name:re,value:Z}}throw new n("intrinsic "+Y+" does not exist!")};return yr=function(Y,V){if(typeof Y!="string"||Y.length===0)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof V!="boolean")throw new o('"allowMissing" argument must be a boolean');if(T(/^%?[^%]*%?$/,Y)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var re=U(Y),F=re.length>0?re[0]:"",Z=ae("%"+F+"%",V),M=Z.name,J=Z.value,be=!1,te=Z.alias;te&&(F=te[0],O(re,I([0,1],te)));for(var we=1,G=!0;we<re.length;we+=1){var j=re[we],ne=N(j,0,1),W=N(j,-1);if((ne==='"'||ne==="'"||ne==="`"||W==='"'||W==="'"||W==="`")&&ne!==W)throw new n("property names with quotes must have matching quotes");if((j==="constructor"||!G)&&(be=!0),F+="."+j,M="%"+F+"%",S(m,M))J=m[M];else if(J!=null){if(!(j in J)){if(!V)throw new o("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var K=u(J,j);G=!!K,G&&"get"in K&&!("originalValue"in K.get)?J=K.get:J=J[j]}else G=S(J,j),J=J[j];G&&!be&&(m[M]=J)}}return J},yr}function ho(){if(Ni)return vr;Ni=!0;var a=qt(),e=a("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return vr=e,vr}function Ja(){if(Ui)return wr;Ui=!0;var a=qt(),e=a("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return wr=e,wr}function ih(){if(Bi)return _r;Bi=!0;var a=ho(),e=Qa(),t=rr(),r=Ja();return _r=function(i,n,o){if(!i||typeof i!="object"&&typeof i!="function")throw new t("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new t("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new t("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new t("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new t("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new t("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,h=!!r&&r(i,n);if(a)a(i,n,{configurable:c===null&&h?h.configurable:!c,enumerable:s===null&&h?h.enumerable:!s,value:o,writable:l===null&&h?h.writable:!l});else if(u||!s&&!l&&!c)i[n]=o;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},_r}function oh(){if(Di)return kr;Di=!0;var a=ho(),e=function(){return!!a};return e.hasArrayLengthDefineBug=function(){if(!a)return null;try{return a([],"length",{value:1}).length!==1}catch{return!0}},kr=e,kr}function sh(){if(Fi)return xr;Fi=!0;var a=qt(),e=ih(),t=oh()(),r=Ja(),i=rr(),n=a("%Math.floor%");return xr=function(o,s){if(typeof o!="function")throw new i("`fn` is not a function");if(typeof s!="number"||s<0||s>4294967295||n(s)!==s)throw new i("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in o&&r){var h=r(o,"length");h&&!h.configurable&&(c=!1),h&&!h.writable&&(u=!1)}return(c||u||!l)&&(t?e(o,"length",s,!0,!0):e(o,"length",s)),o},xr}function ah(){if($i)return Nt;$i=!0;var a=uo(),e=qt(),t=sh(),r=rr(),i=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),o=e("%Reflect.apply%",!0)||a.call(n,i),s=ho(),l=e("%Math.max%");Nt=function(u){if(typeof u!="function")throw new r("a function is required");var h=o(a,n,arguments);return t(h,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return o(a,i,arguments)};return s?s(Nt,"apply",{value:c}):Nt.apply=c,Nt}function lh(){if(qi)return Sr;qi=!0;var a=qt(),e=ah(),t=e(a("String.prototype.indexOf"));return Sr=function(r,i){var n=a(r,!!i);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Sr}var pi,mi,gi,bi,yi,vi,wi,_i,ki,xi,Si,Ei,Ai,Ii,Ti,Ci,fr,Oi,pr,Pi,mr,Mi,gr,Ri,br,Li,yr,ji,vr,Ni,wr,Ui,_r,Bi,kr,Di,xr,Fi,Nt,$i,Sr,qi,ch=Ve(()=>{le(),ue(),ce(),pi={},mi=!1,gi={},bi=!1,yi={},vi=!1,wi={},_i=!1,ki={},xi=!1,Si={},Ei=!1,Ai={},Ii=!1,Ti={},Ci=!1,fr={},Oi=!1,pr={},Pi=!1,mr={},Mi=!1,gr={},Ri=!1,br={},Li=!1,yr={},ji=!1,vr={},Ni=!1,wr={},Ui=!1,_r={},Bi=!1,kr={},Di=!1,xr={},Fi=!1,Nt={},$i=!1,Sr={},qi=!1});function fo(a){throw new Error("Node.js process "+a+" is not supported by JSPM core outside of Node.js")}function uh(){!Tt||!At||(Tt=!1,At.length?it=At.concat(it):Xt=-1,it.length&&Xa())}function Xa(){if(!Tt){var a=setTimeout(uh,0);Tt=!0;for(var e=it.length;e;){for(At=it,it=[];++Xt<e;)At&&At[Xt].run();Xt=-1,e=it.length}At=null,Tt=!1,clearTimeout(a)}}function hh(a){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];it.push(new Za(a,e)),it.length===1&&!Tt&&setTimeout(Xa,0)}function Za(a,e){this.fun=a,this.array=e}function $e(){}function dh(a){fo("_linkedBinding")}function fh(a){fo("dlopen")}function ph(){return[]}function mh(){return[]}function gh(a,e){if(!a)throw new Error(e||"assertion error")}function bh(){return!1}function yh(){return ct.now()/1e3}function Gr(a){var e=Math.floor((Date.now()-ct.now())*.001),t=ct.now()*.001,r=Math.floor(t)+e,i=Math.floor(t%1*1e9);return a&&(r=r-a[0],i=i-a[1],i<0&&(r--,i+=Er)),[r,i]}function gt(){return po}function vh(a){return[]}var it,Tt,At,Xt,Ao,Io,To,Co,Oo,Po,Mo,Ro,Lo,jo,No,Uo,Bo,Do,Fo,$o,qo,Ho,Wo,zo,Vo,or,Go,Ko,Yo,Qo,Jo,Xo,Zo,es,ts,rs,ns,is,os,ss,as,ls,cs,us,hs,ds,fs,ps,ms,gs,bs,ct,Kr,Er,ys,vs,ws,_s,ks,xs,Ss,Es,As,Is,Ts,po,el=Ve(()=>{le(),ue(),ce(),it=[],Tt=!1,Xt=-1,Za.prototype.run=function(){this.fun.apply(null,this.array)},Ao="browser",Io="x64",To="browser",Co={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Oo=["/usr/bin/node"],Po=[],Mo="v16.8.0",Ro={},Lo=function(a,e){console.warn((e?e+": ":"")+a)},jo=function(a){fo("binding")},No=function(a){return 0},Uo=function(){return"/"},Bo=function(a){},Do={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Fo=$e,$o=[],qo={},Ho=!1,Wo={},zo=$e,Vo=$e,or=function(){return{}},Go=or,Ko=or,Yo=$e,Qo=$e,Jo=$e,Xo={},Zo={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},es=$e,ts=$e,rs=$e,ns=$e,is=$e,os=$e,ss=$e,as=void 0,ls=void 0,cs=void 0,us=$e,hs=2,ds=1,fs="/bin/usr/node",ps=9229,ms="node",gs=[],bs=$e,ct={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ct.now===void 0&&(Kr=Date.now(),ct.timing&&ct.timing.navigationStart&&(Kr=ct.timing.navigationStart),ct.now=()=>Date.now()-Kr),Er=1e9,Gr.bigint=function(a){var e=Gr(a);return typeof BigInt>"u"?e[0]*Er+e[1]:BigInt(e[0]*Er)+BigInt(e[1])},ys=10,vs={},ws=0,_s=gt,ks=gt,xs=gt,Ss=gt,Es=gt,As=$e,Is=gt,Ts=gt,po={version:Mo,versions:Ro,arch:Io,platform:To,release:Do,_rawDebug:Fo,moduleLoadList:$o,binding:jo,_linkedBinding:dh,_events:vs,_eventsCount:ws,_maxListeners:ys,on:gt,addListener:_s,once:ks,off:xs,removeListener:Ss,removeAllListeners:Es,emit:As,prependListener:Is,prependOnceListener:Ts,listeners:vh,domain:qo,_exiting:Ho,config:Wo,dlopen:fh,uptime:yh,_getActiveRequests:ph,_getActiveHandles:mh,reallyExit:zo,_kill:Vo,cpuUsage:or,resourceUsage:Go,memoryUsage:Ko,kill:Yo,exit:Qo,openStdin:Jo,allowedNodeEnvironmentFlags:Xo,assert:gh,features:Zo,_fatalExceptions:es,setUncaughtExceptionCaptureCallback:ts,hasUncaughtExceptionCaptureCallback:bh,emitWarning:Lo,nextTick:hh,_tickCallback:rs,_debugProcess:ns,_debugEnd:is,_startProfilerIdleNotifier:os,_stopProfilerIdleNotifier:ss,stdout:as,stdin:cs,stderr:ls,abort:us,umask:No,chdir:Bo,cwd:Uo,env:Co,title:Ao,argv:Oo,execArgv:Po,pid:hs,ppid:ds,execPath:fs,debugPort:ps,hrtime:Gr,argv0:ms,_preload_modules:gs,setSourceMapsEnabled:bs}});function wh(){if(Hi)return Ar;Hi=!0;var a=po;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,o){for(var s="",l=0,c=-1,u=0,h,p=0;p<=n.length;++p){if(p<n.length)h=n.charCodeAt(p);else{if(h===47)break;h=47}if(h===47){if(!(c===p-1||u===1))if(c!==p-1&&u===2){if(s.length<2||l!==2||s.charCodeAt(s.length-1)!==46||s.charCodeAt(s.length-2)!==46){if(s.length>2){var b=s.lastIndexOf("/");if(b!==s.length-1){b===-1?(s="",l=0):(s=s.slice(0,b),l=s.length-1-s.lastIndexOf("/")),c=p,u=0;continue}}else if(s.length===2||s.length===1){s="",l=0,c=p,u=0;continue}}o&&(s.length>0?s+="/..":s="..",l=2)}else s.length>0?s+="/"+n.slice(c+1,p):s=n.slice(c+1,p),l=p-c-1;c=p,u=0}else h===46&&u!==-1?++u:u=-1}return s}function r(n,o){var s=o.dir||o.root,l=o.base||(o.name||"")+(o.ext||"");return s?s===o.root?s+l:s+n+l:l}var i={resolve:function(){for(var n="",o=!1,s,l=arguments.length-1;l>=-1&&!o;l--){var c;l>=0?c=arguments[l]:(s===void 0&&(s=a.cwd()),c=s),e(c),c.length!==0&&(n=c+"/"+n,o=c.charCodeAt(0)===47)}return n=t(n,!o),o?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var o=n.charCodeAt(0)===47,s=n.charCodeAt(n.length-1)===47;return n=t(n,!o),n.length===0&&!o&&(n="."),n.length>0&&s&&(n+="/"),o?"/"+n:n},isAbsolute:function(n){return e(n),n.length>0&&n.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var n,o=0;o<arguments.length;++o){var s=arguments[o];e(s),s.length>0&&(n===void 0?n=s:n+="/"+s)}return n===void 0?".":i.normalize(n)},relative:function(n,o){if(e(n),e(o),n===o||(n=i.resolve(n),o=i.resolve(o),n===o))return"";for(var s=1;s<n.length&&n.charCodeAt(s)===47;++s);for(var l=n.length,c=l-s,u=1;u<o.length&&o.charCodeAt(u)===47;++u);for(var h=o.length,p=h-u,b=c<p?c:p,f=-1,g=0;g<=b;++g){if(g===b){if(p>b){if(o.charCodeAt(u+g)===47)return o.slice(u+g+1);if(g===0)return o.slice(u+g)}else c>b&&(n.charCodeAt(s+g)===47?f=g:g===0&&(f=0));break}var y=n.charCodeAt(s+g),w=o.charCodeAt(u+g);if(y!==w)break;y===47&&(f=g)}var m="";for(g=s+f+1;g<=l;++g)(g===l||n.charCodeAt(g)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+o.slice(u+f):(u+=f,o.charCodeAt(u)===47&&++u,o.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var o=n.charCodeAt(0),s=o===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(o=n.charCodeAt(u),o===47){if(!c){l=u;break}}else c=!1;return l===-1?s?"/":".":s&&l===1?"//":n.slice(0,l)},basename:function(n,o){if(o!==void 0&&typeof o!="string")throw new TypeError('"ext" argument must be a string');e(n);var s=0,l=-1,c=!0,u;if(o!==void 0&&o.length>0&&o.length<=n.length){if(o.length===n.length&&o===n)return"";var h=o.length-1,p=-1;for(u=n.length-1;u>=0;--u){var b=n.charCodeAt(u);if(b===47){if(!c){s=u+1;break}}else p===-1&&(c=!1,p=u+1),h>=0&&(b===o.charCodeAt(h)?--h===-1&&(l=u):(h=-1,l=p))}return s===l?l=p:l===-1&&(l=n.length),n.slice(s,l)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){s=u+1;break}}else l===-1&&(c=!1,l=u+1);return l===-1?"":n.slice(s,l)}},extname:function(n){e(n);for(var o=-1,s=0,l=-1,c=!0,u=0,h=n.length-1;h>=0;--h){var p=n.charCodeAt(h);if(p===47){if(!c){s=h+1;break}continue}l===-1&&(c=!1,l=h+1),p===46?o===-1?o=h:u!==1&&(u=1):o!==-1&&(u=-1)}return o===-1||l===-1||u===0||u===1&&o===l-1&&o===s+1?"":n.slice(o,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 o={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return o;var s=n.charCodeAt(0),l=s===47,c;l?(o.root="/",c=1):c=0;for(var u=-1,h=0,p=-1,b=!0,f=n.length-1,g=0;f>=c;--f){if(s=n.charCodeAt(f),s===47){if(!b){h=f+1;break}continue}p===-1&&(b=!1,p=f+1),s===46?u===-1?u=f:g!==1&&(g=1):u!==-1&&(g=-1)}return u===-1||p===-1||g===0||g===1&&u===p-1&&u===h+1?p!==-1&&(h===0&&l?o.base=o.name=n.slice(1,p):o.base=o.name=n.slice(h,p)):(h===0&&l?(o.name=n.slice(1,u),o.base=n.slice(1,p)):(o.name=n.slice(h,u),o.base=n.slice(h,p)),o.ext=n.slice(u,p)),h>0?o.dir=n.slice(0,h-1):l&&(o.dir="/"),o},sep:"/",delimiter:":",win32:null,posix:null};return i.posix=i,Ar=i,Ar}var Ar,Hi,Wi,_h=Ve(()=>{le(),ue(),ce(),el(),Ar={},Hi=!1,Wi=wh()}),tl={};Dt(tl,{URL:()=>hl,Url:()=>sl,default:()=>qe,fileURLToPath:()=>nl,format:()=>al,parse:()=>ul,pathToFileURL:()=>il,resolve:()=>ll,resolveObject:()=>cl});function kh(){if(zi)return Ir;zi=!0;var a=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&a?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=a&&e&&typeof e.get=="function"?e.get:null,r=a&&Map.prototype.forEach,i=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,o=i&&n&&typeof n.get=="function"?n.get:null,s=i&&Set.prototype.forEach,l=typeof WeakMap=="function"&&WeakMap.prototype,c=l?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,h=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,b=p?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,g=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,_=String.prototype.replace,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,E=RegExp.prototype.test,S=Array.prototype.concat,I=Array.prototype.join,O=Array.prototype.slice,P=Math.floor,N=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,q=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,D=typeof Symbol=="function"&&typeof Symbol.iterator=="object",U=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===D||!0)?Symbol.toStringTag:null,ae=Object.prototype.propertyIsEnumerable,Y=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(z){return z.__proto__}:null);function V(z,ie){if(z===1/0||z===-1/0||z!==z||z&&z>-1e3&&z<1e3||E.call(/e/,ie))return ie;var Ee=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof z=="number"){var Ae=z<0?-P(-z):P(z);if(Ae!==z){var Ie=String(Ae),Ce=m.call(ie,Ie.length+1);return _.call(Ie,Ee,"$&_")+"."+_.call(_.call(Ce,/([0-9]{3})/g,"$&_"),/_$/,"")}}return _.call(ie,Ee,"$&_")}var re=ol,F=re.custom,Z=K(F)?F:null;Ir=function z(ie,Ee,Ae,Ie){var Ce=Ee||{};if(oe(Ce,"quoteStyle")&&Ce.quoteStyle!=="single"&&Ce.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oe(Ce,"maxStringLength")&&(typeof Ce.maxStringLength=="number"?Ce.maxStringLength<0&&Ce.maxStringLength!==1/0:Ce.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var Je=oe(Ce,"customInspect")?Ce.customInspect:!0;if(typeof Je!="boolean"&&Je!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oe(Ce,"indent")&&Ce.indent!==null&&Ce.indent!==" "&&!(parseInt(Ce.indent,10)===Ce.indent&&Ce.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oe(Ce,"numericSeparator")&&typeof Ce.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var Xe=Ce.numericSeparator;if(typeof ie>"u")return"undefined";if(ie===null)return"null";if(typeof ie=="boolean")return ie?"true":"false";if(typeof ie=="string")return se(ie,Ce);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var De=String(ie);return Xe?V(ie,De):De}if(typeof ie=="bigint"){var Ze=String(ie)+"n";return Xe?V(ie,Ze):Ze}var Mt=typeof Ce.depth>"u"?5:Ce.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=Mt&&Mt>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var et=X(Ce,Ae);if(typeof Ie>"u")Ie=[];else if(ee(Ie,ie)>=0)return"[Circular]";function Ge(tt,mt,xt){if(mt&&(Ie=O.call(Ie),Ie.push(mt)),xt){var rt={depth:Ce.depth};return oe(Ce,"quoteStyle")&&(rt.quoteStyle=Ce.quoteStyle),z(tt,rt,Ae+1,Ie)}return z(tt,Ce,Ae+1,Ie)}if(typeof ie=="function"&&!we(ie)){var nr=$(ie),Rt=ke(ie,Ge);return"[Function"+(nr?": "+nr:" (anonymous)")+"]"+(Rt.length>0?" { "+I.call(Rt,", ")+" }":"")}if(K(ie)){var Ht=D?_.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):q.call(ie);return typeof ie=="object"&&!D?d(Ht):Ht}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),L=ie.attributes||[],_e=0;_e<L.length;_e++)C+=" "+L[_e].name+"="+M(J(L[_e].value),"double",Ce);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(be(ie)){if(ie.length===0)return"[]";var xe=ke(ie,Ge);return et&&!B(xe)?"["+he(xe,et)+"]":"[ "+I.call(xe,", ")+" ]"}if(G(ie)){var Se=ke(ie,Ge);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(S.call("[cause]: "+Ge(ie.cause),Se),", ")+" }":Se.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Se,", ")+" }"}if(typeof ie=="object"&&Je){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Mt-Ae});if(Je!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(de(ie)){var Ne=[];return r&&r.call(ie,function(tt,mt){Ne.push(Ge(mt,ie,!0)+" => "+Ge(tt,ie))}),A("Map",t.call(ie),Ne,et)}if(H(ie)){var He=[];return s&&s.call(ie,function(tt){He.push(Ge(tt,ie))}),A("Set",o.call(ie),He,et)}if(fe(ie))return k("WeakMap");if(me(ie))return k("WeakSet");if(ye(ie))return k("WeakRef");if(ne(ie))return d(Ge(Number(ie)));if(Q(ie))return d(Ge(N.call(ie)));if(W(ie))return d(f.call(ie));if(j(ie))return d(Ge(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Tr<"u"&&ie===Tr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var Qe=ke(ie,Ge),Wt=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,zt=ie instanceof Object?"":"null prototype",Vt=!Wt&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):zt?"Object":"",ir=Wt||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",kt=ir+(Vt||zt?"["+I.call(S.call([],Vt||[],zt||[]),": ")+"] ":"");return Qe.length===0?kt+"{}":et?kt+"{"+he(Qe,et)+"}":kt+"{ "+I.call(Qe,", ")+" }"}return String(ie)};function M(z,ie,Ee){var Ae=(Ee.quoteStyle||ie)==="double"?'"':"'";return Ae+z+Ae}function J(z){return _.call(String(z),/"/g,"&quot;")}function be(z){return R(z)==="[object Array]"&&(!U||!(typeof z=="object"&&U in z))}function te(z){return R(z)==="[object Date]"&&(!U||!(typeof z=="object"&&U in z))}function we(z){return R(z)==="[object RegExp]"&&(!U||!(typeof z=="object"&&U in z))}function G(z){return R(z)==="[object Error]"&&(!U||!(typeof z=="object"&&U in z))}function j(z){return R(z)==="[object String]"&&(!U||!(typeof z=="object"&&U in z))}function ne(z){return R(z)==="[object Number]"&&(!U||!(typeof z=="object"&&U in z))}function W(z){return R(z)==="[object Boolean]"&&(!U||!(typeof z=="object"&&U in z))}function K(z){if(D)return z&&typeof z=="object"&&z instanceof Symbol;if(typeof z=="symbol")return!0;if(!z||typeof z!="object"||!q)return!1;try{return q.call(z),!0}catch{}return!1}function Q(z){if(!z||typeof z!="object"||!N)return!1;try{return N.call(z),!0}catch{}return!1}var ge=Object.prototype.hasOwnProperty||function(z){return z in(this||Tr)};function oe(z,ie){return ge.call(z,ie)}function R(z){return g.call(z)}function $(z){if(z.name)return z.name;var ie=w.call(y.call(z),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(z,ie){if(z.indexOf)return z.indexOf(ie);for(var Ee=0,Ae=z.length;Ee<Ae;Ee++)if(z[Ee]===ie)return Ee;return-1}function de(z){if(!t||!z||typeof z!="object")return!1;try{t.call(z);try{o.call(z)}catch{return!0}return z instanceof Map}catch{}return!1}function fe(z){if(!c||!z||typeof z!="object")return!1;try{c.call(z,c);try{h.call(z,h)}catch{return!0}return z instanceof WeakMap}catch{}return!1}function ye(z){if(!b||!z||typeof z!="object")return!1;try{return b.call(z),!0}catch{}return!1}function H(z){if(!o||!z||typeof z!="object")return!1;try{o.call(z);try{t.call(z)}catch{return!0}return z instanceof Set}catch{}return!1}function me(z){if(!h||!z||typeof z!="object")return!1;try{h.call(z,h);try{c.call(z,c)}catch{return!0}return z instanceof WeakSet}catch{}return!1}function ve(z){return!z||typeof z!="object"?!1:typeof HTMLElement<"u"&&z instanceof HTMLElement?!0:typeof z.nodeName=="string"&&typeof z.getAttribute=="function"}function se(z,ie){if(z.length>ie.maxStringLength){var Ee=z.length-ie.maxStringLength,Ae="... "+Ee+" more character"+(Ee>1?"s":"");return se(m.call(z,0,ie.maxStringLength),ie)+Ae}var Ie=_.call(_.call(z,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Te);return M(Ie,"single",ie)}function Te(z){var ie=z.charCodeAt(0),Ee={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ee?"\\"+Ee:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function d(z){return"Object("+z+")"}function k(z){return z+" { ? }"}function A(z,ie,Ee,Ae){var Ie=Ae?he(Ee,Ae):I.call(Ee,", ");return z+" ("+ie+") {"+Ie+"}"}function B(z){for(var ie=0;ie<z.length;ie++)if(ee(z[ie],`
4
+ `)>=0)return!1;return!0}function X(z,ie){var Ee;if(z.indent===" ")Ee=" ";else if(typeof z.indent=="number"&&z.indent>0)Ee=I.call(Array(z.indent+1)," ");else return null;return{base:Ee,prev:I.call(Array(ie+1),Ee)}}function he(z,ie){if(z.length===0)return"";var Ee=`
5
+ `+ie.prev+ie.base;return Ee+I.call(z,","+Ee)+`
6
+ `+ie.prev}function ke(z,ie){var Ee=be(z),Ae=[];if(Ee){Ae.length=z.length;for(var Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],z):""}var Ce=typeof T=="function"?T(z):[],Je;if(D){Je={};for(var Xe=0;Xe<Ce.length;Xe++)Je["$"+Ce[Xe]]=Ce[Xe]}for(var De in z)oe(z,De)&&(Ee&&String(Number(De))===De&&De<z.length||D&&Je["$"+De]instanceof Symbol||(E.call(/[^\w$]/,De)?Ae.push(ie(De,z)+": "+ie(z[De],z)):Ae.push(De+": "+ie(z[De],z))));if(typeof T=="function")for(var Ze=0;Ze<Ce.length;Ze++)ae.call(z,Ce[Ze])&&Ae.push("["+ie(Ce[Ze])+"]: "+ie(z[Ce[Ze]],z));return Ae}return Ir}function xh(){if(Vi)return Cr;Vi=!0;var a=qt(),e=lh(),t=kh(),r=rr(),i=a("%WeakMap%",!0),n=a("%Map%",!0),o=e("WeakMap.prototype.get",!0),s=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),h=e("Map.prototype.has",!0),p=function(y,w){for(var m=y,_;(_=m.next)!==null;m=_)if(_.key===w)return m.next=_.next,_.next=y.next,y.next=_,_},b=function(y,w){var m=p(y,w);return m&&m.value},f=function(y,w,m){var _=p(y,w);_?_.value=m:y.next={key:w,next:y.next,value:m}},g=function(y,w){return!!p(y,w)};return Cr=function(){var y,w,m,_={assert:function(x){if(!_.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(i&&x&&(typeof x=="object"||typeof x=="function")){if(y)return o(y,x)}else if(n){if(w)return c(w,x)}else if(m)return b(m,x)},has:function(x){if(i&&x&&(typeof x=="object"||typeof x=="function")){if(y)return l(y,x)}else if(n){if(w)return h(w,x)}else if(m)return g(m,x);return!1},set:function(x,v){i&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new i),s(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),f(m,x,v))}};return _},Cr}function mo(){if(Gi)return Or;Gi=!0;var a=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Or={default:t.RFC3986,formatters:{RFC1738:function(r){return a.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Or}function rl(){if(Ki)return Pr;Ki=!0;var a=mo(),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})(),i=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var _=[],x=0;x<m.length;++x)typeof m[x]<"u"&&_.push(m[x]);w.obj[w.prop]=_}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},_=0;_<y.length;++_)typeof y[_]<"u"&&(m[_]=y[_]);return m},o=function y(w,m,_){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(_&&(_.plainObjects||_.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var x=w;return t(w)&&!t(m)&&(x=n(w,_)),t(w)&&t(m)?(m.forEach(function(v,E){if(e.call(w,E)){var S=w[E];S&&typeof S=="object"&&v&&typeof v=="object"?w[E]=y(S,v,_):w.push(v)}else w[E]=v}),w):Object.keys(m).reduce(function(v,E){var S=m[E];return e.call(v,E)?v[E]=y(v[E],S,_):v[E]=S,v},x)},s=function(y,w){return Object.keys(w).reduce(function(m,_){return m[_]=w[_],m},y)},l=function(y,w,m){var _=y.replace(/\+/g," ");if(m==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},c=1024,u=function(y,w,m,_,x){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var E="",S=0;S<v.length;S+=c){for(var I=v.length>=c?v.slice(S,S+c):v,O=[],P=0;P<I.length;++P){var N=I.charCodeAt(P);if(N===45||N===46||N===95||N===126||N>=48&&N<=57||N>=65&&N<=90||N>=97&&N<=122||x===a.RFC1738&&(N===40||N===41)){O[O.length]=I.charAt(P);continue}if(N<128){O[O.length]=r[N];continue}if(N<2048){O[O.length]=r[192|N>>6]+r[128|N&63];continue}if(N<55296||N>=57344){O[O.length]=r[224|N>>12]+r[128|N>>6&63]+r[128|N&63];continue}P+=1,N=65536+((N&1023)<<10|I.charCodeAt(P)&1023),O[O.length]=r[240|N>>18]+r[128|N>>12&63]+r[128|N>>6&63]+r[128|N&63]}E+=O.join("")}return E},h=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],_=0;_<w.length;++_)for(var x=w[_],v=x.obj[x.prop],E=Object.keys(v),S=0;S<E.length;++S){var I=E[S],O=v[I];typeof O=="object"&&O!==null&&m.indexOf(O)===-1&&(w.push({obj:v,prop:I}),m.push(O))}return i(w),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},b=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},f=function(y,w){return[].concat(y,w)},g=function(y,w){if(t(y)){for(var m=[],_=0;_<y.length;_+=1)m.push(w(y[_]));return m}return w(y)};return Pr={arrayToObject:n,assign:s,combine:f,compact:h,decode:l,encode:u,isBuffer:b,isRegExp:p,maybeMap:g,merge:o},Pr}function Sh(){if(Yi)return Mr;Yi=!0;var a=xh(),e=rl(),t=mo(),r=Object.prototype.hasOwnProperty,i={brackets:function(g){return g+"[]"},comma:"comma",indices:function(g,y){return g+"["+y+"]"},repeat:function(g){return g}},n=Array.isArray,o=Array.prototype.push,s=function(g,y){o.apply(g,n(y)?y:[y])},l=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(g){return l.call(g)},skipNulls:!1,strictNullHandling:!1},h=function(g){return typeof g=="string"||typeof g=="number"||typeof g=="boolean"||typeof g=="symbol"||typeof g=="bigint"},p={},b=function g(y,w,m,_,x,v,E,S,I,O,P,N,T,q,D,U,ae,Y){for(var V=y,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var M=re.get(y);if(F+=1,typeof M<"u"){if(M===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=0)}if(typeof O=="function"?V=O(w,V):V instanceof Date?V=T(V):m==="comma"&&n(V)&&(V=e.maybeMap(V,function(R){return R instanceof Date?T(R):R})),V===null){if(v)return I&&!U?I(w,u.encoder,ae,"key",q):w;V=""}if(h(V)||e.isBuffer(V)){if(I){var J=U?w:I(w,u.encoder,ae,"key",q);return[D(J)+"="+D(I(V,u.encoder,ae,"value",q))]}return[D(w)+"="+D(String(V))]}var be=[];if(typeof V>"u")return be;var te;if(m==="comma"&&n(V))U&&I&&(V=e.maybeMap(V,I)),te=[{value:V.length>0?V.join(",")||null:void 0}];else if(n(O))te=O;else{var we=Object.keys(V);te=P?we.sort(P):we}var G=S?w.replace(/\./g,"%2E"):w,j=_&&n(V)&&V.length===1?G+"[]":G;if(x&&n(V)&&V.length===0)return j+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],K=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&K===null)){var Q=N&&S?W.replace(/\./g,"%2E"):W,ge=n(V)?typeof m=="function"?m(j,Q):j:j+(N?"."+Q:"["+Q+"]");Y.set(y,F);var oe=a();oe.set(p,Y),s(be,g(K,ge,m,_,x,v,E,S,m==="comma"&&U&&n(V)?null:I,O,P,N,T,q,D,U,ae,oe))}}return be},f=function(g){if(!g)return u;if(typeof g.allowEmptyArrays<"u"&&typeof g.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof g.encodeDotInKeys<"u"&&typeof g.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(g.encoder!==null&&typeof g.encoder<"u"&&typeof g.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=g.charset||u.charset;if(typeof g.charset<"u"&&g.charset!=="utf-8"&&g.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof g.format<"u"){if(!r.call(t.formatters,g.format))throw new TypeError("Unknown format option provided.");w=g.format}var m=t.formatters[w],_=u.filter;(typeof g.filter=="function"||n(g.filter))&&(_=g.filter);var x;if(g.arrayFormat in i?x=g.arrayFormat:"indices"in g?x=g.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in g&&typeof g.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof g.allowDots>"u"?g.encodeDotInKeys===!0?!0:u.allowDots:!!g.allowDots;return{addQueryPrefix:typeof g.addQueryPrefix=="boolean"?g.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof g.allowEmptyArrays=="boolean"?!!g.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof g.charsetSentinel=="boolean"?g.charsetSentinel:u.charsetSentinel,commaRoundTrip:g.commaRoundTrip,delimiter:typeof g.delimiter>"u"?u.delimiter:g.delimiter,encode:typeof g.encode=="boolean"?g.encode:u.encode,encodeDotInKeys:typeof g.encodeDotInKeys=="boolean"?g.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof g.encoder=="function"?g.encoder:u.encoder,encodeValuesOnly:typeof g.encodeValuesOnly=="boolean"?g.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:w,formatter:m,serializeDate:typeof g.serializeDate=="function"?g.serializeDate:u.serializeDate,skipNulls:typeof g.skipNulls=="boolean"?g.skipNulls:u.skipNulls,sort:typeof g.sort=="function"?g.sort:null,strictNullHandling:typeof g.strictNullHandling=="boolean"?g.strictNullHandling:u.strictNullHandling}};return Mr=function(g,y){var w=g,m=f(y),_,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,_=x);var v=[];if(typeof w!="object"||w===null)return"";var E=i[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;_||(_=Object.keys(w)),m.sort&&_.sort(m.sort);for(var I=a(),O=0;O<_.length;++O){var P=_[O];m.skipNulls&&w[P]===null||s(v,b(w[P],P,E,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var N=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&"),N.length>0?T+N:""},Mr}function Eh(){if(Qi)return Rr;Qi=!0;var a=rl(),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:a.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},i=function(p){return p.replace(/&#(\d+);/g,function(b,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,b){return p&&typeof p=="string"&&b.comma&&p.indexOf(",")>-1?p.split(","):p},o="utf8=%26%2310003%3B",s="utf8=%E2%9C%93",l=function(p,b){var f={__proto__:null},g=b.ignoreQueryPrefix?p.replace(/^\?/,""):p;g=g.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=b.parameterLimit===1/0?void 0:b.parameterLimit,w=g.split(b.delimiter,y),m=-1,_,x=b.charset;if(b.charsetSentinel)for(_=0;_<w.length;++_)w[_].indexOf("utf8=")===0&&(w[_]===s?x="utf-8":w[_]===o&&(x="iso-8859-1"),m=_,_=w.length);for(_=0;_<w.length;++_)if(_!==m){var v=w[_],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,O;S===-1?(I=b.decoder(v,r.decoder,x,"key"),O=b.strictNullHandling?null:""):(I=b.decoder(v.slice(0,S),r.decoder,x,"key"),O=a.maybeMap(n(v.slice(S+1),b),function(N){return b.decoder(N,r.decoder,x,"value")})),O&&b.interpretNumericEntities&&x==="iso-8859-1"&&(O=i(O)),v.indexOf("[]=")>-1&&(O=t(O)?[O]:O);var P=e.call(f,I);P&&b.duplicates==="combine"?f[I]=a.combine(f[I],O):(!P||b.duplicates==="last")&&(f[I]=O)}return f},c=function(p,b,f,g){for(var y=g?b:n(b,f),w=p.length-1;w>=0;--w){var m,_=p[w];if(_==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(y===""||f.strictNullHandling&&y===null)?[]:[].concat(y);else{m=f.plainObjects?Object.create(null):{};var x=_.charAt(0)==="["&&_.charAt(_.length-1)==="]"?_.slice(1,-1):_,v=f.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!f.parseArrays&&v===""?m={0:y}:!isNaN(E)&&_!==v&&String(E)===v&&E>=0&&f.parseArrays&&E<=f.arrayLimit?(m=[],m[E]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,b,f,g){if(p){var y=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,_=f.depth>0&&w.exec(y),x=_?y.slice(0,_.index):y,v=[];if(x){if(!f.plainObjects&&e.call(Object.prototype,x)&&!f.allowPrototypes)return;v.push(x)}for(var E=0;f.depth>0&&(_=m.exec(y))!==null&&E<f.depth;){if(E+=1,!f.plainObjects&&e.call(Object.prototype,_[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(_[1])}if(_){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+y.slice(_.index)+"]")}return c(v,b,f,g)}},h=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var b=typeof p.charset>"u"?r.charset:p.charset,f=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var g=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:g,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:b,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||a.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:f,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:r.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:r.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:r.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:r.strictNullHandling}};return Rr=function(p,b){var f=h(b);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?l(p,f):p,y=f.plainObjects?Object.create(null):{},w=Object.keys(g),m=0;m<w.length;++m){var _=w[m],x=u(_,g[_],f,typeof p=="string");y=a.merge(y,x,f)}return f.allowSparse===!0?y:a.compact(y)},Rr}function Ah(){if(Ji)return Lr;Ji=!0;var a=Sh(),e=Eh(),t=mo();return Lr={formats:t,parse:e,stringify:a},Lr}function Ih(){if(Xi)return vt;Xi=!0;var a=yt;function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var t=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,i=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
7
+ `," "],o=["{","}","|","\\","^","`"].concat(n),s=["'"].concat(o),l=["%","/","?",";","#"].concat(s),c=["/","?","#"],u=255,h=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=Ah();function w(v,E,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,E,S),I}e.prototype.parse=function(v,E,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),O=I!==-1&&I<v.indexOf("#")?"?":"#",P=v.split(O),N=/\\/g;P[0]=P[0].replace(N,"/"),v=P.join(O);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var q=i.exec(T);if(q)return this.path=T,this.href=T,this.pathname=q[1],q[2]?(this.search=q[2],E?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var U=D.toLowerCase();this.protocol=U,T=T.substr(D.length)}if(S||D||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(D&&f[D])&&(T=T.substr(2),this.slashes=!0)}if(!f[D]&&(ae||D&&!g[D])){for(var Y=-1,V=0;V<c.length;V++){var re=T.indexOf(c[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var F,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(F=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(F)),Y=-1;for(var V=0;V<l.length;V++){var re=T.indexOf(l[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var J=this.hostname.split(/\./),V=0,be=J.length;V<be;V++){var te=J[V];if(te&&!te.match(h)){for(var we="",G=0,j=te.length;G<j;G++)te.charCodeAt(G)>127?we+="x":we+=te[G];if(!we.match(h)){var ne=J.slice(0,V),W=J.slice(V+1),K=te.match(p);K&&(ne.push(K[1]),W.unshift(K[2])),W.length&&(T="/"+W.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=a.toASCII(this.hostname));var Q=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+Q,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!b[U])for(var V=0,be=s.length;V<be;V++){var oe=s[V];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var $=T.indexOf("#");$!==-1&&(this.hash=T.substr($),T=T.slice(0,$));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),E&&(this.query=y.parse(this.query)),T=T.slice(0,ee)):E&&(this.search="",this.query={}),T&&(this.pathname=T),g[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Q=this.pathname||"",de=this.search||"";this.path=Q+de}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=w(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var E=this.protocol||"",S=this.pathname||"",I=this.hash||"",O=!1,P="";this.host?O=v+this.host:this.hostname&&(O=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(O+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(P=y.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var N=this.search||P&&"?"+P||"";return E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||g[E])&&O!==!1?(O="//"+(O||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):O||(O=""),I&&I.charAt(0)!=="#"&&(I="#"+I),N&&N.charAt(0)!=="?"&&(N="?"+N),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),N=N.replace("#","%23"),E+O+S+N+I};function _(v,E){return w(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function x(v,E){return v?w(v,!1,!0).resolveObject(E):E}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var E=new e;E.parse(v,!1,!0),v=E}for(var S=new e,I=Object.keys(this),O=0;O<I.length;O++){var P=I[O];S[P]=this[P]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var N=Object.keys(v),T=0;T<N.length;T++){var q=N[T];q!=="protocol"&&(S[q]=v[q])}return g[S.protocol]&&S.hostname&&!S.pathname&&(S.pathname="/",S.path=S.pathname),S.href=S.format(),S}if(v.protocol&&v.protocol!==S.protocol){if(!g[v.protocol]){for(var D=Object.keys(v),U=0;U<D.length;U++){var ae=D[U];S[ae]=v[ae]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!f[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),S.pathname=be.join("/")}else S.pathname=v.pathname;if(S.search=v.search,S.query=v.query,S.host=v.host||"",S.auth=v.auth,S.hostname=v.hostname||v.host,S.port=v.port,S.pathname||S.search){var Y=S.pathname||"",V=S.search||"";S.path=Y+V}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||re||S.host&&v.pathname,M=Z,J=S.pathname&&S.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!g[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(J[0]===""?J[0]=S.host:J.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||J[0]==="")),F)S.host=v.host||v.host===""?v.host:S.host,S.hostname=v.hostname||v.hostname===""?v.hostname:S.hostname,S.search=v.search,S.query=v.query,J=be;else if(be.length)J||(J=[]),J.pop(),J=J.concat(be),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=J.shift(),S.hostname=S.host;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return S.search=v.search,S.query=v.query,(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S}if(!J.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var G=J.slice(-1)[0],j=(S.host||v.host||J.length>1)&&(G==="."||G==="..")||G==="",ne=0,W=J.length;W>=0;W--)G=J[W],G==="."?J.splice(W,1):G===".."?(J.splice(W,1),ne++):ne&&(J.splice(W,1),ne--);if(!Z&&!M)for(;ne--;ne)J.unshift("..");Z&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),j&&J.join("/").substr(-1)!=="/"&&J.push("");var K=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(te){S.hostname=K?"":J.length?J.shift():"",S.host=S.hostname;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return Z=Z||S.host&&J.length,Z&&!K&&J.unshift(""),J.length>0?S.pathname=J.join("/"):(S.pathname=null,S.path=null),(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=v.auth||S.auth,S.slashes=S.slashes||v.slashes,S.href=S.format(),S},e.prototype.parseHost=function(){var v=this.host,E=r.exec(v);E&&(E=E[0],E!==":"&&(this.port=E.substr(1)),v=v.substr(0,v.length-E.length)),v&&(this.hostname=v)},vt.parse=w,vt.resolve=_,vt.resolveObject=x,vt.format=m,vt.Url=e,vt}function nl(a){if(typeof a=="string")a=new URL(a);else if(!(a instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(a.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Ur?Th(a):Ch(a)}function Th(a){let e=a.hostname,t=a.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let i=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&i===102||t[r+1]==="5"&&i===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(gl,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,i=t[2];if(r<pl||r>ml||i!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Ch(a){if(a.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=a.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 il(a){let e=Wi.resolve(a),t=a.charCodeAt(a.length-1);(t===fl||Ur&&t===dl)&&e[e.length-1]!==Wi.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(bl,"%25")),!Ur&&e.includes("\\")&&(e=e.replace(yl,"%5C")),e.includes(`
8
+ `)&&(e=e.replace(vl,"%0A")),e.includes("\r")&&(e=e.replace(wl,"%0D")),e.includes(" ")&&(e=e.replace(_l,"%09")),r.pathname=e,r}var ol,Ir,zi,Tr,Cr,Vi,Or,Gi,Pr,Ki,Mr,Yi,Rr,Qi,Lr,Ji,vt,Xi,qe,Cs,sl,al,ll,cl,ul,hl,dl,fl,pl,ml,Ur,gl,bl,yl,vl,wl,_l,Oh=Ve(()=>{le(),ue(),ce(),Gu(),ch(),_h(),el(),ol=Object.freeze(Object.create(null)),Ir={},zi=!1,Tr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Cr={},Vi=!1,Or={},Gi=!1,Pr={},Ki=!1,Mr={},Yi=!1,Rr={},Qi=!1,Lr={},Ji=!1,vt={},Xi=!1,qe=Ih(),qe.parse,qe.resolve,qe.resolveObject,qe.format,qe.Url,Cs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,qe.URL=typeof URL<"u"?URL:null,qe.pathToFileURL=il,qe.fileURLToPath=nl,sl=qe.Url,al=qe.format,ll=qe.resolve,cl=qe.resolveObject,ul=qe.parse,hl=qe.URL,dl=92,fl=47,pl=97,ml=122,Ur=Cs==="win32",gl=/\//g,bl=/%/g,yl=/\\/g,vl=/\n/g,wl=/\r/g,_l=/\t/g}),Ph=pe((a,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")}}),go=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0}),a.BufferedDuplex=void 0,a.writev=r;var e=Pt(),t=(Be(),Pe(Ue));function r(n,o){let s=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?s[l]=t.Buffer.from(n[l].chunk,"utf8"):s[l]=n[l].chunk;this._write(t.Buffer.concat(s),"binary",o)}var i=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,o,s){super({objectMode:!0}),this.proxy=o,this.socket=s,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,o,s){this.isSocketOpen?this.writeToProxy(n,o,s):this.writeQueue.push({chunk:n,encoding:o,cb:s})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,o){this.writeQueue=[],this.proxy.destroy(),o(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,o,s){this.proxy.write(n,o)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:o,cb:s}=this.writeQueue.shift();this.writeToProxy(n,o,s)}}};a.BufferedDuplex=i}),sr=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(a,"__esModule",{value:!0}),a.streamBuilder=a.browserStreamBuilder=void 0;var t=(Be(),Pe(Ue)),r=e(Ph()),i=e(ht()),n=Pt(),o=e(Wr()),s=go(),l=(0,i.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let _=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(_=w.transformWsUrl(_,w,m)),_}function h(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!o.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(_=>{Object.prototype.hasOwnProperty.call(w,_)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,_)&&(m.wsOptions[_]=w[_])}),m}function p(w){let m=h(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let _=new URL(document.URL);m.hostname=_.hostname,m.port||(m.port=Number(_.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function b(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function f(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var g=(w,m)=>{l("streamBuilder");let _=h(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=b(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};a.streamBuilder=g;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=f(w,m),I=P(m,U,ae);m.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{S.close()});let O=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=I,_.socket=S):(_=new s.BufferedDuplex(m,I,S),O?S.addEventListener("open",N):S.onopen=N),O?(S.addEventListener("close",T),S.addEventListener("error",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function P(Y,V,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function N(){l("WebSocket onOpen"),_ instanceof s.BufferedDuplex&&_.socketReady()}function T(Y){l("WebSocket onClose",Y),_.end(),_.destroy()}function q(Y){l("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,_.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function U(Y,V,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,V,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch(F){return re(F)}re()}function ae(Y){S.close(),Y()}return _};a.browserStreamBuilder=y}),bo={};Dt(bo,{Server:()=>Le,Socket:()=>Le,Stream:()=>Le,_createServerHandle:()=>Le,_normalizeArgs:()=>Le,_setSimultaneousAccepts:()=>Le,connect:()=>Le,createConnection:()=>Le,createServer:()=>Le,default:()=>kl,isIP:()=>Le,isIPv4:()=>Le,isIPv6:()=>Le});function Le(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var kl,xl=Ve(()=>{le(),ue(),ce(),kl={_createServerHandle:Le,_normalizeArgs:Le,_setSimultaneousAccepts:Le,connect:Le,createConnection:Le,createServer:Le,isIP:Le,isIPv4:Le,isIPv6:Le,Server:Le,Socket:Le,Stream:Le}}),Sl=pe((a,e)=>{le(),ue(),ce(),e.exports={}}),Os=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(a,"__esModule",{value:!0});var t=e((xl(),Pe(bo))),r=e(ht()),i=e(Sl()),n=(0,r.default)("mqttjs:tcp"),o=(s,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,i.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,h=l.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};a.default=o}),El={};Dt(El,{default:()=>Al});var Al,Mh=Ve(()=>{le(),ue(),ce(),Al={}}),Ps=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(a,"__esModule",{value:!0});var t=(Mh(),Pe(El)),r=e((xl(),Pe(bo))),i=e(ht()),n=e(Sl()),o=(0,i.default)("mqttjs:tls");function s(c){let{host:u,port:h,socksProxy:p,...b}=c;if(p!==void 0){let f=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...b,socket:f})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,o("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let h=s(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(b){u.rejectUnauthorized&&c.emit("error",b),h.end()}return h.on("error",p),h};a.default=l}),Ms=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=(Be(),Pe(Ue)),t=Pt(),r=go(),i,n,o;function s(){let p=new t.Transform;return p._write=(b,f,g)=>{i.send({data:b.buffer,success(){g()},fail(y){g(new Error(y))}})},p._flush=b=>{i.close({success(){b()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,b){let f=p.protocol==="wxs"?"wss":"ws",g=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,b)),g}function u(){i.onOpen(()=>{o.socketReady()}),i.onMessage(p=>{let{data:b}=p;b instanceof ArrayBuffer?b=e.Buffer.from(b):b=e.Buffer.from(b,"utf8"),n.push(b)}),i.onClose(()=>{o.emit("close"),o.end(),o.destroy()}),i.onError(p=>{let b=new Error(p.errMsg);o.destroy(b)})}var h=(p,b)=>{if(b.hostname=b.hostname||b.host,!b.hostname)throw new Error("Could not determine host. Specify host manually.");let f=b.protocolId==="MQIsdp"&&b.protocolVersion===3?"mqttv3.1":"mqtt";l(b);let g=c(b,p);i=wx.connectSocket({url:g,protocols:[f]}),n=s(),o=new r.BufferedDuplex(b,n,i),o._destroy=(w,m)=>{i.close({success(){m&&m(w)}})};let y=o.destroy;return o.destroy=(w,m)=>(o.destroy=y,setTimeout(()=>{i.close({fail(){o._destroy(w,m)}})},0),o),u(),o};a.default=h}),Rs=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=(Be(),Pe(Ue)),t=Pt(),r=go(),i,n,o,s=!1;function l(){let b=new t.Transform;return b._write=(f,g,y)=>{i.sendSocketMessage({data:f.buffer,success(){y()},fail(){y(new Error)}})},b._flush=f=>{i.closeSocket({success(){f()}})},b}function c(b){b.hostname||(b.hostname="localhost"),b.path||(b.path="/"),b.wsOptions||(b.wsOptions={})}function u(b,f){let g=b.protocol==="alis"?"wss":"ws",y=`${g}://${b.hostname}${b.path}`;return b.port&&b.port!==80&&b.port!==443&&(y=`${g}://${b.hostname}:${b.port}${b.path}`),typeof b.transformWsUrl=="function"&&(y=b.transformWsUrl(y,b,f)),y}function h(){s||(s=!0,i.onSocketOpen(()=>{o.socketReady()}),i.onSocketMessage(b=>{if(typeof b.data=="string"){let f=e.Buffer.from(b.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(b.data)}}),i.onSocketClose(()=>{o.end(),o.destroy()}),i.onSocketError(b=>{o.destroy(b)}))}var p=(b,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let g=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let y=u(f,b);return i=f.my,i.connectSocket({url:y,protocols:g}),n=l(),o=new r.BufferedDuplex(f,n,i),h(),o};a.default=p}),Rh=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(a,"__esModule",{value:!0}),a.connectAsync=u;var t=e(ht()),r=e((Oh(),Pe(tl))),i=e(hi()),n=e(Wr());typeof Re?.nextTick!="function"&&(Re.nextTick=setImmediate);var o=(0,t.default)("mqttjs"),s=null;function l(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,b,f]=p;h.username=b,h.password=f}else h.username=h.auth}function c(h,p){if(o("connecting to an MQTT broker..."),typeof h=="object"&&!p&&(p=h,h=""),p=p||{},h&&typeof h=="string"){let g=r.default.parse(h,!0),y={};if(g.port!=null&&(y.port=Number(g.port)),y.host=g.hostname,y.query=g.query,y.auth=g.auth,y.protocol=g.protocol,y.path=g.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Re<"u"&&(p.socksProxy=Re.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(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=sr().streamBuilder,s.wss=sr().streamBuilder,s.mqtt=Os().default,s.tcp=Os().default,s.ssl=Ps().default,s.tls=s.ssl,s.mqtts=Ps().default):(s.ws=sr().browserStreamBuilder,s.wss=sr().browserStreamBuilder,s.wx=Ms().default,s.wxs=Ms().default,s.ali=Rs().default,s.alis=Rs().default)),!s[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>g&&w%2===0?!1:typeof s[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function b(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),o("calling streambuilder for",p.protocol),s[p.protocol](g,p)}let f=new i.default(b,p);return f.on("error",()=>{}),f}function u(h,p,b=!0){return new Promise((f,g)=>{let y=c(h,p),w={connect:_=>{m(),f(y)},end:()=>{m(),f(y)},error:_=>{m(),y.end(),g(_)}};b===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}a.default=c}),Ls=pe(a=>{le(),ue(),ce();var e=a&&a.__createBinding||(Object.create?function(b,f,g,y){y===void 0&&(y=g);var w=Object.getOwnPropertyDescriptor(f,g);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(b,y,w)}:function(b,f,g,y){y===void 0&&(y=g),b[y]=f[g]}),t=a&&a.__setModuleDefault||(Object.create?function(b,f){Object.defineProperty(b,"default",{enumerable:!0,value:f})}:function(b,f){b.default=f}),r=a&&a.__importStar||(function(){var b=function(f){return b=Object.getOwnPropertyNames||function(g){var y=[];for(var w in g)Object.prototype.hasOwnProperty.call(g,w)&&(y[y.length]=w);return y},b(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var y=b(f),w=0;w<y.length;w++)y[w]!=="default"&&e(g,f,y[w]);return t(g,f),g}})(),i=a&&a.__exportStar||function(b,f){for(var g in b)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,b,g)},n=a&&a.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(a,"__esModule",{value:!0}),a.ReasonCodes=a.KeepaliveManager=a.UniqueMessageIdProvider=a.DefaultMessageIdProvider=a.Store=a.MqttClient=a.connectAsync=a.connect=a.Client=void 0;var o=n(hi());a.MqttClient=o.default;var s=n(qa());a.DefaultMessageIdProvider=s.default;var l=n(zu());a.UniqueMessageIdProvider=l.default;var c=n(Ea());a.Store=c.default;var u=r(Rh());a.connect=u.default,Object.defineProperty(a,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(Ya());a.KeepaliveManager=h.default,a.Client=o.default,i(hi(),a),i($t(),a),i(Sa(),a);var p=qr();Object.defineProperty(a,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Lh=pe(a=>{le(),ue(),ce();var e=a&&a.__createBinding||(Object.create?function(o,s,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(s,l);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[l]}}),Object.defineProperty(o,c,u)}:function(o,s,l,c){c===void 0&&(c=l),o[c]=s[l]}),t=a&&a.__setModuleDefault||(Object.create?function(o,s){Object.defineProperty(o,"default",{enumerable:!0,value:s})}:function(o,s){o.default=s}),r=a&&a.__importStar||(function(){var o=function(s){return o=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},o(s)};return function(s){if(s&&s.__esModule)return s;var l={};if(s!=null)for(var c=o(s),u=0;u<c.length;u++)c[u]!=="default"&&e(l,s,c[u]);return t(l,s),l}})(),i=a&&a.__exportStar||function(o,s){for(var l in o)l!=="default"&&!Object.prototype.hasOwnProperty.call(s,l)&&e(s,o,l)};Object.defineProperty(a,"__esModule",{value:!0});var n=r(Ls());a.default=n,i(Ls(),a)});const jh=Lh();const Nh={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}/#"},Uh=300,Bh={templateId:"7",type:"link",isDeepLink:!0},Dh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Il{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={...Nh,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,i={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(i.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,o)=>{let s=!1;const l=h=>{s||(s=!0,clearTimeout(u),h())},c=(h,p)=>{s||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),l(()=>o(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=jh.connect(this.config.mqttEndpoint,i),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),s||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const h=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(h),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:h})}}),this.client.on("message",(h,p)=>{this.dispatchInbound(h,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!s){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),s||c("mqtt-error",h)}),this.client.on("disconnect",h=>{this.debugLog("DISCONNECT",{reasonCode:h?.reasonCode,properties:h?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),s||c("mqtt-offline")}),this.client.on("packetsend",h=>{(h.cmd==="subscribe"||h.cmd==="unsubscribe"||h.cmd==="pingreq")&&this.debugLog(h.cmd.toUpperCase(),{topic:h.topic,packetId:h.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[i,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[i]=`${n.slice(0,200)}…(${n.length})`:r[i]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const i=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,i)}publishFileMessage(e,t){if(!this.client)return;const r={...Bh,...this.config.fileTemplate??{},...Fh(t)},i={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},o=this.buildOutgoingEnvelope(e,{text:JSON.stringify(i),type:"html",attributes:n,metadata:i.metadata});this.publishEnvelope(e,o)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Uh){if(!this.client)return;const i=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(i,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const i=[...this.subscribedTopics];this.subscribedTopics.clear(),i.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let i=null;try{i=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!i)return;this.debugLog("RECV",{topic:e,sender:i.sender,type:i.type,contentType:i.metadata?.contentType,templateId:i.metadata?.templateId,messageId:i.message_id,text:typeof i.text=="string"?i.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",h=typeof i.status=="number"?i.status:Number(i.status??0),p={conversationId:c,messageId:u,status:h,raw:i};this.statusUpdateHandlers.forEach(b=>b(p)),this.messageHandlers.forEach(b=>b(i,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const o=e.match(this.inboundRegex),s=o?.groups?.conversationId,l={topic:e,conversationId:s,messageId:typeof i.message_id=="string"?i.message_id:void 0,kind:o?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(i,l))}buildOutgoingEnvelope(e,t){const r={...Dh,...this.config.messageDefaults??{}},i=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),o={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:i,senderFullname:i,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:o}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(i,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(i,n)=>{const o={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const s=o[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Fh(a){const e={};for(const[t,r]of Object.entries(a))r!==void 0&&(e[t]=r);return e}function Tl(a,e){return(a.sender??"").toString()===e}function Cl(a,e){const t=(a.sender??"").toString(),r=e.systemSenders??["metadata","system"],i=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(i)?"assistant":r.includes(t)?"system":"agent":"system"}function yo(a){const e={raw:a},t=a.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 a.text=="string"&&a.text.trim().startsWith("{"))try{const i=JSON.parse(a.text);typeof i.message=="string"&&(e.innerMessage=i.message);const n=i.metadata;n&&typeof n=="object"&&(!e.contentType&&typeof n.contentType=="string"&&(e.contentType=n.contentType),!e.templateId&&typeof n.templateId=="string"&&(e.templateId=n.templateId),e.payload===void 0&&n.payload!==void 0&&(e.payload=n.payload))}catch{}const r=a.attributes;if(r&&typeof r=="object"){const i=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&i&&typeof i.contentType=="string"&&(e.contentType=i.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&i&&typeof i.templateId=="string"&&(e.templateId=i.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&i&&i.payload!==void 0&&(e.payload=i.payload),e.payload===void 0&&i&&i.template!==void 0&&(e.payload=i.template)}return e}function Ol(a){const e=yo(a);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const i=r[0],n=i.action,o=n&&typeof n.url=="string"?n.url:void 0,s=typeof i.description=="string"?i.description:void 0,l=a.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!o&&!s?null:{fileName:s,fileUrl:o,cloudFileId:c,templateId:e.templateId}}function js(a,e,t){const r=Cl(a,t),i=yo(a),n=Ol(a);let o="";i.innerMessage?o=i.innerMessage:typeof a.text=="string"&&(a.text.trim().startsWith("{")?i.contentType!=="300"&&(o=a.text):o=a.text);const s=typeof a.message_id=="string"?a.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof a.timestamp=="number"?new Date(a.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof a.status=="number"?$h(a.status):"delivered",h={id:s,externalId:s,conversationId:e,role:c,content:o,createdAt:l,status:u,metadata:{sender:a.sender,sender_fullname:a.sender_fullname??a.senderFullname,app_id:a.app_id,attributes:a.attributes}};return i.contentType&&(h.template={contentType:i.contentType,templateId:i.templateId,payload:i.payload}),n?.fileUrl&&(h.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:h,template:i}}function $h(a){return a<0?"error":a>=250?"read":a>=150?"delivered":"sent"}class Pl extends ro{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 Vs(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Gs,this.conversationManager=new Ys(e.conversationId),this.usesAikaara()&&(this.connection=new zs(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.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 Il({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const i=r?"connected":"disconnected";this.emit("connection:state",i),this.config.onConnectionStateChange?.(i)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,i)=>this.handleTiledeskMessage(r,i))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),i=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;i&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const i=r.map(s=>js(s,e,{userId:t}).message).sort((s,l)=>new Date(s.createdAt).getTime()-new Date(l.createdAt).getTime()),n=this.messageStore.messages,o=[...i,...n.filter(s=>!i.some(l=>l.externalId&&l.externalId===s.externalId))];if(this.messageStore.setMessages(o),this.config.onMessage)for(const s of i)try{this.config.onMessage(s)}catch(l){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",l)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const i=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",i),this.config.onMessage?.(i);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const i=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:i.fileName,fileUrl:i.url,cloudFileId:i.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(i,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=t.conversationId??this.conversationManager.conversationId;if(!r)return;const i=this.config.tiledeskIdentity?.userId??"",{message:n,template:o}=js(e,r,{userId:i,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(Tl(e,i)){const c=this.messageStore.reconcileOptimistic(n);if(c){this.emit("message:updated",c);return}}const{message:s,deduped:l}=this.messageStore.upsertRemoteMessage(n);if(l)this.emit("message:updated",s);else{this.emit("message:received",s),this.config.onMessage?.(s);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:s.role,hasAttachments:Array.isArray(s.attachments)&&s.attachments.length>0,templateId:s.template?.templateId,messageId:s.id,conversationId:s.conversationId}}))}catch{}}if(o.contentType){const c={messageId:s.id,conversationId:r,role:n.role==="tool"?"system":n.role,contentType:o.contentType,templateId:o.templateId,payload:o.payload,innerMessage:o.innerMessage,raw:e};this.config.onTemplateMessage?.(c)}}handleTiledeskStatusUpdate(e){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{}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",i=e.content||"";i?this.messageStore.updateStreaming(i):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,i=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),i&&(this.emit("stream:end",{messageId:i.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",i),this.config.onMessage?.(i));break}case"message_queued":{const r=this.messageStore.messages.findLast(i=>i.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}const Ns={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 qh(a){const e=a.lastIndexOf(".");return e<0||e===a.length-1?"":a.slice(e+1).toLowerCase()}function Hh(a,e,t){const r=qh(a.name||"");if(r&&e&&e[r])return e[r];const i=a.type;return i&&i.trim().length>0?i:r&&Ns[r]?Ns[r]:t}function Yr(a,e){return a.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Wh(a,e){const t=e.split(".");let r=a;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return"";return typeof r=="string"?r:""}function Ml(a){const e=a.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const i=t.name||`upload-${Date.now()}`,n=Hh(t,a.contentTypeMap,a.contentTypeFallback??"application/octet-stream"),o={fileName:i,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},s=a.authHeader?await a.authHeader():void 0,l={accept:"application/json",...a.extraHeaders??{},...s?{authorization:s}:{}};let c=a.signEndpoint.includes("{")?a.signEndpoint:`${a.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=Yr(c,o),h=await fetch(u,{method:a.signMethod??"GET",headers:l});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),b=Wh(p,e);if(!b)throw new Error(`Sign response missing path "${e}"`);const f=a.s3HostRewrite?b.replace(/^https:\/\/[^/]+/i,a.s3HostRewrite):b,g=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const w=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${w.slice(0,200)}`)}if(a.registerEndpoint){const w=JSON.parse(Yr(JSON.stringify(a.registerBody??{}),o)),m=await fetch(a.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const _=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${_.slice(0,200)}`)}}return{url:a.viewerTemplate?Yr(a.viewerTemplate,o):b.split("?")[0],fileName:i,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function vo(a){return{async upload(e,t){const r=new FormData,i=a.fieldName??"file";r.append(i,e,e.name);const n=typeof a.extraFields=="function"?a.extraFields(t):a.extraFields;if(n)for(const[p,b]of Object.entries(n))r.append(p,b);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const o=typeof a.headers=="function"?await a.headers():a.headers??{},s=await fetch(a.endpoint,{method:a.method??"POST",body:r,headers:o,credentials:a.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const l=await s.json().catch(()=>({}));if(a.parseResponse)return a.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,h=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:h,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const zh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Rl(a){const e=a.apiBase.replace(/\/$/,""),t=a.pageSize??200,r=a.pathTemplate??zh;return{async fetchMessages(i,n){const o=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(i)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),s=o.startsWith("http")?o:`${e}${o.startsWith("/")?o:`/${o}`}`,l={accept:"application/json","content-type":"application/json",...a.extraHeaders??{}};if(a.getToken){const p=await a.getToken();p&&(l.authorization=p)}const c=await fetch(s,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(a.parseResponse&&u)return a.parseResponse(u);const h=u;if(h&&Array.isArray(h.result))return h.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const Vh="^[A-Z]{5}[0-9]{4}[A-Z]$",Gh="^[A-Z]{4}[0-9]{5}[A-Z]$",Kh="^[A-Z]{4}0[A-Z0-9]{6}$",Ll="^[0-9]{6}$",Yh={id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"typeOfHouseProperty",type:"radio",label:"Property Type",required:!0,options:[{value:"SOP",label:"Self-Occupied"},{value:"LOP",label:"Let-Out"}]},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",hint:"Interest deduction capped at ₹2,00,000",fields:[{id:"loanTakenFrom",type:"text",label:"Loan Taken From",required:!0},{id:"lenderName",type:"text",label:"Lender Name",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account Number",required:!0},{id:"sanctionDate",type:"date",label:"Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Home Loan Interest",currency:"₹",min:0,max:2e5},{id:"homeLoanPrinciple",type:"number",label:"Home Loan Principal",currency:"₹",min:0}]},{id:"addressDetails",type:"group",title:"Property Address",fields:[{id:"housePropertyAddress",type:"text",label:"Address"},{id:"housePropertyPincode",type:"text",label:"Pincode",maxLength:6,pattern:Ll}]},{id:"rentalDetails",type:"group",title:"Rental Income Details",showWhen:{field:"typeOfHouseProperty",equals:"LOP"},fields:[{id:"rentalIncome",type:"number",label:"Annual Rental Income",currency:"₹",required:!0,min:0},{id:"nameOfTenant",type:"text",label:"Tenant Name",required:!0},{id:"propertyTax",type:"number",label:"Municipal / Property Tax Paid",currency:"₹",min:0}]},{id:"hasCoOwnedProperty",type:"yes-no",label:"Is this property co-owned?"},{id:"coOwnerGroup",type:"group",title:"Co-Owner Details",showWhen:{field:"hasCoOwnedProperty",equals:!0},fields:[{id:"coOwnerName",type:"text",label:"Co-Owner Name",required:!0},{id:"coOwnerPan",type:"text",label:"Co-Owner PAN",required:!0,pattern:Vh,maxLength:10},{id:"coOwnerShare",type:"text",label:"Co-Owner Share (%)",placeholder:"e.g. 50",maxLength:5}]}],submitLabel:"Save"},Qh={id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",required:!0,pattern:Gh,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"basicSalary",type:"number",label:"Basic Salary",currency:"₹",required:!0,min:0},{id:"hraReceived",type:"number",label:"HRA Received",currency:"₹",min:0},{id:"leaveTravelAllowance",type:"number",label:"Leave Travel Allowance",currency:"₹",min:0},{id:"anyOtherAllowance",type:"number",label:"Other Allowances",currency:"₹",min:0},{id:"leaveEncashment",type:"number",label:"Leave Encashment",currency:"₹",min:0},{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0}]}],submitLabel:"Save"},Jh={id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"80C Investment Amount",currency:"₹",min:0,max:15e4}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Premium for Self / Spouse / Children",currency:"₹",min:0,max:25e3},{id:"us80dForParentsAmount",type:"number",label:"Premium for Parents",currency:"₹",min:0,max:5e4},{id:"hasParentOverSixty",type:"yes-no",label:"Are your parents senior citizens (60+)?"},{id:"preventiveHealthCheckUp",type:"number",label:"Preventive Health Check-up",currency:"₹",min:0},{id:"medicalExpenditure",type:"number",label:"Medical Expenditure (senior citizen)",currency:"₹",min:0}]}],submitLabel:"Save"},Xh={id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0}]}],submitLabel:"Save"},Zh={id:"capital-gains",title:"Capital Gains",icon:"📈",fields:[{id:"equityGains",type:"group",title:"Equity & Mutual Funds",fields:[{id:"shortTermEquityGain",type:"number",label:"Short-Term Capital Gain",currency:"₹"},{id:"longTermEquityGain",type:"number",label:"Long-Term Capital Gain",currency:"₹"}]},{id:"propertyGains",type:"group",title:"Land & Building",fields:[{id:"landBuildingTermType",type:"radio",label:"Holding Period",options:[{value:"short",label:"Short-Term"},{value:"long",label:"Long-Term"}]},{id:"landBuildingPurchaseValue",type:"number",label:"Purchase Value",currency:"₹"},{id:"landBuildingSellValue",type:"number",label:"Sale Value",currency:"₹"}]}],submitLabel:"Save"},ed={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"},td={id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"businessGroup",type:"group",title:"Business Details",fields:[{id:"businessName",type:"text",label:"Business / Profession Name"},{id:"businessNatureOfWork",type:"text",label:"Nature of Work"},{id:"grossReceipts",type:"number",label:"Gross Receipts / Turnover",currency:"₹",min:0},{id:"netProfit",type:"number",label:"Net Profit",currency:"₹"}]}],submitLabel:"Save"},rd={id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureIncomeGt5Lakh",type:"yes-no",label:"Is agricultural income above ₹5,00,000?"}],submitLabel:"Save"},nd={id:"exempt-income",title:"Other Exempt Income",icon:"🧾",fields:[{id:"exemptIncome",type:"number",label:"Total Exempt Income",currency:"₹",min:0},{id:"exemptIncomeNature",type:"text",label:"Nature of Exempt Income",placeholder:"e.g. PPF interest, gratuity"}],submitLabel:"Save"},id={id:"tax-paid-tds",title:"Tax Paid / TDS",icon:"🧮",fields:[{id:"tdsGroup",type:"group",title:"Tax Deducted at Source",fields:[{id:"tdsOnSalary",type:"number",label:"TDS on Salary",currency:"₹",min:0},{id:"tdsOtherThanSalary",type:"number",label:"TDS (other than salary)",currency:"₹",min:0}]},{id:"advanceTaxGroup",type:"group",title:"Advance / Self-Assessment Tax",fields:[{id:"selfAssessmentOrAdvanceTax",type:"number",label:"Advance / Self-Assessment Tax Paid",currency:"₹",min:0}]}],submitLabel:"Save"},od={id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:Kh,maxLength:11}]},{id:"immovableGroup",type:"group",title:"Immovable Assets",hint:"Required if total income exceeds ₹50,00,000",fields:[{id:"immovableAssetDescription",type:"text",label:"Description"},{id:"immovableAssetFlatNo",type:"text",label:"Flat / House No."},{id:"immovableAssetArea",type:"text",label:"Area / Locality"},{id:"immovableAssetPincode",type:"text",label:"Pincode",maxLength:6,pattern:Ll},{id:"immovableAssetCost",type:"number",label:"Cost of Asset",currency:"₹",min:0}]}],submitLabel:"Save"},sd={id:"have-a-question",title:"I only have a question",icon:"❓",fields:[{id:"question",type:"textarea",label:"What would you like to ask?",placeholder:"Type your question for the TaxBuddy expert…",required:!0,rows:5,maxLength:1e3}],submitLabel:"Send Question"},ad=[Qh,td,Zh,Xh,ed,rd,nd,Yh,Jh,id,od,sd];function ld(a,e){const t=a||{},r={userId:hd(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Oe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Oe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Oe(t.us80dForParentsAmount),r.hasParentOverSixty=Zi(t.hasParentOverSixty),r.preventiveHealthCheckUp=Oe(t.preventiveHealthCheckUp),r.medicalExpenditure=Oe(t.medicalExpenditure),r.savingBankInterest=Oe(t.savingBankInterest),r.fdInterest=Oe(t.fdInterest),r.dividend=Oe(t.dividend),r.anyOtherIncome=Oe(t.anyOtherIncome),r.cryptoSellValue=Oe(t.cryptoSellPrice),r.cryptoPurchaseAmount=Oe(t.cryptoPurchasePrice),r.vdaPurchaseCost=Oe(t.cryptoPurchasePrice),r.businessName=Me(t.businessName),r.businessAnnualTurnOver=Oe(t.grossReceipts),r.businessNetProfit=Oe(t.netProfit),r.agricultureDetails={income:Oe(t.agricultureIncome)},r.exemptIncomeAmount=Oe(t.exemptIncome),r.exemptIncomeNature=Me(t.exemptIncomeNature),Oe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Me(t.exemptIncomeNature)??"Exempt income",value:String(Oe(t.exemptIncome))}]),r.bankAccountNumber=Me(t.bankAccountNumber),r.bankIfscCode=Me(t.bankIfscCode),(Me(t.bankAccountNumber)||Me(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Me(t.bankAccountNumber),bankIfscCode:Me(t.bankIfscCode)}]);const i={description:Me(t.immovableAssetDescription),flatNo:Me(t.immovableAssetFlatNo),area:Me(t.immovableAssetArea),pinCode:Me(t.immovableAssetPincode),amount:Oe(t.immovableAssetCost)};Object.values(i).some(s=>s!==void 0)&&(r.immovableAsset=[i]);const n=Qr(t.hpDetails,cd);n.length&&(r.hpDetails=n);const o=Qr(t.salaryDetails,ud);if(o.length){r.salaryIncome=o;const s=Qr(t.salaryDetails,c=>({grossSalary:Oe(c.grossSalary),employerName:Me(c.employerName)}));s.length&&(r.salary=s);const l=jl(t.salaryDetails)[0]??{};r.hraAmount=Oe(l.hraReceived),r.leaveTravelAllowanceAmount=Oe(l.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Oe(l.leaveEncashment),r.anyOtherAllowanceAmount=Oe(l.anyOtherAllowance),r.salaryIncomeFlag=!0}return Br(r)}function cd(a){const e={loanType:"HOME_LOAN",loanTakenFrom:Me(a.loanTakenFrom),bankOrInstituteName:Me(a.lenderName),loanAccountNo:Me(a.loanAccountNumber),loanSanctionDate:dd(a.sanctionDate),totalLoanAmount:Oe(a.totalLoanAmount),interest:Oe(a.homeLoanInterest)},t=Object.entries(e).some(([r,i])=>r!=="loanType"&&i!==void 0);return{typeOfHouseProperty:Me(a.typeOfHouseProperty),hasRentalIncome:a.typeOfHouseProperty==="LOP"?!0:Zi(a.hasRentalIncome),homeLoanInterest:Oe(a.homeLoanInterest),homeLoanPrinciple:Oe(a.homeLoanPrinciple),housePropertyAddress:Me(a.housePropertyAddress),housePropertyPincode:Me(a.housePropertyPincode),rentalIncome:Oe(a.rentalIncome),nameOfTenant:Me(a.nameOfTenant),propertyTax:Oe(a.propertyTax),hasCoOwnedProperty:Zi(a.hasCoOwnedProperty),coOwnerName:Me(a.coOwnerName),coOwnerPan:Me(a.coOwnerPan),coOwnerShare:Me(a.coOwnerShare),loanDetails:t?[e]:void 0}}function ud(a){return{grossSalaryIncome:Oe(a.grossSalary),salary:Oe(a.basicSalary),employer:{employerName:Me(a.employerName),employerTan:Me(a.employerTan)},allowance:{hraAmount:Oe(a.hraReceived),leaveTravelAllowanceAmount:Oe(a.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Oe(a.leaveEncashment),anyOtherAllowanceAmount:Oe(a.anyOtherAllowance)}}}function hd(a){if(a===void 0||a==="")return;const e=Number(a);return Number.isFinite(e)&&String(e)===String(a)?e:a}function Oe(a){if(a==null||a==="")return;const e=typeof a=="number"?a:Number(a);return Number.isFinite(e)?e:void 0}function Me(a){if(a==null)return;const e=String(a).trim();return e===""?void 0:e}function Zi(a){return a===!0||a===!1?a:void 0}function dd(a){const e=Me(a);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function jl(a){return Array.isArray(a)?a.filter(e=>e&&typeof e=="object"):[]}function Qr(a,e){return jl(a).map(t=>Br(e(t))).filter(t=>t!==void 0)}function Br(a){if(Array.isArray(a)){const e=a.map(Br).filter(t=>t!==void 0);return e.length?e:void 0}if(a&&typeof a=="object"){const e={};for(const[t,r]of Object.entries(a)){const i=Br(r);i!==void 0&&(e[t]=i)}return Object.keys(e).length?e:void 0}return a}function Us(){if(typeof window>"u")return null;const a=window,e=a.__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=e.getChatJwt,r=a.__aikaara_descriptor__??{},i=gd(r.api?.baseUrl)??bd(r.auth?.endpoint)??"",n=r.itr?.automationSubmitUrl||fd(e.configBase,e.slug);return!n&&!i?(console.warn(`[smart-edit] API disabled: no submit URL could be derived (configBase=${e.configBase??"undefined"}, slug=${e.slug??"undefined"}).`),null):(console.info("[smart-edit] API config — submitUrl:",n||"(none)","· baseUrl:",i||"(none)"),{baseUrl:i,getToken:()=>t(),headers:yd(r.auth?.headers),assessmentYear:r.itr?.assessmentYear||wd(),isRevised:"N",userId:vd(e.identity),submitUrl:n})}function fd(a,e){return!a||!e?void 0:`${a.replace(/\/+$/,"")}/api/v1/projects/by-slug/${encodeURIComponent(e)}/itr/automation-data`}async function pd(a){const e=await a.getToken(),t=a.userId||Nl(e,"sub");if(!t)throw new Error("[smart-edit] could not resolve userId for GET /itr/automation/eligible");const r=new URLSearchParams({userId:t,assessmentYear:a.assessmentYear,isRevised:a.isRevised}),i=await fetch(`${a.baseUrl}/itr/automation/eligible?${r}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...a.headers}});if(!i.ok){const n=await i.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/automation/eligible → ${i.status} ${n.slice(0,200)}`)}return Ul(await i.json().catch(()=>({})))}async function md(a,e){const t=await a.getToken(),r=a.userId||Nl(t,"sub"),i=ld(e,{userId:r,assessmentYear:a.assessmentYear,isRevised:a.isRevised}),n=a.submitUrl||`${a.baseUrl}/itr/v1/lanretni/automation/data`,o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...a.headers};a.txbdyApiKey&&(o["txbdy-api-key"]=a.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(i).join(", "));const s=await fetch(n,{method:"PUT",headers:o,body:JSON.stringify(i)});if(!s.ok){const l=await s.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${s.status} ${l.slice(0,200)}`)}return Ul(await s.json().catch(()=>({})))}function gd(a){if(!a)return null;let e=a.trim().replace(/\/+$/,"");return e=e.replace(/\/itr$/i,""),e||null}function bd(a){if(!a)return null;try{return new URL(a).origin}catch{return null}}function yd(a){const e={};if(!a)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,i]of Object.entries(a))!t.test(r)&&typeof i=="string"&&(e[r]=i);return e}function vd(a){if(!a)return;const e=a.userId??a.id??a.ext_uid??a.extUid;return e==null||e===""?void 0:String(e)}function Nl(a,e){try{const t=a.split(".")[1];if(!t)return"";const i=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))[e];return i==null?"":String(i)}catch{return""}}function Ul(a){if(a&&typeof a=="object"){const e=a;return e.data&&typeof e.data=="object"?e.data:e}return{}}function wd(){const a=new Date,e=a.getMonth()>=3?a.getFullYear():a.getFullYear()-1;return`${e}-${e+1}`}class _d{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Pl(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;const r=this.client.config.templateActionAttributes??{},i=t.attributes?.action??{},n={...t.attributes,action:{...r,...i}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:ad,data:{}});const t=Us();if(!(!t||!t.baseUrl))try{const r=await pd(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-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=Us();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await md(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 Bl 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||Ac,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||_o,position:this.getAttribute("position")||this._config.position||Ec,width:Number(this.getAttribute("width"))||this._config.width||_c,height:Number(this.getAttribute("height"))||this._config.height||kc,fontFamily:this._config.fontFamily||Sc,borderRadius:this._config.borderRadius??xc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||ko,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||Ic,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,i){if(typeof document>"u")return;const n=document.documentElement,o=(s,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${s}`,l)};o("primary",e?.primary??t),o("primary-hover",e?.primaryHover),o("primary-contrast",e?.primaryContrast),o("surface",e?.surface),o("surface-muted",e?.surfaceMuted),o("border",e?.border),o("text",e?.text),o("text-muted",e?.textMuted),o("font",e?.font??i),o("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),o("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),o("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),o("user-bubble-bg",e?.userBubbleBg),o("user-bubble-text",e?.userBubbleText),o("bot-bubble-bg",e?.botBubbleBg),o("bot-bubble-text",e?.botBubbleText),o("modal-width",e?.modalWidth),o("modal-height",e?.modalHeight),o("modal-max-width",e?.modalMaxWidth),o("modal-max-height",e?.modalMaxHeight),o("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=i=>typeof i=="number"?`${i}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,i])=>i!==void 0&&i!=="").map(([i,n])=>`--aikaara-${i}: ${n};`).join(`
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
+ font-family: var(--aikaara-font);
11
+ position: fixed;
12
+ z-index: 9999;
13
+ bottom: var(--aikaara-offset-y);
14
+ ${e.position==="bottom-left"?"left":"right"}: var(--aikaara-offset-x);
15
+ `,i=`
16
+ font-family: var(--aikaara-font);
17
+ display: flex;
18
+ flex-direction: column;
19
+ width: 100%;
20
+ height: 100%;
21
+ min-height: var(--aikaara-embed-min-height, 560px);
22
+ `,n=`
23
+ width: var(--aikaara-panel-width);
24
+ height: var(--aikaara-panel-height);
25
+ max-height: calc(100vh - 100px);
26
+ border-radius: var(--aikaara-radius);
27
+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
28
+ border: 1px solid var(--aikaara-border);
29
+ position: absolute;
30
+ bottom: calc(var(--aikaara-bubble-size) + 16px);
31
+ ${e.position==="bottom-left"?"left":"right"}: 0;
32
+ transition: opacity 200ms ease, transform 200ms ease;
33
+ `,o=`
34
+ width: 100%;
35
+ flex: 1 1 auto;
36
+ min-height: 0;
37
+ border-radius: var(--aikaara-radius);
38
+ border: 1px solid var(--aikaara-border);
39
+ position: relative;
40
+ `;this.shadow.innerHTML=`
41
+ <style>
42
+ :host {
43
+ --aikaara-primary: ${e.primaryColor};
44
+ --aikaara-primary-hover: ${this.darkenColor(e.primaryColor||_o)};
45
+ /* Cascade through descriptor.theme.surface / surfaceMuted /
46
+ * text / textMuted / border when those are present (themeVars
47
+ * sets the canonical token below). When the descriptor doesn't
48
+ * theme the chat, the legacy literal defaults still apply, so
49
+ * an un-themed widget renders exactly as it did before 0.8.5. */
50
+ --aikaara-bg: var(--aikaara-surface, #ffffff);
51
+ --aikaara-bg-secondary: var(--aikaara-surface-muted, #f9fafb);
52
+ --aikaara-text: var(--aikaara-text, #1f2937);
53
+ --aikaara-text-secondary: var(--aikaara-text-muted, #6b7280);
54
+ --aikaara-border: var(--aikaara-border, #e5e7eb);
55
+ --aikaara-radius: ${e.borderRadius}px;
56
+ --aikaara-font: ${e.fontFamily};
57
+ --aikaara-panel-width: ${e.width}px;
58
+ --aikaara-panel-height: ${e.height}px;
59
+ --aikaara-bubble-size: 60px;
60
+ --aikaara-offset-x: ${e.offset?.x??20}px;
61
+ --aikaara-offset-y: ${e.offset?.y??20}px;
62
+ ${this.themeVars(e.themeTokens)}
63
+ ${t?i:r}
64
+ }
65
+
66
+ .aikaara-panel {
67
+ background: var(--aikaara-bg);
68
+ display: flex;
69
+ flex-direction: column;
70
+ overflow: hidden;
71
+ ${t?o:n}
72
+ }
73
+
74
+ .aikaara-panel[hidden] {
75
+ display: none;
76
+ }
77
+
78
+ .aikaara-panel.entering {
79
+ opacity: 0;
80
+ transform: translateY(8px) scale(0.98);
81
+ }
82
+
83
+ .aikaara-panel.visible {
84
+ opacity: 1;
85
+ transform: translateY(0) scale(1);
86
+ }
87
+
88
+ aikaara-chat-header,
89
+ aikaara-message-list,
90
+ aikaara-chat-input,
91
+ aikaara-error-banner {
92
+ display: block;
93
+ }
94
+
95
+ aikaara-message-list {
96
+ flex: 1;
97
+ overflow: scroll;
98
+ min-height: 0;
99
+ }
100
+
101
+ aikaara-chat-input { flex-shrink: 0; }
102
+ aikaara-chat-header { flex-shrink: 0; }
103
+ </style>
104
+
105
+ ${t?"":"<aikaara-chat-bubble></aikaara-chat-bubble>"}
106
+
107
+ <div class="aikaara-panel ${t?"visible":"entering"}" ${t?"":"hidden"} role="${t?"region":"dialog"}" aria-label="Chat">
108
+ ${e.showHeader===!1?"":`<aikaara-chat-header
109
+ title="${e.title||"Chat"}"
110
+ ${e.subtitle?`subtitle="${e.subtitle}"`:""}
111
+ ${e.avatarUrl?`avatar-url="${e.avatarUrl}"`:""}
112
+ ></aikaara-chat-header>`}
113
+ <aikaara-message-list></aikaara-message-list>
114
+ <aikaara-chat-input
115
+ placeholder="${e.placeholder||ko}"
116
+ ${this._config.uploadAdapter?"":"disable-attach"}
117
+ ${e.input?.attachPosition==="right"?'attach-position="right"':""}
118
+ ${e.input?.sendButtonShape==="square"?'send-shape="square"':""}
119
+ ></aikaara-chat-input>
120
+ <aikaara-error-banner></aikaara-error-banner>
121
+ </div>
122
+ `;const s=this.shadow.querySelector("aikaara-message-list");if(s){e.hideSystemMessages?.length&&s.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&s.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&s.setShowTimestamps?.(e.showTimestamps);const l=e.templateLayout;l&&s.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 _d(e,this.shadow,{uploadAdapter:this._config.uploadAdapter,historyAdapter:this._config.historyAdapter}),await this.controller.connect())}sendUserEvent(e,t,r){this.controller?.sendUserEvent(e,t,r)}getClient(){return this.controller?.getClient()??null}darkenColor(e){try{const t=parseInt(e.replace("#",""),16),r=Math.max(0,(t>>16)-20),i=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|i<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class Dl 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
+ <style>
124
+ .bubble {
125
+ width: var(--aikaara-bubble-size, 60px);
126
+ height: var(--aikaara-bubble-size, 60px);
127
+ border-radius: 50%;
128
+ background: var(--aikaara-primary, #6366f1);
129
+ color: #ffffff;
130
+ border: none;
131
+ cursor: pointer;
132
+ display: flex;
133
+ align-items: center;
134
+ justify-content: center;
135
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
136
+ transition: transform 200ms ease, box-shadow 200ms ease;
137
+ }
138
+ .bubble:hover {
139
+ transform: scale(1.05);
140
+ box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
141
+ }
142
+ .bubble svg {
143
+ width: 28px;
144
+ height: 28px;
145
+ }
146
+ .bubble-text {
147
+ font-family: var(--aikaara-font, system-ui, sans-serif);
148
+ font-size: 12px;
149
+ font-weight: 500;
150
+ }
151
+ </style>
152
+ <button class="bubble" aria-label="Open chat">
153
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
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
+ </svg>
156
+ </button>
157
+ `}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const kd=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class Fl extends HTMLElement{shadow;actions=kd;menuOpen=!1;outsideClickHandler=null;static get observedAttributes(){return["title","subtitle","avatar-url","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.bindHandlers()}disconnectedCallback(){this.outsideClickHandler&&document.removeEventListener("click",this.outsideClickHandler,!0)}attributeChangedCallback(){this.render(),this.bindHandlers()}setActions(e){this.actions=e,this.render(),this.bindHandlers()}bindHandlers(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))}),this.shadow.querySelector(".menu-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.toggleMenu()}),this.shadow.querySelectorAll(".menu-item").forEach(t=>{t.addEventListener("click",r=>{r.stopPropagation();const i=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:i,label:n},bubbles:!0,composed:!0}))})}),this.outsideClickHandler||(this.outsideClickHandler=t=>{!this.menuOpen||t.composedPath().includes(this)||this.closeMenu()},document.addEventListener("click",this.outsideClickHandler,!0))}toggleMenu(){this.menuOpen=!this.menuOpen;const e=this.shadow.querySelector(".menu");e&&e.classList.toggle("open",this.menuOpen)}closeMenu(){if(!this.menuOpen)return;this.menuOpen=!1;const e=this.shadow.querySelector(".menu");e&&e.classList.remove("open")}iconSvg(e){return e==="edit"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>':e==="mail"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>':e==="star"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>':""}render(){const e=this.getAttribute("title")||"Chat",t=this.getAttribute("subtitle")||"",r=this.getAttribute("avatar-url"),i=this.getAttribute("status")||"connected",n=i==="connected"?"#10b981":i==="connecting"||i==="reconnecting"?"#f59e0b":"#ef4444",o=this.actions.map(s=>`
158
+ <button class="menu-item" type="button" data-action-id="${s.id}" data-action-label="${s.label}">
159
+ <span class="menu-item-icon">${this.iconSvg(s.icon)}</span>
160
+ <span class="menu-item-label">${s.label}</span>
161
+ </button>`).join("");this.shadow.innerHTML=`
162
+ <style>
163
+ :host { position: relative; display: block; }
164
+ .header {
165
+ display: flex;
166
+ align-items: center;
167
+ gap: 12px;
168
+ padding: 14px 16px;
169
+ background: var(--aikaara-primary, #6366f1);
170
+ color: #ffffff;
171
+ flex-shrink: 0;
172
+ }
173
+ .avatar {
174
+ width: 36px;
175
+ height: 36px;
176
+ border-radius: 50%;
177
+ background: rgba(255,255,255,0.2);
178
+ display: flex;
179
+ align-items: center;
180
+ justify-content: center;
181
+ flex-shrink: 0;
182
+ overflow: hidden;
183
+ }
184
+ .avatar img {
185
+ width: 100%;
186
+ height: 100%;
187
+ object-fit: cover;
188
+ }
189
+ .avatar svg {
190
+ width: 20px;
191
+ height: 20px;
192
+ }
193
+ .info {
194
+ flex: 1;
195
+ min-width: 0;
196
+ }
197
+ .title {
198
+ font-size: 15px;
199
+ font-weight: 600;
200
+ line-height: 1.2;
201
+ display: flex;
202
+ align-items: center;
203
+ gap: 6px;
204
+ }
205
+ .status-dot {
206
+ width: 8px;
207
+ height: 8px;
208
+ border-radius: 50%;
209
+ flex-shrink: 0;
210
+ }
211
+ .subtitle {
212
+ font-size: 12px;
213
+ opacity: 0.85;
214
+ white-space: nowrap;
215
+ overflow: hidden;
216
+ text-overflow: ellipsis;
217
+ }
218
+ .actions { display: flex; align-items: center; gap: 4px; }
219
+ .icon-btn {
220
+ background: none;
221
+ border: none;
222
+ color: #ffffff;
223
+ cursor: pointer;
224
+ padding: 4px;
225
+ border-radius: 4px;
226
+ display: flex;
227
+ align-items: center;
228
+ justify-content: center;
229
+ opacity: 0.8;
230
+ transition: opacity 200ms, background 200ms;
231
+ }
232
+ .close-btn {
233
+ display: var(--aikaara-close-btn-display, flex);
234
+ }
235
+ .icon-btn:hover {
236
+ opacity: 1;
237
+ background: rgba(255,255,255,0.12);
238
+ }
239
+ .icon-btn svg {
240
+ width: 20px;
241
+ height: 20px;
242
+ }
243
+ .menu-wrap { position: relative; }
244
+ .menu {
245
+ position: absolute;
246
+ top: 100%;
247
+ right: 0;
248
+ margin-top: 6px;
249
+ min-width: 220px;
250
+ background: var(--aikaara-surface, #ffffff);
251
+ color: var(--aikaara-text, #1f2937);
252
+ border-radius: 8px;
253
+ box-shadow: 0 8px 24px rgba(0,0,0,0.18);
254
+ padding: 6px;
255
+ z-index: 1000;
256
+ display: none;
257
+ flex-direction: column;
258
+ gap: 2px;
259
+ }
260
+ .menu.open { display: flex; }
261
+ .menu-item {
262
+ display: flex;
263
+ align-items: center;
264
+ gap: 10px;
265
+ width: 100%;
266
+ padding: 9px 10px;
267
+ background: none;
268
+ border: none;
269
+ color: inherit;
270
+ font: inherit;
271
+ font-size: 13.5px;
272
+ text-align: left;
273
+ border-radius: 6px;
274
+ cursor: pointer;
275
+ }
276
+ .menu-item:hover {
277
+ background: var(--aikaara-menu-hover, rgba(99,102,241,0.10));
278
+ }
279
+ .menu-item-icon {
280
+ display: flex;
281
+ align-items: center;
282
+ justify-content: center;
283
+ flex-shrink: 0;
284
+ color: var(--aikaara-primary, #6366f1);
285
+ }
286
+ .menu-item-icon svg { width: 16px; height: 16px; }
287
+ .menu-item-label { flex: 1; }
288
+ </style>
289
+ <div class="header">
290
+ <div class="avatar">
291
+ ${r?`<img src="${r}" alt="Avatar" />`:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>'}
292
+ </div>
293
+ <div class="info">
294
+ <div class="title">
295
+ ${e}
296
+ <span class="status-dot" style="background:${n}"></span>
297
+ </div>
298
+ ${t?`<div class="subtitle">${t}</div>`:""}
299
+ </div>
300
+ <div class="actions">
301
+ ${this.actions.length>0?`
302
+ <div class="menu-wrap">
303
+ <button class="icon-btn menu-btn" aria-label="More actions" type="button">
304
+ <svg viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="12" cy="19" r="1.6"/></svg>
305
+ </button>
306
+ <div class="menu" role="menu">
307
+ ${o}
308
+ </div>
309
+ </div>`:""}
310
+ <button class="icon-btn close-btn" aria-label="Close chat" type="button">
311
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
312
+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
313
+ </svg>
314
+ </button>
315
+ </div>
316
+ </div>
317
+ `}setStatus(e){this.setAttribute("status",e)}}const xd=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,Sd=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,Ed={"&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">","&amp;":"&","&nbsp;":" "};function Ad(a){return a.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>Ed[e.toLowerCase()]??e).replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,10))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/&amp;/gi,"&")}function Ut(a){if(xd.test(a))return a;const e=Sd.test(a)?Ad(a):a;let t=Id(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,i,n)=>`<pre><code>${n.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),t=t.replace(/(^|[^"'>=(])(https?:\/\/[^\s<]+)/g,(r,i,n)=>{const o=/[.,!?;:]+$/.exec(n),s=o?o[0]:"",l=s?n.slice(0,n.length-s.length):n;return`${i}<a href="${l}" target="_blank" rel="noopener noreferrer">${l}</a>${s}`}),t=t.replace(/\n/g,"<br>"),t}function Id(a){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return a.replace(/[&<>"']/g,t=>e[t])}const Td=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"]),Cd={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 Bt(a){const e=document.createElement("template");return e.innerHTML=a,$l(e.content),e.innerHTML}function $l(a){const e=Array.from(a.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,i=r.tagName.toLowerCase();if(!Td.has(i)){const s=document.createTextNode(r.textContent||"");a.replaceChild(s,t);continue}const n=Cd[i]||new Set,o=Array.from(r.attributes);for(const s of o)n.has(s.name)||r.removeAttribute(s.name);if(r.hasAttribute("href")){const s=r.getAttribute("href")||"";!s.startsWith("http://")&&!s.startsWith("https://")&&!s.startsWith("/")&&r.removeAttribute("href")}$l(t)}}function Od(a){const e=Date.now()-a.getTime(),t=Math.round(e/1e3);if(t<5)return"just now";if(t<60)return`${t}s ago`;const r=Math.round(t/60);if(r<60)return`${r} min ago`;const i=Math.round(r/60);if(i<24)return`${i} hr ago`;const n=Math.round(i/24);return n===1?"Yesterday":n<7?`${n} d ago`:a.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class ql extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(e.template?.contentType)return!1;const t=e.content;if(!t)return!1;const r=t.trim().toLowerCase();return r==="chat_initiated"||r==="group created"||r==="file_uploaded"||r==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(i=>r.includes(i)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(n=>n&&n.tagName==="A");!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment")||t.some(n=>{if(!n||!n.classList)return!1;const o=n.classList;return o.contains("bubble")&&o.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
318
+ <style>
319
+ :host {
320
+ display: flex;
321
+ flex-direction: column;
322
+ min-height: 0;
323
+ }
324
+ .message-list {
325
+ flex: 1;
326
+ overflow-y: auto;
327
+ padding: 16px;
328
+ display: flex;
329
+ flex-direction: column;
330
+ gap: 8px;
331
+ }
332
+ .message-list { scrollbar-width: thin; scrollbar-color: var(--aikaara-border, #e5e7eb) transparent; }
333
+ .message-list::-webkit-scrollbar { width: 6px; height: 6px; }
334
+ .message-list::-webkit-scrollbar-track { background: transparent; }
335
+ .message-list::-webkit-scrollbar-thumb { background: var(--aikaara-border, #e5e7eb); border-radius: 3px; }
336
+ .message-list::-webkit-scrollbar-button { display: none; width: 0; height: 0; }
337
+ .message-list::-webkit-scrollbar-corner { background: transparent; }
338
+ .message-wrap { display: flex; flex-direction: column; }
339
+ .message-wrap.user { align-items: flex-end; }
340
+ .message-wrap.assistant,
341
+ .message-wrap.agent { align-items: flex-start; }
342
+ .message-wrap.system { align-items: center; text-align: center; }
343
+ .message-wrap.system .bubble {
344
+ background: transparent;
345
+ color: var(--aikaara-text-secondary, #6b7280);
346
+ font-size: 12px;
347
+ font-style: italic;
348
+ padding: 4px 0;
349
+ }
350
+ .attachments {
351
+ display: flex;
352
+ flex-direction: column;
353
+ gap: 4px;
354
+ margin-top: 6px;
355
+ }
356
+ .attachment {
357
+ display: inline-flex;
358
+ align-items: center;
359
+ gap: 6px;
360
+ padding: 6px 10px;
361
+ background: rgba(0,0,0,0.05);
362
+ border-radius: 8px;
363
+ font-size: 12px;
364
+ color: inherit;
365
+ text-decoration: none;
366
+ }
367
+ .attachment:hover { background: rgba(0,0,0,0.08); }
368
+ .status-tick {
369
+ font-size: 10px;
370
+ margin-left: 4px;
371
+ color: var(--aikaara-text-secondary, #6b7280);
372
+ }
373
+ .status-tick.read { color: var(--aikaara-primary, #6366f1); }
374
+ aikaara-template-renderer { display: block; margin-top: 6px; }
375
+ .bubble {
376
+ max-width: 85%;
377
+ padding: 10px 14px;
378
+ border-radius: var(--aikaara-radius, 12px);
379
+ font-size: 14px;
380
+ line-height: 1.5;
381
+ word-wrap: break-word;
382
+ overflow-wrap: break-word;
383
+ }
384
+ .bubble.user {
385
+ background: var(--aikaara-user-bubble-bg, var(--aikaara-primary, #6366f1));
386
+ color: var(--aikaara-user-bubble-text, var(--aikaara-primary-contrast, #ffffff));
387
+ border-bottom-right-radius: 4px;
388
+ }
389
+ /* Attachment-only user message: strip the colored bubble so the
390
+ file-tile stands on its own. The tile component carries its own
391
+ background, padding, hover state, and click-to-preview affordance. */
392
+ .bubble.user.attachment-only {
393
+ background: transparent;
394
+ padding: 0;
395
+ border-radius: 0;
396
+ }
397
+ .bubble.attachment-only .attachments { margin-top: 0; }
398
+ .bubble.assistant, .bubble.agent {
399
+ background: var(--aikaara-bot-bubble-bg, var(--aikaara-bg-secondary, #f9fafb));
400
+ color: var(--aikaara-bot-bubble-text, var(--aikaara-text, #1f2937));
401
+ border-bottom-left-radius: 4px;
402
+ }
403
+ /* Tenant-style: template chips render below bubble as a sibling
404
+ (templateLayout='outside'). Full content width, no clamp. */
405
+ aikaara-template-renderer.template-outside {
406
+ align-self: stretch;
407
+ width: 100%;
408
+ margin-top: 8px;
409
+ background: transparent;
410
+ }
411
+ .bubble pre {
412
+ background: rgba(0,0,0,0.06);
413
+ padding: 8px 12px;
414
+ border-radius: 6px;
415
+ overflow-x: auto;
416
+ font-size: 13px;
417
+ margin: 8px 0;
418
+ }
419
+ .bubble code {
420
+ font-family: 'SF Mono', 'Fira Code', monospace;
421
+ font-size: 13px;
422
+ }
423
+ .bubble.assistant code:not(pre code) {
424
+ background: rgba(0,0,0,0.06);
425
+ padding: 2px 4px;
426
+ border-radius: 3px;
427
+ }
428
+ .bubble a { color: inherit; text-decoration: underline; }
429
+ .timestamp {
430
+ font-size: 11px;
431
+ color: var(--aikaara-text-secondary, #6b7280);
432
+ margin-top: 2px;
433
+ padding: 0 4px;
434
+ }
435
+ .welcome {
436
+ text-align: center;
437
+ color: var(--aikaara-text-secondary, #6b7280);
438
+ font-size: 14px;
439
+ padding: 24px 16px;
440
+ }
441
+ .streaming-cursor::after {
442
+ content: '\\25CF';
443
+ animation: blink 1s infinite;
444
+ margin-left: 2px;
445
+ font-size: 10px;
446
+ vertical-align: middle;
447
+ }
448
+ @keyframes blink {
449
+ 0%, 100% { opacity: 1; }
450
+ 50% { opacity: 0; }
451
+ }
452
+ .typing-indicator {
453
+ display: flex;
454
+ align-items: center;
455
+ gap: 4px;
456
+ padding: 10px 14px;
457
+ align-self: flex-start;
458
+ background: var(--aikaara-bot-bubble-bg, var(--aikaara-bg-secondary, #f9fafb));
459
+ border-radius: var(--aikaara-radius, 12px);
460
+ border-bottom-left-radius: 4px;
461
+ }
462
+ .typing-indicator .dot {
463
+ width: 6px;
464
+ height: 6px;
465
+ border-radius: 50%;
466
+ background: var(--aikaara-text-secondary, #6b7280);
467
+ animation: typing-bounce 1.4s infinite ease-in-out;
468
+ }
469
+ .typing-indicator .dot:nth-child(1) { animation-delay: 0ms; }
470
+ .typing-indicator .dot:nth-child(2) { animation-delay: 200ms; }
471
+ .typing-indicator .dot:nth-child(3) { animation-delay: 400ms; }
472
+ @keyframes typing-bounce {
473
+ 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
474
+ 30% { transform: translateY(-4px); opacity: 1; }
475
+ }
476
+ </style>
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">${Bt(Ut(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const i=r.externalId??r.id;this.appendMessageElement(r,t.get(i))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;let r=-1;for(let i=e.length-1;i>=0;i--)if(e[i].role==="user"){r=i;break}for(let i=0;i<e.length;i++){const n=e[i];if(n.role==="user"){const o=n.metadata?.attributes?.action;if(o){const s=Pd(o);if(o.message_id&&t.set(o.message_id,s),Object.keys(s).length>0)for(let l=i-1;l>=0;l--){const c=e[l];if(c.role!=="user"&&c.template?.contentType){const u=c.externalId??c.id,h=t.get(u);(!h||Object.keys(h).length===0)&&t.set(u,s);break}}}}if(n.role!=="user"&&n.template?.contentType&&i<r){const o=n.externalId??n.id;t.has(o)||t.set(o,{})}}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=Bt(Ut(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e))return;if(e.role==="system"){if(!e.content||!e.content.trim())return;const h=document.createElement("div");h.classList.add("message-wrap","system"),h.dataset.messageId=e.id,e.externalId&&(h.dataset.externalId=e.externalId);const p=document.createElement("aikaara-system-pill");p.setAttribute("text",e.content),h.appendChild(p),this.container.appendChild(h);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const i=document.createElement("div");i.classList.add("bubble",e.role);const o=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?i.classList.add("attachment-only"):i.textContent=e.content:o?e.content&&(i.innerHTML=Bt(Ut(e.content))):(i.innerHTML=Bt(Ut(e.content||"")),e.status==="streaming"&&i.classList.add("streaming-cursor"));let s=null;if(e.template?.contentType){const h=document.createElement("aikaara-template-renderer");h.setAttribute("content-type",e.template.contentType),e.template.templateId&&h.setAttribute("template-id",e.template.templateId);const p=e.externalId??e.id;p&&h.setAttribute("message-id",p),h.setPayload(e.template.payload),t!==void 0&&(h.dataset.consumed="true",Object.keys(t).length>0&&h.setConsumedValues?.(t)),this.templateLayout==="outside"?(h.classList.add("template-outside"),s=h):i.appendChild(h)}const l=e.template?.templateId==="7";if(e.attachments?.length&&!l){const h=document.createElement("div");h.classList.add("attachments");for(const p of e.attachments){const b=document.createElement("aikaara-template-renderer");b.setAttribute("content-type","300"),b.setAttribute("template-id","7");const f={elements:[{description:p.fileName,action:{url:p.fileUrl,type:"link",isDeepLink:!0}}]};b.setPayload(f,""),h.appendChild(b)}i.appendChild(h)}const u=!(i.childNodes.length===0&&(i.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(i),s&&r.appendChild(s),(u||s)&&this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const h=document.createElement("div");if(h.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(h.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const p=document.createElement("span");p.classList.add("status-tick"),e.status==="read"&&p.classList.add("read"),p.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",h.appendChild(p)}r.appendChild(h)}r.childNodes.length>0&&this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){const e=()=>{this.scrollTop=this.scrollHeight,this.container.scrollTop=this.container.scrollHeight};requestAnimationFrame(()=>{e(),requestAnimationFrame(e)}),setTimeout(e,150)}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return Od(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(b=>Md(e,b.match)),i=r?.target??"iframe";if(i==="tab"){window.open(e,"_blank","noopener,noreferrer");return}const n=this.getOrCreateModal(),o=r?.title??t??"Link";if(i==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,o));return}const s=Rd(e),l=Hl(r.fetch.url,s),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const b=await this.getLinkBearer(u);b&&(c.authorization=`Bearer ${b}`)}const h={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",h.body=JSON.stringify(eo(r.fetch.body,s)));let p=null;try{const b=await fetch(l,h);b.ok&&(p=await b.json().catch(()=>null))}catch(b){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",b)}requestAnimationFrame(()=>{n.showElement?.(r.render,o,b=>{const f=r.props??{setData:p};for(const[y,w]of Object.entries(f)){const m=b[y];typeof m=="function"&&m.call(b,w)}const g=y=>{const w=y,m=w.detail?.message??w.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...w.detail?.attributes??{}}},bubbles:!0,composed:!0})))};b.addEventListener("aikaara-plan-select",g),b.addEventListener("aikaara-select",g)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function Pd(a){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,i]of Object.entries(a))e.has(r)||(Array.isArray(i)&&i.every(n=>typeof n=="string")?t[r]=i:typeof i=="string"&&(t[r]=[i]));return t}function Md(a,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(a)}function Rd(a){try{const e=new URL(a),t={};return e.searchParams.forEach((r,i)=>{t[i]=r}),t}catch{return{}}}function Hl(a,e){return a.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function eo(a,e){if(typeof a=="string")return Hl(a,e);if(Array.isArray(a))return a.map(t=>eo(t,e));if(a&&typeof a=="object"){const t={};for(const[r,i]of Object.entries(a))t[r]=eo(i,e);return t}return a}class Wl extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",i=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",o=this.getAttribute("template-id")||"",s=this.getAttribute("inner-message")||"",l=e==="user"?document.createTextNode(t).textContent||"":Bt(Ut(t)),c=e==="user"&&i,u=i==="sending"?"○":i==="sent"?"✓":i==="delivered"||i==="read"?"✓✓":"";this.shadow.innerHTML=`
479
+ <style>
480
+ :host { display: flex; flex-direction: column; }
481
+ :host([role="user"]) { align-items: flex-end; }
482
+ :host([role="assistant"]),
483
+ :host([role="agent"]),
484
+ :host([role="system"]) { align-items: flex-start; }
485
+ .bubble {
486
+ max-width: 85%;
487
+ padding: 10px 14px;
488
+ border-radius: var(--aikaara-bubble-radius, var(--aikaara-radius, 12px));
489
+ font-size: 14px;
490
+ line-height: 1.5;
491
+ word-wrap: break-word;
492
+ }
493
+ .bubble.user {
494
+ background: var(--aikaara-user-bubble-bg, var(--aikaara-primary, #6366f1));
495
+ color: var(--aikaara-user-bubble-text, var(--aikaara-primary-contrast, #fff));
496
+ border-bottom-right-radius: 4px;
497
+ }
498
+ .bubble.assistant, .bubble.agent {
499
+ background: var(--aikaara-bot-bubble-bg, var(--aikaara-bg-secondary, #f9fafb));
500
+ color: var(--aikaara-bot-bubble-text, var(--aikaara-text, #1f2937));
501
+ border-bottom-left-radius: 4px;
502
+ }
503
+ .bubble.system {
504
+ background: transparent;
505
+ color: var(--aikaara-text-secondary, #6b7280);
506
+ font-size: 12px;
507
+ font-style: italic;
508
+ }
509
+ .timestamp {
510
+ font-size: 11px;
511
+ color: var(--aikaara-text-secondary, #6b7280);
512
+ margin-top: 2px;
513
+ padding: 0 4px;
514
+ }
515
+ .status {
516
+ font-size: 10px;
517
+ color: ${i==="read"?"var(--aikaara-primary, #6366f1)":"var(--aikaara-text-secondary, #6b7280)"};
518
+ margin-left: 4px;
519
+ }
520
+ .attachments {
521
+ display: flex;
522
+ flex-direction: column;
523
+ gap: 6px;
524
+ margin-top: 8px;
525
+ }
526
+ .attachment {
527
+ display: inline-flex;
528
+ align-items: center;
529
+ gap: 6px;
530
+ padding: 6px 10px;
531
+ background: rgba(0,0,0,0.05);
532
+ border-radius: 8px;
533
+ font-size: 12px;
534
+ color: inherit;
535
+ text-decoration: none;
536
+ max-width: 100%;
537
+ }
538
+ .attachment:hover { background: rgba(0,0,0,0.08); }
539
+ aikaara-template-renderer { display: block; margin-top: 6px; }
540
+ </style>
541
+ <div class="bubble ${e}">
542
+ <div class="content">${l}</div>
543
+ ${n?`<aikaara-template-renderer
544
+ content-type="${n}"
545
+ template-id="${o}"
546
+ inner-message="${Bs(s)}"
547
+ ></aikaara-template-renderer>`:""}
548
+ ${this.renderAttachments()}
549
+ </div>
550
+ ${r||c?`
551
+ <div class="timestamp">
552
+ ${r}${c?`<span class="status">${u}</span>`:""}
553
+ </div>
554
+ `:""}
555
+ `;const h=this.shadow.querySelector("aikaara-template-renderer");h&&this.templatePayload!==null&&h.setPayload(this.templatePayload,s),h&&h.addEventListener("template-action",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${Bs(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
556
+ 📎 ${Ld(t.fileName)}
557
+ </a>`).join("")}</div>`:""}}function Bs(a){return String(a).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Ld(a){return String(a).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class zl extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",i=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",o=this.getAttribute("send-shape")==="square",s=t?`
558
+ <button class="attach-btn" aria-label="Attach file" type="button">
559
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
560
+ <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
561
+ </svg>
562
+ </button>
563
+ <input type="file" ${r?`accept="${r}"`:""} ${i?"multiple":""} />`:"",l=`
564
+ <button class="send-btn" aria-label="Send message" type="button" disabled>
565
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
566
+ <line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
567
+ </svg>
568
+ </button>`,c=o?"border-radius: var(--aikaara-button-radius, 8px);":"border-radius: 50%;";this.shadow.innerHTML=`
569
+ <style>
570
+ .input-container {
571
+ display: flex;
572
+ align-items: flex-end;
573
+ gap: 8px;
574
+ padding: 12px 16px;
575
+ border-top: 1px solid var(--aikaara-border, #e5e7eb);
576
+ background: var(--aikaara-bg, #ffffff);
577
+ }
578
+ textarea {
579
+ flex: 1;
580
+ resize: none;
581
+ border: 1px solid var(--aikaara-border, #e5e7eb);
582
+ border-radius: 8px;
583
+ padding: 10px 12px;
584
+ font-family: var(--aikaara-font, system-ui, sans-serif);
585
+ font-size: 14px;
586
+ color: var(--aikaara-text, #1f2937);
587
+ background: var(--aikaara-bg, #ffffff);
588
+ outline: none;
589
+ min-height: 40px;
590
+ max-height: 120px;
591
+ line-height: 1.4;
592
+ transition: border-color 200ms ease;
593
+ }
594
+ textarea:focus { border-color: var(--aikaara-primary, #6366f1); }
595
+ textarea::placeholder { color: var(--aikaara-text-secondary, #6b7280); }
596
+ button {
597
+ width: 40px;
598
+ height: 40px;
599
+ border: none;
600
+ cursor: pointer;
601
+ display: flex;
602
+ align-items: center;
603
+ justify-content: center;
604
+ flex-shrink: 0;
605
+ transition: background 200ms, opacity 200ms, color 200ms;
606
+ font-family: inherit;
607
+ }
608
+ .attach-btn {
609
+ background: transparent;
610
+ color: var(--aikaara-text-secondary, #6b7280);
611
+ border-radius: 50%;
612
+ }
613
+ .attach-btn:hover {
614
+ background: rgba(0,0,0,0.05);
615
+ color: var(--aikaara-primary, #6366f1);
616
+ }
617
+ .attach-btn[data-uploading="true"] svg { animation: spin 1s linear infinite; }
618
+ .send-btn {
619
+ background: var(--aikaara-primary, #6366f1);
620
+ color: #ffffff;
621
+ ${c}
622
+ }
623
+ .send-btn:hover { background: var(--aikaara-primary-hover, #4f46e5); }
624
+ button:disabled { opacity: 0.5; cursor: not-allowed; }
625
+ button svg { width: 18px; height: 18px; }
626
+ input[type="file"] { display: none; }
627
+ @keyframes spin { to { transform: rotate(360deg); } }
628
+ </style>
629
+ <div class="input-container">
630
+ ${n?"":s}
631
+ <textarea rows="1" placeholder="${e}"></textarea>
632
+ ${n?s:""}
633
+ ${l}
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 h of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:h},bubbles:!0,composed:!0}));this.fileInput&&(this.fileInput.value="")}})}set disabled(e){this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.attachBtn&&(this.attachBtn.disabled=e||this._uploading),this.refreshSendDisabled()}get disabled(){return this._disabled}set uploading(e){this._uploading=e,this.attachBtn&&(this.attachBtn.dataset.uploading=String(e),this.attachBtn.disabled=this._disabled||e)}get uploading(){return this._uploading}focus(){this.textarea?.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.refreshSendDisabled())}refreshSendDisabled(){this.sendBtn&&(this.sendBtn.disabled=this._disabled||this._uploading||!this.textarea.value.trim())}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class Vl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
636
+ <style>
637
+ :host { display: none; }
638
+ :host([visible]) { display: block; }
639
+ .typing {
640
+ display: flex;
641
+ align-items: center;
642
+ gap: 4px;
643
+ padding: 10px 14px;
644
+ background: var(--aikaara-bg-secondary, #f9fafb);
645
+ border-radius: var(--aikaara-radius, 12px);
646
+ border-bottom-left-radius: 4px;
647
+ width: fit-content;
648
+ }
649
+ .dot {
650
+ width: 6px;
651
+ height: 6px;
652
+ border-radius: 50%;
653
+ background: var(--aikaara-text-secondary, #6b7280);
654
+ animation: bounce 1.4s infinite ease-in-out;
655
+ }
656
+ .dot:nth-child(1) { animation-delay: 0ms; }
657
+ .dot:nth-child(2) { animation-delay: 200ms; }
658
+ .dot:nth-child(3) { animation-delay: 400ms; }
659
+ @keyframes bounce {
660
+ 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
661
+ 30% { transform: translateY(-4px); opacity: 1; }
662
+ }
663
+ </style>
664
+ <div class="typing">
665
+ <span class="dot"></span>
666
+ <span class="dot"></span>
667
+ <span class="dot"></span>
668
+ </div>
669
+ `}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class Gl extends HTMLElement{shadow;bubble;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
670
+ <style>
671
+ :host {
672
+ display: flex;
673
+ flex-direction: column;
674
+ align-items: flex-start;
675
+ }
676
+ .bubble {
677
+ max-width: 85%;
678
+ padding: 10px 14px;
679
+ border-radius: var(--aikaara-bubble-radius, var(--aikaara-radius, 12px));
680
+ border-bottom-left-radius: 4px;
681
+ background: var(--aikaara-bot-bubble-bg, var(--aikaara-bg-secondary, #f9fafb));
682
+ color: var(--aikaara-bot-bubble-text, var(--aikaara-text, #1f2937));
683
+ font-size: 14px;
684
+ line-height: 1.5;
685
+ word-wrap: break-word;
686
+ min-height: 20px;
687
+ }
688
+ .bubble pre {
689
+ background: rgba(0,0,0,0.06);
690
+ padding: 8px 12px;
691
+ border-radius: 6px;
692
+ overflow-x: auto;
693
+ font-size: 13px;
694
+ margin: 8px 0;
695
+ }
696
+ .bubble code {
697
+ font-family: 'SF Mono', 'Fira Code', monospace;
698
+ font-size: 13px;
699
+ }
700
+ .bubble code:not(pre code) {
701
+ background: rgba(0,0,0,0.06);
702
+ padding: 2px 4px;
703
+ border-radius: 3px;
704
+ }
705
+ .cursor::after {
706
+ content: '\\25CF';
707
+ animation: blink 1s infinite;
708
+ margin-left: 2px;
709
+ font-size: 10px;
710
+ vertical-align: middle;
711
+ }
712
+ @keyframes blink {
713
+ 0%, 100% { opacity: 1; }
714
+ 50% { opacity: 0; }
715
+ }
716
+ </style>
717
+ <div class="bubble cursor"></div>
718
+ `,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=Bt(Ut(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class Kl extends HTMLElement{shadow;container;dismissTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
719
+ <style>
720
+ .banner {
721
+ display: none;
722
+ padding: 8px 16px;
723
+ background: #fef2f2;
724
+ color: #dc2626;
725
+ font-size: 13px;
726
+ text-align: center;
727
+ border-top: 1px solid #fecaca;
728
+ }
729
+ .banner.visible {
730
+ display: block;
731
+ }
732
+ .dismiss {
733
+ background: none;
734
+ border: none;
735
+ color: #dc2626;
736
+ cursor: pointer;
737
+ font-size: 12px;
738
+ text-decoration: underline;
739
+ margin-left: 8px;
740
+ }
741
+ </style>
742
+ <div class="banner">
743
+ <span class="message"></span>
744
+ <button class="dismiss">Dismiss</button>
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 Jr=new Map;function Yl(a){const e=Jr.get(a);if(e)return e;const t=new Promise((r,i)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(a)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>i(new Error(`Failed to load ${a}`)),{once:!0}));return}const o=document.createElement("script");o.src=a,o.async=!0,o.crossOrigin="anonymous",o.dataset.aikaaraSrc=a,o.addEventListener("load",()=>{o.dataset.aikaaraReady="1",r()},{once:!0}),o.addEventListener("error",()=>{Jr.delete(a),i(new Error(`Failed to load ${a}`))},{once:!0}),document.head.appendChild(o)});return Jr.set(a,t),t}function jd(a,e=5e3){return new Promise((t,r)=>{const i=setTimeout(()=>r(new Error(`Custom element <${a}> not registered within ${e}ms`)),e);customElements.whenDefined(a).then(()=>{clearTimeout(i),t()})})}function Nd(a){const e=`template:${a}`,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?.[a]}class Ql extends HTMLElement{shadow;payloadData=null;innerMessage="";renderGen=0;_consumedValues=null;static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",e=>{const t=e.detail,r=this.getAttribute("message-id");if(r&&t?.attributes?.action){const i=Dd(t.attributes.action);if(Object.keys(i).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(i))}catch{}}this.dataset.consumed="true",this._applyConsumedToChildren()})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}setConsumedValues(e){this._consumedValues=e,this._applyConsumedToChildren()}_applyConsumedToChildren(){let e=this._consumedValues;if(!e){const r=this.getAttribute("message-id");if(r)try{const i=localStorage.getItem(`aikaara_form:${r}`);i&&(e=JSON.parse(i))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(i=>{const n=i,o=n.getName?.();o&&r[o]?.length&&n.setPreSelected?.(r[o])})}this.querySelectorAll("aikaara-submit-action, aikaara-modal-action, aikaara-link-button").forEach(r=>{r.style.display="none"});const t=new Set(["aikaara-option-list","aikaara-submit-action","aikaara-modal-action","aikaara-link-button"]);this.querySelectorAll("*").forEach(r=>{if(t.has(r.tagName.toLowerCase()))return;e&&r.setConsumedValues?.(e),r.dataset.consumed="true"})}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.renderGen+=1,this.shadow.innerHTML=`
747
+ <style>
748
+ :host { display: block; }
749
+ ::slotted(*) { display: block; }
750
+ /* Consumed forms: hide the submit button, lock option lists to display-only. */
751
+ :host([data-consumed]) ::slotted(aikaara-submit-action) { display: none; }
752
+ :host([data-consumed]) ::slotted(aikaara-modal-action) { display: none; }
753
+ :host([data-consumed]) ::slotted(aikaara-link-button) { display: none; }
754
+ :host([data-consumed]) ::slotted(aikaara-option-list) {
755
+ pointer-events: none;
756
+ opacity: 0.65;
757
+ }
758
+ </style>
759
+ <slot></slot>
760
+ `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Nd(t):void 0,i=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`);if(r?.scriptUrl&&!customElements.get(i)&&Yl(r.scriptUrl).then(()=>jd(i)).then(()=>this.render()).catch(n=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,n)),customElements.get(i)){const n=document.createElement(i);if(r?.props){for(const[o,s]of Object.entries(r.props))if(typeof n[o]=="function")try{n[o](s)}catch(l){console.warn(`[aikaara-template-renderer] props.${o} threw on <${i}>`,l)}}n.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(n),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&n.setConsumedValues?.(this._consumedValues),n.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const n=this.payloadData;if(n.length>0&&n.every(s=>s&&typeof s=="object"&&!Array.isArray(s)&&!("type"in s)&&!("data"in s)&&typeof s.message=="string")){const s=document.createElement("aikaara-option-list");s.setPayload({name:"quick-reply",type:"button",options:n.map(l=>{const c=typeof l.title=="string"?l.title:"",u=l.message;return{label:c||u,value:u}})}),this.appendChild(s);return}for(const s of n)this.mountField(s)}else if(this.payloadData&&typeof this.payloadData=="object"){const n=this.payloadData;typeof n.message=="string"&&(n.okLabel||n.action||n.ok)&&this.mountModal(n)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="checkbox"||t==="radio"||t==="button"){const i=document.createElement("aikaara-option-list");i.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(i);return}if(t==="submit"){const i=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;i.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(i);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>require("./AikaaraLinkButton-VDNx7RfC.cjs")).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:i})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Bd(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Ud=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Bd(a){const e={};for(const[t,r]of Object.entries(a))Ud.has(t)||(e[t]=r);return e}function Dd(a){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,i]of Object.entries(a))e.has(r)||(Array.isArray(i)&&i.every(n=>typeof n=="string")?t[r]=i:typeof i=="string"&&(t[r]=[i]));return t}class Jl 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
+ <style>
762
+ :host {
763
+ display: flex;
764
+ flex-direction: column;
765
+ align-items: center;
766
+ gap: 2px;
767
+ padding: 6px 0;
768
+ }
769
+ .pill {
770
+ display: inline-block;
771
+ background: var(--aikaara-system-pill-bg, rgba(0,0,0,0.06));
772
+ color: var(--aikaara-system-pill-color, var(--aikaara-text-secondary, #6b7280));
773
+ padding: var(--aikaara-system-pill-padding, 6px 14px);
774
+ border-radius: var(--aikaara-system-pill-radius, 9999px);
775
+ font-size: var(--aikaara-system-pill-font-size, 12px);
776
+ font-weight: var(--aikaara-system-pill-font-weight, 500);
777
+ border: var(--aikaara-system-pill-border, none);
778
+ line-height: 1.3;
779
+ }
780
+ .sub {
781
+ font-size: 11px;
782
+ color: var(--aikaara-text-secondary, #9ca3af);
783
+ }
784
+ </style>
785
+ <span class="pill">${Ds(e)}</span>
786
+ ${t?`<span class="sub">${Ds(t)}</span>`:""}
787
+ `}}function Ds(a){return String(a).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Xl extends HTMLElement{shadow;data=null;selected=new Set;preSelectedDisabled=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.selected.clear(),this.preSelectedDisabled=!1,this.render()}getName(){return this.data?.name??""}setPreSelected(e){this.selected=new Set(e),this.preSelectedDisabled=!0,this.render()}getValues(){return{name:this.data?.name??"",values:[...this.selected],type:this.data?.type??"checkbox"}}toggle(e){this.data&&(this.data.type==="radio"||this.data.type==="button"?(this.selected.clear(),this.selected.add(e)):this.selected.has(e)?this.selected.delete(e):this.selected.add(e),this.data.type==="button"?this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e,attributes:{action:{[this.data.name]:e}}},bubbles:!0,composed:!0})):this.dispatchEvent(new CustomEvent("option-change",{detail:this.getValues(),bubbles:!0,composed:!0})),this.render())}render(){if(!this.data){this.shadow.innerHTML="";return}const{title:e,options:t,type:r}=this.data,i=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const o=t[0],s=this.selected.has(o.value),l=this.preSelectedDisabled?"cursor: default; pointer-events: none;":"cursor: pointer;";if(this.shadow.innerHTML=`
788
+ <style>
789
+ :host { display: block; margin: 8px 0; }
790
+ .row {
791
+ display: flex; align-items: flex-start; gap: 10px;
792
+ ${l}
793
+ font-family: inherit;
794
+ color: var(--aikaara-text, #1f2937);
795
+ font-size: var(--aikaara-option-title-font-size, 14px);
796
+ line-height: 1.5;
797
+ }
798
+ .row:focus-visible { outline: 2px solid var(--aikaara-primary, #6366f1); outline-offset: 2px; border-radius: 4px; }
799
+ .box {
800
+ flex-shrink: 0;
801
+ width: 18px; height: 18px;
802
+ border: 1.5px solid var(--aikaara-primary, #6366f1);
803
+ border-radius: 4px;
804
+ margin-top: 3px;
805
+ background: var(--aikaara-option-bg, transparent);
806
+ display: grid; place-items: center;
807
+ transition: background 120ms, border-color 120ms;
808
+ }
809
+ .row[aria-checked="true"] .box {
810
+ background: var(--aikaara-primary, #6366f1);
811
+ border-color: var(--aikaara-primary, #6366f1);
812
+ }
813
+ .check {
814
+ width: 11px; height: 11px;
815
+ stroke: #fff;
816
+ opacity: 0;
817
+ transition: opacity 120ms;
818
+ }
819
+ .row[aria-checked="true"] .check { opacity: 1; }
820
+ .text { flex: 1; }
821
+ </style>
822
+ <div class="row" role="checkbox" tabindex="${this.preSelectedDisabled?"-1":"0"}" aria-checked="${s}" aria-disabled="${this.preSelectedDisabled}" data-value="${Fs(o.value)}">
823
+ <span class="box" aria-hidden="true">
824
+ <svg class="check" viewBox="0 0 16 16" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
825
+ <path d="M3 8 L7 12 L13 4" />
826
+ </svg>
827
+ </span>
828
+ <span class="text">${ar(e)}</span>
829
+ </div>
830
+ `,!this.preSelectedDisabled){const c=this.shadow.querySelector(".row");if(c){const u=()=>this.toggle(o.value);c.addEventListener("click",u),c.addEventListener("keydown",h=>{(h.key===" "||h.key==="Enter")&&(h.preventDefault(),u())})}}return}this.shadow.innerHTML=`
831
+ <style>
832
+ :host { display: block; margin: 8px 0; }
833
+ .title {
834
+ color: var(--aikaara-option-title-color, var(--aikaara-text, #111827));
835
+ font-size: var(--aikaara-option-title-font-size, 14px);
836
+ font-weight: var(--aikaara-option-title-font-weight, 600);
837
+ margin-bottom: 8px;
838
+ }
839
+ .grid {
840
+ display: flex;
841
+ flex-wrap: wrap;
842
+ gap: var(--aikaara-option-gap, 8px);
843
+ }
844
+ button.opt {
845
+ background: var(--aikaara-option-bg, transparent);
846
+ color: var(--aikaara-option-color, var(--aikaara-text, #1f2937));
847
+ border: var(--aikaara-option-border, 1.5px solid var(--aikaara-primary, #6366f1));
848
+ border-radius: var(--aikaara-option-radius, 10px);
849
+ padding: var(--aikaara-option-padding, 10px 16px);
850
+ font-size: 14px;
851
+ font-family: inherit;
852
+ cursor: ${this.preSelectedDisabled?"default":"pointer"};
853
+ transition: background 120ms, color 120ms, border-color 120ms;
854
+ line-height: 1.2;
855
+ }
856
+ button.opt:hover { filter: ${this.preSelectedDisabled?"none":"brightness(0.96)"}; }
857
+ button.opt[aria-pressed="true"] {
858
+ background: var(--aikaara-option-selected-bg, var(--aikaara-primary, #6366f1));
859
+ color: var(--aikaara-option-selected-color, #fff);
860
+ border-color: var(--aikaara-option-selected-border, var(--aikaara-primary, #6366f1));
861
+ }
862
+ </style>
863
+ ${e?`<div class="title">${ar(e)}</div>`:""}
864
+ <div class="grid" role="${i?"group":"radiogroup"}" aria-label="${ar(e??this.data.name)}">
865
+ ${t.map(o=>`
866
+ <button class="opt" type="button"
867
+ data-value="${Fs(o.value)}"
868
+ role="${i?"checkbox":"radio"}"
869
+ aria-pressed="${this.selected.has(o.value)}"
870
+ ${this.preSelectedDisabled?'disabled aria-disabled="true"':""}>
871
+ ${ar(o.label)}
872
+ </button>`).join("")}
873
+ </div>
874
+ `,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(o=>{o.addEventListener("click",()=>this.toggle(o.dataset.value||""))})}}function ar(a){return String(a).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function Fs(a){return String(a).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Zl extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;return t&&t.querySelectorAll("aikaara-option-list").forEach(r=>{const i=r.getValues?.();i?.name&&(e[i.name]=i.values)}),e}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues(),r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
875
+ <style>
876
+ :host { display: block; margin: 12px 0 4px; }
877
+ button {
878
+ font-family: inherit;
879
+ background: var(--aikaara-submit-bg, var(--aikaara-primary, #6366f1));
880
+ color: var(--aikaara-submit-color, #ffffff);
881
+ border: var(--aikaara-submit-border, none);
882
+ border-radius: var(--aikaara-submit-radius, 10px);
883
+ padding: var(--aikaara-submit-padding, 12px 22px);
884
+ font-size: var(--aikaara-submit-font-size, 14px);
885
+ font-weight: var(--aikaara-submit-font-weight, 600);
886
+ cursor: pointer;
887
+ transition: background 120ms, opacity 120ms;
888
+ }
889
+ button:hover { background: var(--aikaara-submit-hover-bg, var(--aikaara-primary-hover, #4f46e5)); }
890
+ button:disabled { opacity: var(--aikaara-submit-disabled-opacity, 0.5); cursor: not-allowed; }
891
+ </style>
892
+ <button type="button">${Fd(e)}</button>
893
+ `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Fd(a){return String(a).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class ec extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
894
+ <style>
895
+ :host { all: initial; }
896
+ .overlay {
897
+ position: fixed; inset: 0;
898
+ background: var(--aikaara-modal-overlay-bg, rgba(15, 23, 42, 0.45));
899
+ display: flex; align-items: center; justify-content: center;
900
+ z-index: 99999;
901
+ font-family: var(--aikaara-font, inherit);
902
+ }
903
+ .modal {
904
+ background: var(--aikaara-modal-bg, #ffffff);
905
+ color: var(--aikaara-modal-color, #1f2937);
906
+ border-radius: var(--aikaara-modal-radius, 14px);
907
+ padding: var(--aikaara-modal-padding, 24px 28px);
908
+ box-shadow: var(--aikaara-modal-shadow, 0 10px 40px rgba(15, 23, 42, 0.18));
909
+ max-width: 360px;
910
+ text-align: center;
911
+ }
912
+ .msg { font-size: 14px; line-height: 1.5; margin-bottom: 18px; }
913
+ .actions { display: flex; gap: 10px; justify-content: center; }
914
+ button {
915
+ font-family: inherit;
916
+ padding: 8px 22px;
917
+ font-size: 13px;
918
+ font-weight: 500;
919
+ border-radius: var(--aikaara-modal-button-radius, 10px);
920
+ cursor: pointer;
921
+ border: none;
922
+ }
923
+ button.ok {
924
+ background: var(--aikaara-modal-button-bg, var(--aikaara-primary, #6366f1));
925
+ color: var(--aikaara-modal-button-color, #ffffff);
926
+ }
927
+ button.cancel {
928
+ background: transparent;
929
+ color: var(--aikaara-modal-cancel-color, var(--aikaara-text-secondary, #6b7280));
930
+ }
931
+ </style>
932
+ <div class="overlay" role="dialog" aria-modal="true">
933
+ <div class="modal">
934
+ <div class="msg">${Xr(this.data.message)}</div>
935
+ <div class="actions">
936
+ ${t?`<button class="cancel" type="button">${Xr(t)}</button>`:""}
937
+ <button class="ok" type="button">${Xr(e)}</button>
938
+ </div>
939
+ </div>
940
+ </div>
941
+ `,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function Xr(a){return String(a).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class tc extends HTMLElement{static get observedAttributes(){return["slug","user-id","user-name","user-token","department-id","config-base","api-key"]}tokenGetter;apiKey;configHeaders;identity;credentialProviders;mounted=null;mountInflight=null;connectedCallback(){this.style.display||(this.style.display="flex"),this.style.flexDirection||(this.style.flexDirection="column"),this.style.minHeight||(this.style.minHeight="0"),this.tryMount()}disconnectedCallback(){this.mounted?.destroy(),this.mounted=null}attributeChangedCallback(){this.isConnected&&(this.mounted?.destroy(),this.mounted=null,this.tryMount())}async refreshAuth(){await this.mounted?.refreshAuth()}async tryMount(){if(this.mountInflight)return this.mountInflight;const e=this.getAttribute("slug"),t=this.getAttribute("user-id");if(!e||!t)return;const r=this.getAttribute("user-token"),i=this.tokenGetter??r;if(!i){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},o=Object.keys(n).find(c=>c.toLowerCase()==="x-api-key"),s=this.apiKey??this.getAttribute("api-key")??(o?n[o]:void 0);s&&(o&&o!=="X-Api-Key"&&delete n[o],n["X-Api-Key"]=s);const l=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await yc({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:i,identity:this.identity,credentialProviders:this.credentialProviders},hooks:{onError:c=>this.dispatchEvent(new CustomEvent("error",{detail:c}))}}),this.dispatchEvent(new CustomEvent("ready",{detail:{requestId:this.mounted.requestId,fullName:this.mounted.fullName}}))}catch(c){this.dispatchEvent(new CustomEvent("error",{detail:c}))}finally{this.mountInflight=null}})(),this.mountInflight}}class rc extends HTMLElement{shadow;root=null;iframe=null;fallbackTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.render()}show(e,t){if(this.root||this.render(),!this.root||!this.iframe)return;const r=this.shadow.querySelector(".modal-title");r&&(r.textContent=t||"Link"),this.swapBody("iframe"),this.iframe.src=e,this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{url:e},bubbles:!0,composed:!0})),this.fallbackTimer&&window.clearTimeout(this.fallbackTimer);let i=!1;this.iframe.addEventListener("load",()=>{i=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{i||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const i=this.shadow.querySelector(".modal-title");i&&(i.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const o=document.createElement(e);n.appendChild(o),requestAnimationFrame(()=>r?.(o))}this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{element:e},bubbles:!0,composed:!0}))}swapBody(e){if(!this.iframe)return;const t=this.shadow.querySelector(".modal-body-element");e==="iframe"?(this.iframe.style.display="",t&&(t.style.display="none")):(this.iframe.style.display="none",t&&(t.style.display=""))}close(){this.root&&(this.root.classList.remove("open"),this.iframe&&(this.iframe.src="about:blank"),this.fallbackTimer&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.dispatchEvent(new CustomEvent("aikaara-link-modal-close",{bubbles:!0,composed:!0})))}render(){this.shadow.innerHTML=`
942
+ <style>
943
+ :host { display: block; }
944
+ .backdrop {
945
+ position: fixed; inset: 0; z-index: 10000;
946
+ background: rgba(0,0,0,0.45);
947
+ display: none; align-items: center; justify-content: center;
948
+ padding: var(--aikaara-modal-padding, 24px);
949
+ font-family: var(--aikaara-font, system-ui, sans-serif);
950
+ }
951
+ :host(.open) .backdrop, .backdrop.open { display: flex; }
952
+ .modal {
953
+ background: var(--aikaara-surface, #fff);
954
+ border-radius: var(--aikaara-radius, 12px);
955
+ width: var(--aikaara-modal-width, min(900px, 100%));
956
+ height: var(--aikaara-modal-height, min(720px, 90vh));
957
+ max-width: var(--aikaara-modal-max-width, 100%);
958
+ max-height: var(--aikaara-modal-max-height, 90vh);
959
+ display: flex; flex-direction: column;
960
+ overflow: hidden;
961
+ box-shadow: 0 20px 60px rgba(0,0,0,0.3);
962
+ }
963
+ .modal-header {
964
+ display: flex; align-items: center; justify-content: space-between;
965
+ padding: 12px 16px;
966
+ background: var(--aikaara-primary, #0f2e5c);
967
+ color: var(--aikaara-primary-contrast, #fff);
968
+ font-size: 14px; font-weight: 600;
969
+ }
970
+ .modal-title { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
971
+ .modal-close {
972
+ background: transparent; border: none; color: inherit;
973
+ font-size: 22px; line-height: 1; cursor: pointer;
974
+ padding: 4px 8px; border-radius: 4px;
975
+ }
976
+ .modal-close:hover { background: rgba(255,255,255,0.15); }
977
+ iframe {
978
+ flex: 1; border: 0; width: 100%; height: 100%;
979
+ }
980
+ </style>
981
+ <div class="backdrop" part="backdrop">
982
+ <div class="modal" role="dialog" aria-modal="true">
983
+ <div class="modal-header">
984
+ <span class="modal-title">Link</span>
985
+ <button class="modal-close" aria-label="Close" type="button">×</button>
986
+ </div>
987
+ <iframe sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation-by-user-activation allow-downloads" allow="downloads" referrerpolicy="no-referrer-when-downgrade" loading="lazy"></iframe>
988
+ <div class="modal-body-element" style="display:none; flex:1; overflow:auto; padding:18px;"></div>
989
+ </div>
990
+ </div>
991
+ `,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const $d=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],qd=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class nc extends HTMLElement{shadow;data=null;columns=qd;features=$d;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
992
+ <style>
993
+ :host {
994
+ display: block;
995
+ font-family: var(--aikaara-font, system-ui, sans-serif);
996
+ color: var(--aikaara-text, #0f2e5c);
997
+ }
998
+ table {
999
+ width: 100%;
1000
+ border-collapse: collapse;
1001
+ font-size: 14px;
1002
+ border-radius: var(--aikaara-radius, 12px);
1003
+ overflow: hidden;
1004
+ }
1005
+ thead th {
1006
+ background: var(--aikaara-primary, #0f2e5c);
1007
+ color: var(--aikaara-primary-contrast, #fff);
1008
+ padding: 12px 14px;
1009
+ text-align: left;
1010
+ font-weight: 600;
1011
+ }
1012
+ thead th + th { text-align: center; }
1013
+ tbody td {
1014
+ padding: 11px 14px;
1015
+ border-bottom: 1px solid var(--aikaara-border, #e5e7eb);
1016
+ background: var(--aikaara-surface, #fff);
1017
+ }
1018
+ tbody tr:nth-child(even) td {
1019
+ background: var(--aikaara-surface-muted, #f6fafb);
1020
+ }
1021
+ tbody td + td { text-align: center; }
1022
+ .check { color: #16a34a; font-weight: 700; }
1023
+ .cross { color: #dc2626; font-weight: 700; }
1024
+ .price-row td { font-weight: 600; }
1025
+ .actions {
1026
+ display: flex; flex-direction: column; gap: 8px;
1027
+ margin-top: 12px;
1028
+ }
1029
+ button.action {
1030
+ display: flex; justify-content: space-between; align-items: center;
1031
+ padding: 12px 14px;
1032
+ background: var(--aikaara-primary, #0f2e5c);
1033
+ color: var(--aikaara-primary-contrast, #fff);
1034
+ border: none;
1035
+ border-radius: var(--aikaara-button-radius, 8px);
1036
+ font-size: 14px; font-weight: 600;
1037
+ cursor: pointer;
1038
+ width: 100%; text-align: left;
1039
+ }
1040
+ button.action:hover { background: var(--aikaara-primary-hover, #0a2347); }
1041
+ button.action small { font-weight: 400; opacity: 0.8; font-size: 12px; }
1042
+ </style>
1043
+ <table>
1044
+ <thead>
1045
+ <tr>
1046
+ <th>Feature</th>
1047
+ ${e.map(r=>`<th>${Zr(r.label)}</th>`).join("")}
1048
+ </tr>
1049
+ </thead>
1050
+ <tbody>
1051
+ ${t.map((r,i)=>`
1052
+ <tr>
1053
+ <td>${Zr(r.label)}</td>
1054
+ ${e.map(n=>n.features[i]?'<td><span class="check">✓</span></td>':'<td><span class="cross">✕</span></td>').join("")}
1055
+ </tr>`).join("")}
1056
+ <tr class="price-row">
1057
+ <td>Price (excl. GST)</td>
1058
+ ${e.map(r=>{const i=this.priceFor(r);return`<td>${i!=null?"₹"+Math.round(i):"—"}</td>`}).join("")}
1059
+ </tr>
1060
+ </tbody>
1061
+ </table>
1062
+ <div class="actions">
1063
+ ${e.map((r,i)=>{const n=this.priceFor(r),o=r.selectLabel.replace("{price}",n!=null?String(Math.round(n)):"—");return`<button class="action" data-col="${i}" type="button">
1064
+ <span>${Zr(o)}</span>
1065
+ <small>Tap to select</small>
1066
+ </button>`}).join("")}
1067
+ </div>
1068
+ `,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const i=Number(r.dataset.col),n=e[i];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function Zr(a){return a.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class ic extends HTMLElement{shadow;root=null;schemas=[];data={};view="picker";activeSectionId=null;keydownHandler=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.renderShell()}disconnectedCallback(){this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null)}open(e){this.root||this.renderShell(),this.root&&(this.schemas=e.schemas,this.data=e.data?{...e.data}:{},e.activeSectionId&&this.schemas.some(t=>t.id===e.activeSectionId)?(this.activeSectionId=e.activeSectionId,this.view="form"):(this.activeSectionId=null,this.view="picker"),this.renderView(),this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("smart-edit-open",{bubbles:!0,composed:!0})))}close(){this.root&&(this.root.classList.remove("open"),this.dispatchEvent(new CustomEvent("smart-edit-close",{bubbles:!0,composed:!0})))}setData(e){this.data={...e},this.view==="form"&&this.mountActiveForm()}openSection(e){this.activeSectionId=e,this.view="form",this.renderView()}backToPicker(){this.activeSectionId=null,this.view="picker",this.renderView()}extractSlice(e){const t=e.dataPath;if(!t)return this.data;const r=t.endsWith("[]"),i=r?t.slice(0,-2):t,n=this.data[i];return r?Array.isArray(n)?n:[]:n??null}handleSectionSubmit(e,t){const r=this.schemas.find(i=>i.id===e);if(r){if(r.dataPath){const n=r.dataPath.endsWith("[]")?r.dataPath.slice(0,-2):r.dataPath;this.data={...this.data,[n]:t}}else t&&typeof t=="object"&&(this.data={...this.data,...t});this.dispatchEvent(new CustomEvent("smart-edit-submit",{detail:{sectionId:e,record:this.data},bubbles:!0,composed:!0})),this.backToPicker()}}handleRecalculate(){this.dispatchEvent(new CustomEvent("smart-edit-recalculate",{detail:{record:this.data},bubbles:!0,composed:!0})),this.close()}renderView(){this.view==="form"?this.renderForm():this.renderPicker()}renderPicker(){const e=this.shadow.querySelector(".modal");if(!e)return;e.classList.remove("view-form"),e.classList.add("view-picker");const t=this.shadow.querySelector(".modal-header");t.innerHTML=`
1069
+ <span class="header-spacer"></span>
1070
+ <div class="modal-title">Correct Your ITR Details</div>
1071
+ <button class="icon-btn close-btn" type="button" aria-label="Close">${$s}</button>
1072
+ `;const r=this.shadow.querySelector(".modal-body"),i=this.schemas.map(o=>`
1073
+ <button class="chip" type="button" data-section-id="${Wd(o.id)}">
1074
+ <span class="chip-icon">${o.icon??"📄"}</span>
1075
+ <span class="chip-label">${qs(o.title)}</span>
1076
+ </button>`).join("");r.innerHTML=`
1077
+ <div class="picker">
1078
+ <div class="intro-card">
1079
+ <span class="intro-icon">✨</span>
1080
+ <div>
1081
+ <div class="intro-title">What would you like to correct?</div>
1082
+ <div class="intro-sub">Select a category to edit</div>
1083
+ </div>
1084
+ </div>
1085
+ <div class="chip-grid">${i}</div>
1086
+ </div>
1087
+ `;const n=this.shadow.querySelector(".modal-footer");n.style.display="",n.innerHTML=`
1088
+ <button class="primary-btn" type="button" data-action="recalculate">Save &amp; Recalculate</button>
1089
+ `,this.bindCommon(),r.querySelectorAll(".chip").forEach(o=>{o.addEventListener("click",()=>{const s=o.dataset.sectionId;s&&this.openSection(s)})}),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=`
1090
+ <button class="icon-btn back-btn" type="button" aria-label="Back">${Hd}</button>
1091
+ <div class="modal-title">${qs(t?.title??"Edit")}</div>
1092
+ <button class="icon-btn close-btn" type="button" aria-label="Close">${$s}</button>
1093
+ `;const i=this.shadow.querySelector(".modal-footer");i.style.display="none",i.innerHTML="",this.bindCommon(),r.querySelector(".back-btn")?.addEventListener("click",()=>this.backToPicker()),this.mountActiveForm()}mountActiveForm(){const e=this.shadow.querySelector(".modal-body");if(!e)return;e.innerHTML="";const t=this.schemas.find(i=>i.id===this.activeSectionId);if(!t){e.innerHTML='<div class="empty">Section not found.</div>';return}const r=document.createElement("aikaara-schema-form");r.addEventListener("aikaara-form-submit",(i=>{const n=i.detail;this.handleSectionSubmit(n.sectionId,n.value)})),e.appendChild(r),requestAnimationFrame(()=>{r.setSchema(t),r.setValue(this.extractSlice(t))})}bindCommon(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>this.close())}renderShell(){this.shadow.innerHTML=`
1094
+ <style>${this.css()}</style>
1095
+ <div class="backdrop" part="backdrop">
1096
+ <div class="modal view-picker" role="dialog" aria-modal="true" aria-label="Correct Your ITR Details">
1097
+ <div class="modal-header"></div>
1098
+ <div class="modal-body"></div>
1099
+ <div class="modal-footer"></div>
1100
+ </div>
1101
+ </div>
1102
+ `,this.root=this.shadow.querySelector(".backdrop"),this.root.addEventListener("click",e=>{e.target===this.root&&this.close()}),this.keydownHandler||(this.keydownHandler=e=>{e.key!=="Escape"||!this.root?.classList.contains("open")||(this.view==="form"?this.backToPicker():this.close())},document.addEventListener("keydown",this.keydownHandler))}css(){return`
1103
+ :host { display: block; }
1104
+ .backdrop {
1105
+ position: fixed; inset: 0; z-index: 10000;
1106
+ background: rgba(15, 23, 42, 0.55);
1107
+ display: none; align-items: center; justify-content: center;
1108
+ padding: 20px;
1109
+ font-family: var(--aikaara-font, system-ui, -apple-system, sans-serif);
1110
+ }
1111
+ .backdrop.open { display: flex; }
1112
+ .modal {
1113
+ background: var(--aikaara-surface, #ffffff);
1114
+ border-radius: var(--aikaara-radius, 16px);
1115
+ width: min(560px, 100%);
1116
+ max-height: 88vh;
1117
+ display: flex;
1118
+ flex-direction: column;
1119
+ overflow: hidden;
1120
+ box-shadow: 0 28px 80px rgba(15,23,42,0.35);
1121
+ color: var(--aikaara-text, #0f172a);
1122
+ }
1123
+ .modal-header {
1124
+ flex-shrink: 0;
1125
+ display: flex; align-items: center; gap: 8px;
1126
+ padding: 14px 14px;
1127
+ border-bottom: 1px solid var(--aikaara-border, #e3e8ef);
1128
+ }
1129
+ .modal-title {
1130
+ flex: 1;
1131
+ text-align: center;
1132
+ font-size: 15.5px;
1133
+ font-weight: 700;
1134
+ color: var(--aikaara-text-strong, #0f172a);
1135
+ }
1136
+ .header-spacer, .icon-btn { width: 32px; height: 32px; flex-shrink: 0; }
1137
+ .icon-btn {
1138
+ display: flex; align-items: center; justify-content: center;
1139
+ background: transparent; border: none; cursor: pointer;
1140
+ color: var(--aikaara-text-muted, #475569);
1141
+ border-radius: 8px;
1142
+ padding: 0;
1143
+ }
1144
+ .icon-btn:hover { background: var(--aikaara-border, #eef1f5); }
1145
+ .icon-btn svg { width: 18px; height: 18px; }
1146
+ .modal-body {
1147
+ flex: 1;
1148
+ min-height: 0;
1149
+ display: flex;
1150
+ flex-direction: column;
1151
+ }
1152
+ .modal.view-picker .modal-body { overflow-y: auto; padding: 16px 18px; }
1153
+ .modal.view-form .modal-body { overflow: hidden; }
1154
+ /* The schema form is a flex child here — it must be allowed to shrink
1155
+ below its content height (min-height: 0) so its own internal
1156
+ .scroll region can take over, instead of overflowing the modal. */
1157
+ .modal-body aikaara-schema-form { flex: 1 1 auto; min-height: 0; }
1158
+ .modal-footer {
1159
+ flex-shrink: 0;
1160
+ padding: 14px 18px;
1161
+ border-top: 1px solid var(--aikaara-border, #e3e8ef);
1162
+ }
1163
+
1164
+ /* ── picker view ─────────────────────────────────────────── */
1165
+ .picker { display: flex; flex-direction: column; gap: 16px; }
1166
+ .intro-card {
1167
+ display: flex; align-items: flex-start; gap: 12px;
1168
+ padding: 14px 15px;
1169
+ background: var(--aikaara-section-bg, #eaf2fd);
1170
+ border: 1px solid var(--aikaara-section-border, #d4e4fb);
1171
+ border-radius: 12px;
1172
+ }
1173
+ .intro-icon { font-size: 20px; line-height: 1.2; }
1174
+ .intro-title {
1175
+ font-size: 14px; font-weight: 700;
1176
+ color: var(--aikaara-text-strong, #0f2f5c);
1177
+ }
1178
+ .intro-sub {
1179
+ font-size: 12.5px; margin-top: 2px;
1180
+ color: var(--aikaara-text-muted, #5b7798);
1181
+ }
1182
+ .chip-grid { display: flex; flex-wrap: wrap; gap: 9px; }
1183
+ .chip {
1184
+ display: inline-flex; align-items: center; gap: 7px;
1185
+ padding: 9px 13px;
1186
+ border: 1px solid var(--aikaara-input-border, #cbd5e1);
1187
+ border-radius: 999px;
1188
+ background: #ffffff;
1189
+ font: inherit; font-size: 13px; font-weight: 500;
1190
+ color: var(--aikaara-text, #1f2937);
1191
+ cursor: pointer;
1192
+ transition: border-color 150ms, background 150ms, box-shadow 150ms;
1193
+ }
1194
+ .chip:hover {
1195
+ border-color: var(--aikaara-primary, #2563eb);
1196
+ background: var(--aikaara-primary-soft, rgba(37,99,235,0.06));
1197
+ }
1198
+ .chip-icon { font-size: 14px; line-height: 1; }
1199
+ .chip-label { white-space: nowrap; }
1200
+
1201
+ /* ── footer button ──────────────────────────────────────── */
1202
+ .primary-btn {
1203
+ width: 100%;
1204
+ padding: 13px 18px;
1205
+ background: var(--aikaara-primary, #2563eb);
1206
+ color: #ffffff;
1207
+ border: none;
1208
+ border-radius: 10px;
1209
+ font: inherit; font-size: 14.5px; font-weight: 700;
1210
+ cursor: pointer;
1211
+ transition: filter 150ms;
1212
+ }
1213
+ .primary-btn:hover { filter: brightness(1.07); }
1214
+ .primary-btn:active { filter: brightness(0.95); }
1215
+
1216
+ .empty {
1217
+ padding: 40px 12px;
1218
+ text-align: center;
1219
+ color: var(--aikaara-text-muted, #64748b);
1220
+ font-size: 14px;
1221
+ }
1222
+
1223
+ @media (max-width: 600px) {
1224
+ .backdrop { padding: 0; align-items: flex-end; }
1225
+ .modal {
1226
+ width: 100%;
1227
+ max-height: 94vh;
1228
+ border-radius: 16px 16px 0 0;
1229
+ }
1230
+ }
1231
+ `}}const $s='<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>',Hd='<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 Wd(a){return a.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function qs(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class oc extends HTMLElement{shadow;schema=null;value={};errors=new Map;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setSchema(e){this.schema=e,this.isRepeatable()&&!Array.isArray(this.value)?this.value=[]:!this.isRepeatable()&&Array.isArray(this.value)&&(this.value={}),this.render()}setValue(e){this.isRepeatable()?(this.value=Array.isArray(e)?[...e]:[],this.value.length===0&&this.value.push({})):this.value=e&&typeof e=="object"?{...e}:{},this.render()}isRepeatable(){return!!this.schema?.repeatable&&this.schema.repeatable.maxCount>0}getEntries(){return this.isRepeatable()?this.value:[this.value]}setEntry(e,t,r){this.setEntryNoRender(e,t,r),this.render()}setEntryNoRender(e,t,r){const i=this.getEntries(),n={...i[e]||{}};n[t]=r,i[e]=n,this.isRepeatable()?this.value=i:this.value=n}addEntry(){if(!this.isRepeatable()||!this.schema?.repeatable)return;const e=this.getEntries();e.length>=this.schema.repeatable.maxCount||(e.push({}),this.value=e,this.render())}removeEntry(e){if(!this.isRepeatable())return;const t=this.getEntries();t.length<=1||(t.splice(e,1),this.value=t,this.render())}fieldVisible(e,t){const r=o=>{if(!o)return null;const s=t[o.field];return"equals"in o?s===o.equals:Array.isArray(o.in)?o.in.includes(s):null};return!(r(e.showWhen)===!1||r(e.hideWhen)===!0)}validate(){return this.errors.clear(),this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],i=>{if(!this.fieldVisible(i,t)||i.type==="group")return;const n=t[i.id],o=`${r}.${i.id}`;if(i.required&&(n==null||n==="")){this.errors.set(o,"Required");return}if(i.type==="text"&&typeof n=="string"&&(i.pattern&&n&&!new RegExp(i.pattern).test(n)?this.errors.set(o,"Invalid format"):i.maxLength&&n.length>i.maxLength&&this.errors.set(o,`Max ${i.maxLength} characters`)),i.type==="textarea"&&typeof n=="string"&&i.maxLength&&n.length>i.maxLength&&this.errors.set(o,`Max ${i.maxLength} characters`),i.type==="number"&&n!==void 0&&n!==null&&n!==""){const s=typeof n=="number"?n:Number(n),l=i;Number.isNaN(s)?this.errors.set(o,"Must be a number"):l.min!==void 0&&s<l.min?this.errors.set(o,`Minimum ${l.min}`):l.max!==void 0&&s>l.max&&this.errors.set(o,`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((i,n)=>this.renderEntry(i,n)).join(""),r=this.isRepeatable()&&e.length<(this.schema.repeatable?.maxCount||1);this.shadow.innerHTML=`
1232
+ <style>${this.css()}</style>
1233
+ <div class="container">
1234
+ <div class="scroll">
1235
+ <div class="section-card">
1236
+ <span class="section-icon">${this.schema.icon??"📝"}</span>
1237
+ <div class="section-meta">
1238
+ <div class="section-title">${Ye(this.schema.title)}</div>
1239
+ ${this.schema.hint?`<div class="section-hint">${Ye(this.schema.hint)}</div>`:""}
1240
+ </div>
1241
+ </div>
1242
+ <div class="entries">${t}</div>
1243
+ ${r?'<button class="add-btn" type="button" data-action="add-entry">+ Add another</button>':""}
1244
+ </div>
1245
+ <div class="footer">
1246
+ <button class="save-btn" type="button" data-action="save">
1247
+ ${Ye(this.schema.submitLabel||"Save")}
1248
+ </button>
1249
+ </div>
1250
+ </div>
1251
+ `,this.bindHandlers()}renderEntry(e,t){const i=this.isRepeatable()&&this.schema?.repeatable?this.schema.repeatable.labelTemplate.replace("{index}",String(t+1)):"",n=this.isRepeatable()&&this.getEntries().length>1?`<button class="remove-btn" type="button" data-entry-index="${t}" data-action="remove-entry" aria-label="Remove">Remove</button>`:"",o=(this.schema?.fields||[]).map(l=>this.renderField(l,e,t)).join("");return`<section class="entry-card">${i?`<div class="entry-header">
1252
+ <span class="entry-label">
1253
+ ${this.schema?.entryIcon?`<span class="entry-icon">${this.schema.entryIcon}</span>`:""}
1254
+ ${Ye(i)}
1255
+ </span>
1256
+ ${n}
1257
+ </div>`:""}<div class="entry-body">${o}</div></section>`}renderField(e,t,r){if(!this.fieldVisible(e,t))return"";if(e.type==="group"){const h=e,p=h.fields.map(b=>this.renderField(b,t,r)).join("");return`
1258
+ <fieldset class="group">
1259
+ ${h.title?`<legend class="group-title">${Ye(h.title)}</legend>`:""}
1260
+ ${h.hint?`<div class="group-hint">${Ye(h.hint)}</div>`:""}
1261
+ <div class="group-body">${p}</div>
1262
+ </fieldset>`}const i=`${r}.${e.id}`,n=this.errors.get(i),o=n?"has-error":"",s=e.required?'<span class="req">*</span>':"",l=e.label?`<label class="field-label" for="${this.fieldHtmlId(e,r)}">${Ye(e.label)} ${s}</label>`:"",c=this.renderInput(e,t,r),u=n?`<div class="field-error">${Ye(n)}</div>`:"";return`
1263
+ <div class="field ${o}" data-field-id="${e.id}" data-entry-index="${r}">
1264
+ ${l}
1265
+ ${c}
1266
+ ${u}
1267
+ </div>`}renderInput(e,t,r){const i=t[e.id],n=this.fieldHtmlId(e,r),o=`data-field-id="${e.id}" data-entry-index="${r}"`;if(e.type==="text"){const s=e;return`<input type="text" class="input" id="${n}" ${o} value="${St(String(i??""))}" placeholder="${St(s.placeholder??"")}" ${s.maxLength?`maxlength="${s.maxLength}"`:""}/>`}if(e.type==="textarea"){const s=e;return`<textarea class="input textarea" id="${n}" ${o} rows="${s.rows??4}" placeholder="${St(s.placeholder??"")}" ${s.maxLength?`maxlength="${s.maxLength}"`:""}>${Ye(String(i??""))}</textarea>`}if(e.type==="number"){const s=e;return`
1268
+ <div class="input-with-prefix">
1269
+ ${s.currency?`<span class="prefix">${Ye(s.currency)}</span>`:""}
1270
+ <input type="number" class="input" id="${n}" ${o} value="${St(String(i??""))}" placeholder="${St(s.placeholder??"")}" ${s.min!==void 0?`min="${s.min}"`:""} ${s.max!==void 0?`max="${s.max}"`:""}/>
1271
+ </div>`}if(e.type==="date")return`<input type="date" class="input" id="${n}" ${o} value="${St(String(i??""))}"/>`;if(e.type==="radio")return`
1272
+ <div class="radio-group">
1273
+ ${e.options.map(l=>{const c=i===l.value?"checked":"",u=`${n}-${l.value}`;return`
1274
+ <label class="radio-item ${c?"selected":""}" for="${u}">
1275
+ <input type="radio" id="${u}" ${o} name="${n}" value="${St(l.value)}" ${c}/>
1276
+ <span class="radio-label">${Ye(l.label)}</span>
1277
+ </label>`}).join("")}
1278
+ </div>`;if(e.type==="yes-no"){const s=i===!0?"checked":"",l=i===!1?"checked":"";return`
1279
+ <div class="radio-group">
1280
+ <label class="radio-item ${s?"selected":""}">
1281
+ <input type="radio" ${o} name="${n}" value="true" ${s}/>
1282
+ <span class="radio-label">Yes</span>
1283
+ </label>
1284
+ <label class="radio-item ${l?"selected":""}">
1285
+ <input type="radio" ${o} name="${n}" value="false" ${l}/>
1286
+ <span class="radio-label">No</span>
1287
+ </label>
1288
+ </div>`}return e.type==="checkbox"?`
1289
+ <label class="checkbox-item">
1290
+ <input type="checkbox" id="${n}" ${o} ${i===!0?"checked":""}/>
1291
+ <span class="checkbox-label">${Ye(e.label??"")}</span>
1292
+ </label>`:""}fieldHtmlId(e,t){return`aikf-${e.id}-${t}`}bindHandlers(){this.shadow.querySelectorAll("input[data-field-id], textarea[data-field-id]").forEach(e=>{const t=e,r=t.dataset.fieldId,i=Number(t.dataset.entryIndex||0),o=t.type==="radio"||t.type==="checkbox"?"change":"input";t.addEventListener(o,()=>{let s;t.type==="checkbox"?s=t.checked:t.type==="radio"?t.value==="true"?s=!0:t.value==="false"?s=!1:s=t.value:t.type==="number"?s=t.value===""?null:Number(t.value):s=t.value,o==="input"?this.setEntryNoRender(i,r,s):this.setEntry(i,r,s)})}),this.shadow.querySelector('[data-action="save"]')?.addEventListener("click",()=>this.handleSubmit()),this.shadow.querySelector('[data-action="add-entry"]')?.addEventListener("click",()=>this.addEntry()),this.shadow.querySelectorAll('[data-action="remove-entry"]').forEach(e=>{e.addEventListener("click",()=>{const t=Number(e.dataset.entryIndex||0);this.removeEntry(t)})})}css(){return`
1293
+ /* Pure-flex height chain — no percentage heights, which do not
1294
+ resolve reliably through a max-height-only flex ancestor. The
1295
+ modal makes this element a flex item (flex:1; min-height:0); we
1296
+ then flex all the way down to .scroll so it owns the overflow. */
1297
+ :host {
1298
+ display: flex;
1299
+ flex-direction: column;
1300
+ min-height: 0;
1301
+ color: var(--aikaara-text, #0f172a);
1302
+ font-family: var(--aikaara-font, system-ui, -apple-system, sans-serif);
1303
+ }
1304
+ .container { display: flex; flex-direction: column; flex: 1 1 auto; min-height: 0; }
1305
+ .scroll {
1306
+ flex: 1; min-height: 0; overflow-y: auto;
1307
+ padding: 16px 18px 8px;
1308
+ display: flex; flex-direction: column; gap: 14px;
1309
+ }
1310
+ .section-card {
1311
+ display: flex; align-items: center; gap: 12px;
1312
+ padding: 13px 15px;
1313
+ background: var(--aikaara-section-bg, #eaf2fd);
1314
+ border: 1px solid var(--aikaara-section-border, #d4e4fb);
1315
+ border-radius: 12px;
1316
+ }
1317
+ .section-icon { font-size: 20px; line-height: 1; flex-shrink: 0; }
1318
+ .section-meta { min-width: 0; }
1319
+ .section-title { font-size: 15px; font-weight: 700; color: var(--aikaara-text-strong, #0f2f5c); }
1320
+ .section-hint { font-size: 12px; color: var(--aikaara-text-muted, #5b7798); margin-top: 2px; }
1321
+ .entries { display: flex; flex-direction: column; gap: 14px; }
1322
+ .entry-card {
1323
+ border: 1px solid var(--aikaara-border, #e3e8ef);
1324
+ border-radius: 12px;
1325
+ overflow: hidden;
1326
+ background: #ffffff;
1327
+ }
1328
+ .entry-header {
1329
+ display: flex; align-items: center; justify-content: space-between;
1330
+ padding: 10px 14px;
1331
+ background: var(--aikaara-entry-bg, #e8f1fd);
1332
+ border-bottom: 1px solid var(--aikaara-section-border, #d4e4fb);
1333
+ }
1334
+ .entry-label {
1335
+ display: inline-flex; align-items: center; gap: 7px;
1336
+ font-size: 13.5px; font-weight: 700;
1337
+ color: var(--aikaara-primary, #2563eb);
1338
+ }
1339
+ .entry-icon { font-size: 15px; }
1340
+ .remove-btn {
1341
+ background: transparent; border: none; cursor: pointer;
1342
+ font: inherit; font-size: 12px; font-weight: 600;
1343
+ color: #b91c1c;
1344
+ padding: 3px 8px; border-radius: 6px;
1345
+ }
1346
+ .remove-btn:hover { background: rgba(185,28,28,0.10); }
1347
+ .entry-body { padding: 14px; display: flex; flex-direction: column; gap: 14px; }
1348
+ .group {
1349
+ border: 1px solid var(--aikaara-group-border, #dbe7e0);
1350
+ border-radius: 10px;
1351
+ padding: 0;
1352
+ margin: 0;
1353
+ background: var(--aikaara-group-bg, #f1f7f3);
1354
+ overflow: hidden;
1355
+ }
1356
+ .group-title {
1357
+ display: block;
1358
+ float: none;
1359
+ width: 100%;
1360
+ box-sizing: border-box;
1361
+ padding: 10px 13px;
1362
+ font-size: 12.5px; font-weight: 700;
1363
+ color: var(--aikaara-text-strong, #1f3b2e);
1364
+ background: var(--aikaara-group-head, #e6f1ea);
1365
+ border-bottom: 1px solid var(--aikaara-group-border, #dbe7e0);
1366
+ }
1367
+ .group-hint {
1368
+ font-size: 11.5px;
1369
+ color: var(--aikaara-text-muted, #5b7798);
1370
+ font-style: italic;
1371
+ padding: 8px 13px 0;
1372
+ }
1373
+ .group-body { padding: 12px 13px; display: flex; flex-direction: column; gap: 12px; }
1374
+ .field { display: flex; flex-direction: column; gap: 6px; }
1375
+ .field-label {
1376
+ font-size: 12.5px; font-weight: 600;
1377
+ color: var(--aikaara-text, #334155);
1378
+ }
1379
+ .req { color: #dc2626; }
1380
+ .input {
1381
+ width: 100%;
1382
+ padding: 10px 12px;
1383
+ font: inherit;
1384
+ font-size: 13.5px;
1385
+ border: 1px solid var(--aikaara-input-border, #cbd5e1);
1386
+ border-radius: 8px;
1387
+ background: #ffffff;
1388
+ color: inherit;
1389
+ box-sizing: border-box;
1390
+ outline: none;
1391
+ transition: border-color 150ms, box-shadow 150ms;
1392
+ }
1393
+ .textarea { resize: vertical; min-height: 70px; line-height: 1.45; }
1394
+ .input:focus {
1395
+ border-color: var(--aikaara-primary, #2563eb);
1396
+ box-shadow: 0 0 0 3px rgba(37,99,235,0.16);
1397
+ }
1398
+ .field.has-error .input,
1399
+ .field.has-error .input-with-prefix { border-color: #dc2626; }
1400
+ .input-with-prefix {
1401
+ display: flex; align-items: stretch;
1402
+ border: 1px solid var(--aikaara-input-border, #cbd5e1);
1403
+ border-radius: 8px;
1404
+ background: #ffffff;
1405
+ overflow: hidden;
1406
+ }
1407
+ .input-with-prefix .prefix {
1408
+ padding: 0 11px;
1409
+ display: flex; align-items: center;
1410
+ background: var(--aikaara-prefix-bg, #f1f5f9);
1411
+ color: var(--aikaara-text-muted, #475569);
1412
+ font-size: 13.5px;
1413
+ border-right: 1px solid var(--aikaara-input-border, #cbd5e1);
1414
+ }
1415
+ .input-with-prefix .input { border: none; border-radius: 0; }
1416
+ .input-with-prefix:focus-within {
1417
+ border-color: var(--aikaara-primary, #2563eb);
1418
+ box-shadow: 0 0 0 3px rgba(37,99,235,0.16);
1419
+ }
1420
+ .radio-group { display: flex; flex-wrap: wrap; gap: 10px; padding: 2px 0; }
1421
+ .radio-item {
1422
+ display: inline-flex; align-items: center; gap: 8px;
1423
+ font-size: 13px; cursor: pointer;
1424
+ padding: 8px 13px;
1425
+ border: 1px solid var(--aikaara-input-border, #cbd5e1);
1426
+ border-radius: 8px;
1427
+ background: #ffffff;
1428
+ transition: border-color 150ms, background 150ms;
1429
+ }
1430
+ .radio-item.selected {
1431
+ border-color: var(--aikaara-primary, #2563eb);
1432
+ background: var(--aikaara-primary-soft, rgba(37,99,235,0.08));
1433
+ }
1434
+ .radio-item input[type="radio"] { accent-color: var(--aikaara-primary, #2563eb); }
1435
+ .checkbox-item {
1436
+ display: inline-flex; align-items: center; gap: 8px;
1437
+ font-size: 13px; cursor: pointer;
1438
+ }
1439
+ .checkbox-item input[type="checkbox"] { accent-color: var(--aikaara-primary, #2563eb); }
1440
+ .field-error { font-size: 11.5px; color: #dc2626; }
1441
+ .add-btn {
1442
+ align-self: flex-start;
1443
+ background: transparent;
1444
+ border: 1px dashed var(--aikaara-primary, #2563eb);
1445
+ color: var(--aikaara-primary, #2563eb);
1446
+ font: inherit; font-size: 13px; font-weight: 600;
1447
+ padding: 9px 15px;
1448
+ border-radius: 8px;
1449
+ cursor: pointer;
1450
+ }
1451
+ .add-btn:hover { background: var(--aikaara-primary-soft, rgba(37,99,235,0.08)); }
1452
+ .footer {
1453
+ flex-shrink: 0;
1454
+ padding: 12px 18px;
1455
+ border-top: 1px solid var(--aikaara-border, #e3e8ef);
1456
+ background: var(--aikaara-surface, #ffffff);
1457
+ }
1458
+ .save-btn {
1459
+ width: 100%;
1460
+ padding: 13px 18px;
1461
+ background: var(--aikaara-primary, #2563eb);
1462
+ color: #ffffff;
1463
+ border: none;
1464
+ border-radius: 10px;
1465
+ font: inherit; font-size: 14.5px; font-weight: 700;
1466
+ cursor: pointer;
1467
+ transition: filter 150ms;
1468
+ }
1469
+ .save-btn:hover { filter: brightness(1.07); }
1470
+ .save-btn:active { filter: brightness(0.95); }
1471
+ `}}function St(a){return a.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ye(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function sc(){const a=[["aikaara-chat-widget",Bl],["aikaara-chat-bubble",Dl],["aikaara-chat-header",Fl],["aikaara-message-list",ql],["aikaara-message-bubble",Wl],["aikaara-chat-input",zl],["aikaara-typing-indicator",Vl],["aikaara-streaming-message",Gl],["aikaara-error-banner",Kl],["aikaara-template-renderer",Ql],["aikaara-system-pill",Jl],["aikaara-option-list",Xl],["aikaara-submit-action",Zl],["aikaara-modal-action",ec],["aikaara-chat",tc],["aikaara-link-modal",rc],["aikaara-compare-plans",nc],["aikaara-smart-edit-modal",ic],["aikaara-schema-form",oc]];for(const[e,t]of a)customElements.get(e)||customElements.define(e,t)}sc();function lr(a,e,t=""){if(!e)return t;const r=e.split(".");let i=a;for(const n of r)if(i&&typeof i=="object"&&n in i)i=i[n];else return t;return typeof i=="string"?i:t}function Hs(a){try{const e=a.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(a){return typeof a=="function"?await a():a}class ac{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=Hs(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}",i={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",o={method:n,headers:i};n==="POST"&&(i["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,o);if(!s.ok){const w=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${w.slice(0,200)}`)}const l=await s.json().catch(()=>({})),c=lr(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,h=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!h)throw new Error("Session auth response missing token");const p=lr(l,this.descriptor.requestIdPath??"data.requestId"),b=this.cache?.requestId||p||"",f=lr(l,this.descriptor.fullNamePath??"data.fullName"),g=lr(l,this.descriptor.userPath??"data.userId"),y=Hs(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:b,fullName:f,userId:g,expiresAt:y},this.cache}}async function lc(a){const e={};for(const t of a.spec){const r=await zd(t,a.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function zd(a,e){const t=a.key??a.name;switch(a.source){case"cookie":return Vd(t);case"localStorage":return cr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return cr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return cr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return cr(()=>document.querySelector(`meta[name="${Gd(t)}"]`)?.content??void 0);case"callback":{const r=e?.[a.name];if(!r)return;const i=await r();return typeof i=="string"?i:void 0}default:return}}function Vd(a){if(typeof document>"u")return;const e=encodeURIComponent(a),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===a||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function cr(a){try{return a()}catch{return}}function Gd(a){return a.replace(/["\\]/g,"\\$&")}const Kd=1800;class cc{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 lc({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const i=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!i)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(i,{method:"POST",headers:r,body:t});if(!n.ok){const h=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${h.slice(0,240)}`)}const s=(await n.json().catch(()=>({}))).user??{},l=String(s.ext_uid??s.extUid??""),c=String(s.token??s.user_token??s.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:s.id,extUid:l,userToken:c,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Kd;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 Yd=3e4,Qd=2e3,Jd=100;async function uc(a){const{descriptor:e}=a,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!a.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:a.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Xd(r);if(!i)throw new Ke("query",`?${r}= not present`);return{token:i,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Zd(r);if(!i)throw new Ke("hash",`#${r}= not present`);return{token:i,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",i=typeof t.key=="string"&&t.key?t.key:"token",n=of(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Yd;return{token:await nf({type:r,key:i,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const i=ef(r);if(!i)throw new Ke("cookie",`cookie "${r}" not set`);return{token:i,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",i=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!i)throw new Ke("storage","storage.key not configured");const o=tf(r,i,n);if(!o)throw new Ke("storage",`${r}Storage["${i}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Qd,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Jd,o=await rf(r,i,n);if(!o)throw new Ke("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class hc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await uc(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 Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function Xd(a){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))===a)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function Zd(a){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(a)??void 0}catch{return}}function ef(a){if(typeof document>"u")return;const e=encodeURIComponent(a),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===a||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function tf(a,e,t){if(!(typeof window>"u"))try{const i=(a==="session"?window.sessionStorage:window.localStorage).getItem(e);if(i==null)return;if(!t)return i;let n;try{n=JSON.parse(i)}catch{return i}const o=dc(n,t);return typeof o=="string"?o:void 0}catch{return}}async function rf(a,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const i=dc(window,a);if(typeof i=="string"&&i.length>0)return i;if(typeof i=="function")try{const n=i();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function nf(a){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(i)},i=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${a.timeoutMs}ms`))},a.timeoutMs),n=o=>{if(a.origins.length>0&&!a.origins.includes(o.origin))return;const s=o.data;if(!s||typeof s!="object")return;const l=s;if(a.type&&l.type!==a.type)return;const c=l[a.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function of(a){return a?a.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function dc(a,e){if(!e)return a;const t=e.split(".").filter(Boolean);let r=a;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function sf(){const a=typeof crypto<"u"?crypto:null;if(a?.randomUUID)return a.randomUUID();if(a?.getRandomValues){const e=new Uint8Array(16);a.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 af="aikaara_chat:requestId";function wo(a,e,t){const r=`${af}:${a}:${e}`;return t?`${r}:${t}`:r}function fc(a,e,t){try{return localStorage.getItem(wo(a,e,t))}catch{return null}}function lf(a,e,t,r){try{localStorage.setItem(wo(a,e,r),t)}catch{}}function cf(a,e,t){try{localStorage.removeItem(wo(a,e,t))}catch{}}async function to(a,e,t="before-chat"){const r=a.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const i={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,h]of Object.entries(e.identity))typeof h=="string"&&(i[u]=h);typeof e.serviceType=="string"&&(i.serviceType=e.serviceType),typeof e.userType=="string"&&(i.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(h,p)=>p in i?i[p]:""),o=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(o);if(u&&typeof u=="object"){const h={};for(const[p,b]of Object.entries(u))h[p]=o(b);return h}return u},s=await Zt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const h=r[u],p=n(h.url),b=h.method??(h.body?"POST":"GET"),f={accept:"application/json",...h.headers??{}};if((h.authHeader??"session")==="session"){const x=h.authHeaderTemplate??"Bearer {token}";f.authorization=x.replace("{token}",s)}const g={method:b,headers:f};h.body&&(f["content-type"]="application/json",g.body=JSON.stringify(o(h.body)));let y=0,w="",m=0,_=null;for(;;)try{const x=await fetch(p,g);if(x.ok){_=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&hf(y,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${b} ${p} → ${y} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${b} ${p} → ${y} ${w.slice(0,200)}`;if(h.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(x){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,x),await new Promise(E=>setTimeout(E,v));continue}if(h.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(_&&h.capture&&h.capture.as)try{const x=await _.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(h.capture.path)for(const E of h.capture.path.split("."))if(v&&typeof v=="object"&&E in v)v=v[E];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let E=v;h.capture.stripPrefix&&E.startsWith(h.capture.stripPrefix)&&(E=E.slice(h.capture.stripPrefix.length)),l[h.capture.as]=E,i[h.capture.as]=E,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${h.capture.as} (${E.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function uf(a){const e=a.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await to(e,{sessionToken:a.sessionToken,userId:a.userId,projectId:a.projectId??"",slug:a.slug??"",identity:a.identity,serviceType:a.serviceType,userType:a.userType},"on-method-select")).captured:{}}function hf(a,e){if(a===503||a===504||a===502)return!0;if(a===401||a===403)return e.trim().length===0;if(a===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function pc(a,e){const t=await fetch(a,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${i.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function mc(a,e){return a.replace("{projectId}",e).replace("{uuid}",sf().replace(/-/g,""))}function gc(a){const e=a._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>Yl(r)))}async function bc(a){const e={...a.config??(a.configUrl?await pc(a.configUrl,a.configHeaders):{}),...a.overrides??{}};gc(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const i=r?.projectId??"",n=a.identity.userId,o=a.conversationScope||void 0,s=a.forceNewConversation?null:fc(n,i,o),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=a.conversationId??s??mc(l,i);(a.conversationId||!s||a.forceNewConversation)&&i&&lf(n,i,c,o);const u=await a.tokenProvider(),h=a.tokenProvider,p=a.historyTokenProvider??h,b=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:a.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,...a.identity.departmentId?{departmentId:a.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:a.identity.senderFullname??a.identity.userName,tokenProvider:h}:void 0,f=a.uploadAdapter??(e.uploadEndpoint?vo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),g=a.historyAdapter??(e.historyApiBase?Rl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),y={transport:t,baseUrl:"",userToken:a.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:a.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:b,tiledeskIdentity:{userId:n,userName:a.identity.userName,departmentId:a.identity.departmentId,senderFullname:a.identity.senderFullname??a.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:f,historyAdapter:g,onError:a.onError,onMessage:a.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;"),a.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function df(a){if(typeof a!="string")return a;const e=document.querySelector(a);if(!e)throw new Error(`mountFromSlug: container "${a}" not found`);return e}async function yc(a){const e=(a.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(a.slug)}`;let r=null;try{r=await pc(t,a.configHeaders)}catch(I){if(!a.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${a.slug}" — using fallbackConfig.`,I)}const i={...a.fallbackConfig??{},...r??{},...a.overrides??{}};if(gc(i),i.templates&&Object.keys(i.templates).length>0){i.components={...i.components??{}};for(const[I,O]of Object.entries(i.templates)){const P=`template:${I}`;i.components[P]||!O?.scriptUrl||!O?.render||(i.components[P]={kind:"iife-element",scriptUrl:O.scriptUrl,tag:O.render,...O.props?{props:O.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:i.templates,components:i.components,razorpay:i.razorpay,title:i.title,cloud:i.cloud??n.__aikaara_descriptor__?.cloud,upload:i.upload??n.__aikaara_descriptor__?.upload,themeSource:i.themeSource??n.__aikaara_descriptor__?.themeSource,api:i.api,auth:i.auth},!i.auth)throw new Error(`mountFromSlug: widget_configs/${a.slug} descriptor must include "auth" block`);let o=null,s=a.user.id,l=a.user.name,c="",u=a.user.token,h=null;const p=await Zt(a.user.token).catch(()=>""),b=typeof p=="string"&&p.length>0;if(!b&&i.sso?.tokenSource){h=new hc({descriptor:{provider:i.sso.provider,flow:i.sso.flow,skipLogin:i.sso.skipLogin,autoRefresh:i.sso.autoRefresh,tokenSource:i.sso.tokenSource,tokenSourceConfig:i.sso.tokenSourceConfig,fallback:i.sso.fallback,map:i.sso.map},initToken:a.user.partnerToken});const I=await h.get();u=async()=>(await h.get()).token,a.user.identity&&!a.user.identity.partnerToken&&(a.user.identity.partnerToken=I.token)}else if(!b&&i.sso&&i.sso.collect&&i.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(a.slug)}/sso_exchange`;o=await new cc({descriptor:i.sso,providers:a.user.credentialProviders,exchangeUrl:I}).get(),s=o.extUid||s,l=l??o.displayName,c=o.userToken}let f="",g="";if(i.preflight&&i.preflight.length){const I=await to(i.preflight,{sessionToken:u,userId:s,projectId:i.tiledesk?.projectId??"",slug:a.slug,identity:a.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const O=f;u=()=>O}I.captured.userId&&(s=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const y=new ac(i.auth,u);if(f){const I=i.tiledesk?.projectId??"",O=I?fc(s,I):null,P=i.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",N=O??(I?mc(P,I):"");y.prime(f,{requestId:N,fullName:l})}const w=await y.get();s=s||w.userId;const m=w.fullName||l||s;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,identity:a.user.identity,slug:a.slug,configBase:e};const _=h&&i.sso?.autoRefresh?async()=>{try{return await h.refresh(),y.reset(),(await y.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=i.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await y.get()).token:await Zt(a.user.token)}`,E=a.hooks?.upload??(x&&x.mode==="presigned-3step"?Ml({...x,authHeader:v}):x&&x.mode==="direct"?vo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await bc({container:df(a.container),config:i,userToken:c||void 0,identity:{userId:s,userName:m,departmentId:a.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:E,historyAdapter:a.hooks?.history,conversationId:w.requestId||g||void 0,conversationScope:a.conversationScope,onError:a.hooks?.onError,onMessage:a.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Zt(a.user.token)});return Object.assign(S,{fullName:m,requestId:w.requestId,descriptor:i,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return _?_():null},async runMethodSelectPreflight(I){const O=i.preflight;return!O||!O.length?{}:O.some(N=>N.trigger==="on-method-select")?(await to(O,{sessionToken:u,userId:s,projectId:i.tiledesk?.projectId??"",slug:a.slug,identity:{...a.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}exports.ActionCableClient=en;exports.AikaaraChat=tc;exports.AikaaraChatBubble=Dl;exports.AikaaraChatClient=Pl;exports.AikaaraChatHeader=Fl;exports.AikaaraChatInput=zl;exports.AikaaraChatWidget=Bl;exports.AikaaraComparePlans=nc;exports.AikaaraErrorBanner=Kl;exports.AikaaraLinkModal=rc;exports.AikaaraMessageBubble=Wl;exports.AikaaraMessageList=ql;exports.AikaaraModalAction=ec;exports.AikaaraOptionList=Xl;exports.AikaaraSchemaForm=oc;exports.AikaaraSmartEditModal=ic;exports.AikaaraStreamingMessage=Gl;exports.AikaaraSubmitAction=Zl;exports.AikaaraSystemPill=Jl;exports.AikaaraTemplateRenderer=Ql;exports.AikaaraTypingIndicator=Vl;exports.ApiClient=Vs;exports.ChannelSubscription=Ws;exports.ConnectionManager=zs;exports.ConversationManager=Ys;exports.EventEmitter=ro;exports.MessageStore=Gs;exports.SessionAuthAdapter=ac;exports.SsoExchangeAdapter=cc;exports.TiledeskTransport=Il;exports.TokenDiscoveryError=Ke;exports.TokenDiscoveryReader=hc;exports.clearPersistedConversationId=cf;exports.collectSsoCredentials=lc;exports.createFetchUploadAdapter=vo;exports.createPresigned3StepUploadAdapter=Ml;exports.createTiledeskHistoryAdapter=Rl;exports.discoverToken=uc;exports.extractTiledeskFileEnvelope=Ol;exports.inferTiledeskRole=Cl;exports.isTiledeskSelfEcho=Tl;exports.mount=bc;exports.mountFromSlug=yc;exports.parseTiledeskTemplate=yo;exports.registerComponents=sc;exports.runMethodSelectPreflight=uf;