bitmax-crm-widget 1.0.8 β†’ 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,16 +1,31 @@
1
1
  # Chat CRM Widget
2
2
 
3
- Universal chat widget that works on **any website** - React, Vue, HTML, WordPress, Shopify, and more!
3
+ Universal Help & Support widget with **Chat** and **Ticketing System** that works on **any website** - React, Vue, HTML, WordPress, Shopify, and more!
4
4
 
5
5
  ## ✨ Features
6
6
 
7
- - πŸš€ **Universal**: Works with React, Vue, Angular, HTML, WordPress, etc.
7
+ ### 🎯 Help & Support Menu
8
+ - **Start Query**: Real-time chat with support agents
9
+ - **Raise Ticket**: Complete ticketing system with full management
10
+
11
+ ### πŸ’¬ Query/Chat System
12
+ - ⚑ **Real-time**: Socket.IO powered instant messaging
8
13
  - πŸ‘€ **Smart User Detection**: Automatically supports both logged-in users and guests
9
- - 🎨 **Fully Customizable**: Colors, position, theme, welcome message
10
- - πŸ“± **Responsive**: Mobile-first design
11
- - πŸŒ™ **Dark Mode**: Built-in dark theme support
12
14
  - πŸ”” **Notifications**: Unread message badges and sound alerts
13
- - ⚑ **Real-time**: Socket.IO powered instant messaging
15
+ - πŸ“Έ **Camera Support**: Agent can request camera snapshots
16
+
17
+ ### 🎫 Ticketing System (NEW in v1.2.0)
18
+ - πŸ“ **Create Tickets**: Submit support tickets with priority and category
19
+ - πŸ“Š **Track Status**: View open, pending, and closed tickets
20
+ - πŸ” **History**: Complete ticket history with filtering
21
+ - 🎨 **Professional UI**: Full-page overlay with modern design
22
+ - πŸ“± **Fully Responsive**: Works perfectly on all devices
23
+
24
+ ### 🎨 Customization & Design
25
+ - πŸš€ **Universal**: Works with React, Vue, Angular, HTML, WordPress, etc.
26
+ - 🎨 **Fully Customizable**: Colors, position, theme, welcome message
27
+ - πŸŒ™ **Dark Mode**: Built-in dark theme support for all components
28
+ - πŸ“± **Mobile-First**: Responsive design for all screen sizes
14
29
  - πŸ”’ **Secure**: API key based authentication
15
30
  - πŸ“¦ **Lightweight**: < 50KB gzipped
16
31
 
@@ -1,4 +1,4 @@
1
1
  !function(){"use strict";function t(t,e,n,s,i,r,o){try{var a=t[r](o),c=a.value}catch(t){return void n(t)}a.done?e(c):Promise.resolve(c).then(s,i)}function e(e){return function(){var n=this,s=arguments;return new Promise(function(i,r){var o=e.apply(n,s);function a(e){t(o,i,r,a,c,"next",e)}function c(e){t(o,i,r,a,c,"throw",e)}a(void 0)})}}function n(t,e,n){return e&&function(t,e){for(var n=0;n<e.length;n++){var s=e[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,c(s.key),s)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function s(t,e,n){return(e=c(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,s)}return n}function r(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?i(Object(n),!0).forEach(function(e){s(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function o(){
2
2
  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
3
- var t,e,n="function"==typeof Symbol?Symbol:{},s=n.iterator||"@@iterator",i=n.toStringTag||"@@toStringTag";function r(n,s,i,r){var o=s&&s.prototype instanceof h?s:h,u=Object.create(o.prototype);return a(u,"_invoke",function(n,s,i){var r,o,a,h=0,u=i||[],p=!1,l={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,n){return r=e,o=0,a=t,l.n=n,c}};function d(n,s){for(o=n,a=s,e=0;!p&&h&&!i&&e<u.length;e++){var i,r=u[e],d=l.p,f=r[2];n>3?(i=f===s)&&(a=r[(o=r[4])?5:(o=3,3)],r[4]=r[5]=t):r[0]<=d&&((i=n<2&&d<r[1])?(o=0,l.v=s,l.n=r[1]):d<f&&(i=n<3||r[0]>s||s>f)&&(r[4]=n,r[5]=s,l.n=f,o=0))}if(i||n>1)return c;throw p=!0,s}return function(i,u,f){if(h>1)throw TypeError("Generator is already running");for(p&&1===u&&d(u,f),o=u,a=f;(e=o<2?t:a)||!p;){r||(o?o<3?(o>1&&(l.n=-1),d(o,a)):l.n=a:l.v=a);try{if(h=2,r){if(o||(i="next"),e=r[i]){if(!(e=e.call(r,a)))throw TypeError("iterator result is not an object");if(!e.done)return e;a=e.value,o<2&&(o=0)}else 1===o&&(e=r.return)&&e.call(r),o<2&&(a=TypeError("The iterator does not provide a '"+i+"' method"),o=1);r=t}else if((e=(p=l.n<0)?a:n.call(s,l))!==c)break}catch(e){r=t,o=1,a=e}finally{h=1}}return{value:e,done:p}}}(n,i,r),!0),u}var c={};function h(){}function u(){}function p(){}e=Object.getPrototypeOf;var l=[][s]?e(e([][s]())):(a(e={},s,function(){return this}),e),d=p.prototype=h.prototype=Object.create(l);function f(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,p):(t.__proto__=p,a(t,i,"GeneratorFunction")),t.prototype=Object.create(d),t}return u.prototype=p,a(d,"constructor",p),a(p,"constructor",u),u.displayName="GeneratorFunction",a(p,i,"GeneratorFunction"),a(d),a(d,i,"Generator"),a(d,s,function(){return this}),a(d,"toString",function(){return"[object Generator]"}),(o=function(){return{w:r,m:f}})()}function a(t,e,n,s){var i=Object.defineProperty;try{i({},"",{})}catch(t){i=0}a=function(t,e,n,s){function r(e,n){a(t,e,function(t){return this._invoke(e,n,t)})}e?i?i(t,e,{value:n,enumerable:!s,configurable:!s,writable:!s}):t[e]=n:(r("next",0),r("throw",1),r("return",2))},a(t,e,n,s)}function c(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var s=n.call(t,e);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}const h=Object.create(null);h.open="0",h.close="1",h.ping="2",h.pong="3",h.message="4",h.upgrade="5",h.noop="6";const u=Object.create(null);Object.keys(h).forEach(t=>{u[h[t]]=t});const p={type:"error",data:"parser error"},l="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),d="function"==typeof ArrayBuffer,f=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,m=({type:t,data:e},n,s)=>l&&e instanceof Blob?n?s(e):y(e,s):d&&(e instanceof ArrayBuffer||f(e))?n?s(e):y(new Blob([e]),s):s(h[t]+(e||"")),y=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function g(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let b;const v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)_[v.charCodeAt(t)]=t;const w="function"==typeof ArrayBuffer,k=(t,e)=>{if("string"!=typeof t)return{type:"message",data:O(t,e)};const n=t.charAt(0);if("b"===n)return{type:"message",data:E(t.substring(1),e)};return u[n]?t.length>1?{type:u[n],data:t.substring(1)}:{type:u[n]}:p},E=(t,e)=>{if(w){const n=(t=>{let e,n,s,i,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),u=new Uint8Array(h);for(e=0;e<a;e+=4)n=_[t.charCodeAt(e)],s=_[t.charCodeAt(e+1)],i=_[t.charCodeAt(e+2)],r=_[t.charCodeAt(e+3)],u[c++]=n<<2|s>>4,u[c++]=(15&s)<<4|i>>2,u[c++]=(3&i)<<6|63&r;return h})(t);return O(n,e)}return{base64:!0,data:t}},O=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,C=String.fromCharCode(30);function T(){return new TransformStream({transform(t,e){!function(t,e){l&&t.data instanceof Blob?t.data.arrayBuffer().then(g).then(e):d&&(t.data instanceof ArrayBuffer||f(t.data))?e(g(t.data)):m(t,!1,t=>{b||(b=new TextEncoder),e(b.encode(t))})}(t,n=>{const s=n.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,s)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(s))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),e.enqueue(n)})}})}let A;function S(t){return t.reduce((t,e)=>t+e.length,0)}function B(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)n[i]=t[0][s++],s===t[0].length&&(t.shift(),s=0);return t.length&&s<t[0].length&&(t[0]=t[0].slice(s)),n}function R(t){if(t)return function(t){for(var e in R.prototype)t[e]=R.prototype[e];return t}(t)}R.prototype.on=R.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},R.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},R.prototype.off=R.prototype.removeListener=R.prototype.removeAllListeners=R.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,s=this._callbacks["$"+t];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<s.length;i++)if((n=s[i])===e||n.fn===e){s.splice(i,1);break}return 0===s.length&&delete this._callbacks["$"+t],this},R.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(n){s=0;for(var i=(n=n.slice(0)).length;s<i;++s)n[s].apply(this,e)}return this},R.prototype.emitReserved=R.prototype.emit,R.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},R.prototype.hasListeners=function(t){return!!this.listeners(t).length};const x="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),N="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function L(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const I=N.setTimeout,P=N.clearTimeout;function j(t,e){e.useNativeTimers?(t.setTimeoutFn=I.bind(N),t.clearTimeoutFn=P.bind(N)):(t.setTimeoutFn=N.setTimeout.bind(N),t.clearTimeoutFn=N.clearTimeout.bind(N))}function q(t){return"string"==typeof t?function(t){let e=0,n=0;for(let s=0,i=t.length;s<i;s++)e=t.charCodeAt(s),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(s++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))}function D(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class U extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class M extends R{constructor(t){super(),this.writable=!1,j(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new U(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=k(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}}class F extends M{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const n=t.split(C),s=[];for(let t=0;t<n.length;t++){const i=k(n[t],e);if(s.push(i),"error"===i.type)break}return s})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const n=t.length,s=new Array(n);let i=0;t.forEach((t,r)=>{m(t,!1,t=>{s[r]=t,++i===n&&e(s.join(C))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=D()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let H=!1;try{H="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const V=H;function K(){}class z extends F{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class W extends R{constructor(t,e,n){super(),this.createRequest=t,j(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=L(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=W.requestsCount++,W.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=K,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete W.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(W.requestsCount=0,W.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Y);else if("function"==typeof addEventListener){addEventListener("onpagehide"in N?"pagehide":"unload",Y,!1)}function Y(){for(let t in W.requests)W.requests.hasOwnProperty(t)&&W.requests[t].abort()}const G=function(){const t=J({xdomain:!1});return t&&null!==t.responseType}();function J(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||V))return new XMLHttpRequest}catch(t){}if(!e)try{return new(N[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const $="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Q extends M{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=$?{}:L(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],s=e===t.length-1;m(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}s&&x(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=D()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const X=N.WebSocket||N.MozWebSocket;const Z={websocket:class extends Q{createSocket(t,e,n){return $?new X(t,e,n):e?new X(t,e):new X(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends M{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=function(t,e){A||(A=new TextDecoder);const n=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,a){for(n.push(o);;){if(0===s){if(S(n)<1)break;const t=B(n,1);r=!(128&~t[0]),i=127&t[0],s=i<126?3:126===i?1:2}else if(1===s){if(S(n)<2)break;const t=B(n,2);i=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),s=3}else if(2===s){if(S(n)<8)break;const t=B(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),r=e.getUint32(0);if(r>Math.pow(2,21)-1){a.enqueue(p);break}i=r*Math.pow(2,32)+e.getUint32(4),s=3}else{if(S(n)<i)break;const t=B(n,i);a.enqueue(k(r?t:A.decode(t),e)),s=0}if(0===i||i>t){a.enqueue(p);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),s=T();s.readable.pipeTo(t.writable),this._writer=s.writable.getWriter();const i=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),i())}).catch(t=>{})};i();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],s=e===t.length-1;this._writer.write(n).then(()=>{s&&x(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends z{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=G&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new W(J,this.uri(),t)}}},tt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,et=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function nt(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),s=t.indexOf("]");-1!=n&&-1!=s&&(t=t.substring(0,n)+t.substring(n,s).replace(/:/g,";")+t.substring(s,t.length));let i=tt.exec(t||""),r={},o=14;for(;o--;)r[et[o]]=i[o]||"";return-1!=n&&-1!=s&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const n=/\/{2,9}/g,s=e.replace(n,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1);"/"==e.slice(-1)&&s.splice(s.length-1,1);return s}(0,r.path),r.queryKey=function(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,s){e&&(n[e]=s)}),n}(0,r.query),r}const st="function"==typeof addEventListener&&"function"==typeof removeEventListener,it=[];st&&addEventListener("offline",()=>{it.forEach(t=>t())},!1);class rt extends R{constructor(t,e){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const n=nt(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=nt(e.host).host);j(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},n=t.split("&");for(let t=0,s=n.length;t<s;t++){let s=n[t].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}(this.opts.query)),st&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},it.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&rt.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",rt.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const n=this.writeBuffer[e].data;if(n&&(t+=q(n)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,x(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,s){if("function"==typeof e&&(s=e,e=void 0),"function"==typeof n&&(s=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(rt.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),st&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=it.indexOf(this._offlineEventListener);-1!==t&&it.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}rt.protocol=4;class ot extends rt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;rt.priorWebsocketSuccess=!1;const s=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;rt.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function i(){n||(n=!0,h(),e.close(),e=null)}const r=t=>{const n=new Error("probe error: "+t);n.transport=e.name,i(),this.emitReserved("upgradeError",n)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",s),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",s),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let at=class extends ot{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>Z[t]).filter(t=>!!t)),super(t,n)}};const ct="function"==typeof ArrayBuffer,ht=Object.prototype.toString,ut="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ht.call(Blob),pt="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ht.call(File);function lt(t){return ct&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||ut&&t instanceof Blob||pt&&t instanceof File}function dt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(dt(t[e]))return!0;return!1}if(lt(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return dt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&dt(t[e]))return!0;return!1}function ft(t){const e=[],n=t.data,s=t;return s.data=mt(n,e),s.attachments=e.length,{packet:s,buffers:e}}function mt(t,e){if(!t)return t;if(lt(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=mt(t[s],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=mt(t[s],e));return n}return t}function yt(t,e){return t.data=gt(t.data,e),delete t.attachments,t}function gt(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=gt(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=gt(t[n],e));return t}const bt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var vt;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(vt||(vt={}));function _t(t){return"[object Object]"===Object.prototype.toString.call(t)}class wt extends R{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===vt.BINARY_EVENT;n||e.type===vt.BINARY_ACK?(e.type=n?vt.EVENT:vt.ACK,this.reconstructor=new kt(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!lt(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===vt[n.type])throw new Error("unknown packet type "+n.type);if(n.type===vt.BINARY_EVENT||n.type===vt.BINARY_ACK){const s=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(s,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===t.charAt(e+1)){const s=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}n.nsp=t.substring(s,e)}else n.nsp="/";const s=t.charAt(e+1);if(""!==s&&Number(s)==s){const s=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(s,e+1))}if(t.charAt(++e)){const s=this.tryParse(t.substr(e));if(!wt.isPayloadValid(n.type,s))throw new Error("invalid payload");n.data=s}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case vt.CONNECT:return _t(e);case vt.DISCONNECT:return void 0===e;case vt.CONNECT_ERROR:return"string"==typeof e||_t(e);case vt.EVENT:case vt.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===bt.indexOf(e[0]));case vt.ACK:case vt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class kt{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=yt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Et=Object.freeze({__proto__:null,Decoder:wt,Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==vt.EVENT&&t.type!==vt.ACK||!dt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===vt.EVENT?vt.BINARY_EVENT:vt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==vt.BINARY_EVENT&&t.type!==vt.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=ft(t),n=this.encodeAsString(e.packet),s=e.buffers;return s.unshift(n),s}},get PacketType(){return vt},protocol:5});function Ot(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const Ct=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Tt extends R{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Ot(t,"open",this.onopen.bind(this)),Ot(t,"packet",this.onpacket.bind(this)),Ot(t,"error",this.onerror.bind(this)),Ot(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,s,i;if(Ct.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const r={type:vt.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),r.id=t}const o=null===(s=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===s?void 0:s.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(t,e){var n;const s=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===s)return void(this.acks[t]=e);const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},s),r=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((n,s)=>{const i=(t,e)=>t?s(t):n(e);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...s)=>{if(n!==this._queue[0])return;return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...s)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:vt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case vt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case vt.EVENT:case vt.BINARY_EVENT:this.onevent(t);break;case vt.ACK:case vt.BINARY_ACK:this.onack(t);break;case vt.DISCONNECT:this.ondisconnect();break;case vt.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...s){n||(n=!0,e.packet({type:vt.ACK,id:t,data:s}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:vt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function At(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}At.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},At.prototype.reset=function(){this.attempts=0},At.prototype.setMin=function(t){this.ms=t},At.prototype.setMax=function(t){this.max=t},At.prototype.setJitter=function(t){this.jitter=t};class St extends R{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,j(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new At({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const s=e.parser||Et;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new at(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const s=Ot(e,"open",function(){n.onopen(),t&&t()}),i=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=Ot(e,"error",i);if(!1!==this._timeout){const t=this._timeout,n=this.setTimeoutFn(()=>{s(),i(new Error("timeout")),e.close()},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(s),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ot(t,"ping",this.onping.bind(this)),Ot(t,"data",this.ondata.bind(this)),Ot(t,"error",this.onerror.bind(this)),Ot(t,"close",this.onclose.bind(this)),Ot(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){x(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Tt(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e){if(this.nsps[t].active)return}this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Bt={};function Rt(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let s=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),s=nt(t)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+e,s.href=s.protocol+"://"+i+(n&&n.port===s.port?"":":"+s.port),s}(t,(e=e||{}).path||"/socket.io"),s=n.source,i=n.id,r=n.path,o=Bt[i]&&r in Bt[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new St(s,e):(Bt[i]||(Bt[i]=new St(s,e)),a=Bt[i]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(Rt,{Manager:St,Socket:Tt,io:Rt,connect:Rt}),function(){var t=document.createElement("style");t.textContent="/* Styles will be injected by Rollup */",document.head.appendChild(t);var s=function(){return n(function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.config={apiKey:e.apiKey||"",apiUrl:e.apiUrl||"https://chat-crm-backend-7mzo.onrender.com",primaryColor:e.primaryColor||"#4F46E5",position:e.position||"bottom-right",userData:e.userData||null,welcomeMessage:e.welcomeMessage||"πŸ‘‹ Welcome! How can we help you today?",companyName:e.companyName||"Support",autoOpen:e.autoOpen||!1,showNotifications:!1!==e.showNotifications,playSound:e.playSound||!1,theme:e.theme||"light",zIndex:e.zIndex||9999},this.state={isOpen:this.config.autoOpen,messages:[],isConnected:!1,isTyping:!1,agentName:"Support Agent",guestId:null,conversationId:null,unreadCount:0,socket:null},this.init()},[{key:"init",value:function(){this.createWidget(),this.attachEventListeners(),this.config.autoOpen&&this.openChat()}},{key:"getUserData",value:function(){return this.config.userData?{name:this.config.userData.name||"Guest User",email:this.config.userData.email||null,phone:this.config.userData.phone||null,userId:this.config.userData.userId||null}:{name:localStorage.getItem("chatGuestName")||"Guest User",email:localStorage.getItem("chatGuestEmail")||null,phone:localStorage.getItem("chatGuestPhone")||null,userId:localStorage.getItem("chatUserId")||null}}},{key:"createWidget",value:function(){var t=document.createElement("div");t.id="chat-crm-widget-root",t.className="crm-widget-container",t.style.zIndex=this.config.zIndex,t.innerHTML=this.getWidgetHTML(),document.body.appendChild(t)}},{key:"getWidgetHTML",value:function(){var t=this.getPositionClass();return'\n <button id="crm-chat-button" class="crm-chat-button '.concat(t,'" style="background-color: ').concat(this.config.primaryColor,'">\n <svg class="crm-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />\n </svg>\n <span id="crm-badge" class="crm-badge" style="display: none;">0</span>\n </button>\n\n <div id="crm-chat-window" class="crm-chat-window ').concat(t,'" style="display: none;">\n <div class="crm-header" style="background-color: ').concat(this.config.primaryColor,'">\n <div class="crm-header-content">\n <div class="crm-avatar">πŸ’¬</div>\n <div>\n <h3 class="crm-title">').concat(this.config.companyName,'</h3>\n <div class="crm-status">\n <div id="crm-status-dot" class="crm-status-dot crm-offline"></div>\n <span id="crm-status-text">Connecting...</span>\n </div>\n </div>\n </div>\n <button id="crm-close-btn" class="crm-close-btn">\n <svg class="crm-icon-sm" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />\n </svg>\n </button>\n </div>\n\n <div id="crm-messages" class="crm-messages">\n <div class="crm-welcome-message">\n <p>').concat(this.config.welcomeMessage,'</p>\n </div>\n </div>\n\n <div class="crm-input-container">\n <div class="crm-input-wrapper">\n <textarea \n id="crm-input" \n class="crm-input" \n placeholder="Type your message..." \n rows="1"\n disabled\n ></textarea>\n <button id="crm-send-btn" class="crm-send-btn" style="background-color: ').concat(this.config.primaryColor,'" disabled>\n <svg class="crm-icon-sm" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />\n </svg>\n </button>\n </div>\n <p class="crm-input-hint">Press Enter to send β€’ Shift+Enter for new line</p>\n </div>\n </div>\n ')}},{key:"getPositionClass",value:function(){var t={"bottom-right":"crm-bottom-6 crm-right-6","bottom-left":"crm-bottom-6 crm-left-6","top-right":"crm-top-6 crm-right-6","top-left":"crm-top-6 crm-left-6"};return t[this.config.position]||t["bottom-right"]}},{key:"attachEventListeners",value:function(){var t=this;document.getElementById("crm-chat-button").addEventListener("click",function(){return t.openChat()}),document.getElementById("crm-close-btn").addEventListener("click",function(){return t.closeChat()}),document.getElementById("crm-send-btn").addEventListener("click",function(){return t.sendMessage()}),document.getElementById("crm-input").addEventListener("keypress",function(e){"Enter"!==e.key||e.shiftKey||(e.preventDefault(),t.sendMessage())})}},{key:"openChat",value:(i=e(o().m(function t(){return o().w(function(t){for(;;)switch(t.n){case 0:if(this.state.isOpen=!0,this.state.unreadCount=0,document.getElementById("crm-chat-window").style.display="flex",document.getElementById("crm-badge").style.display="none",this.state.socket){t.n=1;break}return t.n=1,this.initializeChat();case 1:return t.a(2)}},t,this)})),function(){return i.apply(this,arguments)})},{key:"closeChat",value:function(){this.state.isOpen=!1,document.getElementById("crm-chat-window").style.display="none"}},{key:"initializeChat",value:(s=e(o().m(function t(){var e,n,s,i;return o().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,e=this.getUserData(),t.n=1,fetch("".concat(this.config.apiUrl,"/api/v1/webhook/guest-conversation"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:this.config.apiKey,guestName:e.name,guestEmail:e.email,guestPhone:e.phone,customUserId:e.userId})});case 1:return n=t.v,t.n=2,n.json();case 2:(s=t.v).status&&(this.state.guestId=s.data.guestId,this.state.conversationId=s.data.conversationId,localStorage.setItem("chatGuestId",this.state.guestId),localStorage.setItem("chatConversationId",this.state.conversationId),this.connectSocket()),t.n=4;break;case 3:t.p=3,i=t.v,console.error("❌ Chat initialization error:",i),alert("Failed to connect to chat. Please try again.");case 4:return t.a(2)}},t,this,[[0,3]])})),function(){return s.apply(this,arguments)})},{key:"connectSocket",value:function(){var t=this;this.state.socket=Rt(this.config.apiUrl,{query:{guestId:this.state.guestId,conversationId:this.state.conversationId,apiKey:this.config.apiKey},transports:["websocket","polling"]}),this.state.socket.on("connect",function(){t.state.isConnected=!0,t.updateConnectionStatus(!0),document.getElementById("crm-input").disabled=!1,document.getElementById("crm-send-btn").disabled=!1}),this.state.socket.on("disconnect",function(){t.state.isConnected=!1,t.updateConnectionStatus(!1)}),this.state.socket.on("new-message",function(e){t.addMessage(r(r({},e),{},{sender:"agent",timestamp:new Date})),!t.state.isOpen&&t.config.showNotifications&&(t.state.unreadCount++,t.updateBadge(),t.config.playSound&&t.playNotificationSound())}),this.state.socket.on("agent-typing",function(e){t.state.agentName=e.agentName||"Support Agent",t.showTypingIndicator()})}},{key:"updateConnectionStatus",value:function(t){var e=document.getElementById("crm-status-dot"),n=document.getElementById("crm-status-text");t?(e.classList.remove("crm-offline"),e.classList.add("crm-online"),n.textContent="Online"):(e.classList.remove("crm-online"),e.classList.add("crm-offline"),n.textContent="Connecting...")}},{key:"updateBadge",value:function(){var t=document.getElementById("crm-badge");this.state.unreadCount>0?(t.textContent=this.state.unreadCount,t.style.display="flex"):t.style.display="none"}},{key:"addMessage",value:function(t){this.state.messages.push(t);var e=document.getElementById("crm-messages"),n=document.createElement("div");n.className="crm-message crm-message-".concat(t.sender);var s="guest"===t.sender?'style="background-color: '.concat(this.config.primaryColor,'"'):"";n.innerHTML='\n <div class="crm-message-bubble" '.concat(s,">\n ").concat("agent"===t.sender?'<p class="crm-agent-name">'.concat(this.state.agentName,"</p>"):"",'\n <p class="crm-message-text">').concat(this.escapeHtml(t.message),'</p>\n <p class="crm-message-time">').concat(this.formatTime(t.timestamp),"</p>\n </div>\n "),e.appendChild(n),e.scrollTop=e.scrollHeight}},{key:"sendMessage",value:(t=e(o().m(function t(){var e,n,s,i;return o().w(function(t){for(;;)switch(t.p=t.n){case 0:if(e=document.getElementById("crm-input"),(n=e.value.trim())&&this.state.isConnected){t.n=1;break}return t.a(2);case 1:return s={guestId:this.state.guestId,conversationId:this.state.conversationId,message:n,timestamp:new Date},t.p=2,this.addMessage(r(r({},s),{},{sender:"guest"})),e.value="",this.state.socket.emit("send-message",s),t.n=3,fetch("".concat(this.config.apiUrl,"/api/v1/webhook/send-message"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:this.config.apiKey,guestId:this.state.guestId,conversationId:this.state.conversationId,message:n})});case 3:t.n=5;break;case 4:t.p=4,i=t.v,console.error("❌ Send message error:",i),alert("Failed to send message. Please try again.");case 5:return t.a(2)}},t,this,[[2,4]])})),function(){return t.apply(this,arguments)})},{key:"showTypingIndicator",value:function(){var t=this;this.state.isTyping=!0,setTimeout(function(){t.state.isTyping=!1},3e3)}},{key:"playNotificationSound",value:function(){try{var t=new(window.AudioContext||window.webkitAudioContext),e=t.createOscillator(),n=t.createGain();e.connect(n),n.connect(t.destination),e.frequency.value=800,e.type="sine",n.gain.value=.1,e.start(),setTimeout(function(){return e.stop()},200)}catch(t){console.log("Sound playback not available")}}},{key:"formatTime",value:function(t){return new Date(t).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}},{key:"escapeHtml",value:function(t){var e=document.createElement("div");return e.textContent=t,e.innerHTML}}]);var t,s,i}();window.ChatCRMWidget={init:function(t){return new s(t)}}}()}();
3
+ var t,e,n="function"==typeof Symbol?Symbol:{},s=n.iterator||"@@iterator",i=n.toStringTag||"@@toStringTag";function r(n,s,i,r){var o=s&&s.prototype instanceof h?s:h,u=Object.create(o.prototype);return a(u,"_invoke",function(n,s,i){var r,o,a,h=0,u=i||[],p=!1,l={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,n){return r=e,o=0,a=t,l.n=n,c}};function d(n,s){for(o=n,a=s,e=0;!p&&h&&!i&&e<u.length;e++){var i,r=u[e],d=l.p,f=r[2];n>3?(i=f===s)&&(a=r[(o=r[4])?5:(o=3,3)],r[4]=r[5]=t):r[0]<=d&&((i=n<2&&d<r[1])?(o=0,l.v=s,l.n=r[1]):d<f&&(i=n<3||r[0]>s||s>f)&&(r[4]=n,r[5]=s,l.n=f,o=0))}if(i||n>1)return c;throw p=!0,s}return function(i,u,f){if(h>1)throw TypeError("Generator is already running");for(p&&1===u&&d(u,f),o=u,a=f;(e=o<2?t:a)||!p;){r||(o?o<3?(o>1&&(l.n=-1),d(o,a)):l.n=a:l.v=a);try{if(h=2,r){if(o||(i="next"),e=r[i]){if(!(e=e.call(r,a)))throw TypeError("iterator result is not an object");if(!e.done)return e;a=e.value,o<2&&(o=0)}else 1===o&&(e=r.return)&&e.call(r),o<2&&(a=TypeError("The iterator does not provide a '"+i+"' method"),o=1);r=t}else if((e=(p=l.n<0)?a:n.call(s,l))!==c)break}catch(e){r=t,o=1,a=e}finally{h=1}}return{value:e,done:p}}}(n,i,r),!0),u}var c={};function h(){}function u(){}function p(){}e=Object.getPrototypeOf;var l=[][s]?e(e([][s]())):(a(e={},s,function(){return this}),e),d=p.prototype=h.prototype=Object.create(l);function f(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,p):(t.__proto__=p,a(t,i,"GeneratorFunction")),t.prototype=Object.create(d),t}return u.prototype=p,a(d,"constructor",p),a(p,"constructor",u),u.displayName="GeneratorFunction",a(p,i,"GeneratorFunction"),a(d),a(d,i,"Generator"),a(d,s,function(){return this}),a(d,"toString",function(){return"[object Generator]"}),(o=function(){return{w:r,m:f}})()}function a(t,e,n,s){var i=Object.defineProperty;try{i({},"",{})}catch(t){i=0}a=function(t,e,n,s){function r(e,n){a(t,e,function(t){return this._invoke(e,n,t)})}e?i?i(t,e,{value:n,enumerable:!s,configurable:!s,writable:!s}):t[e]=n:(r("next",0),r("throw",1),r("return",2))},a(t,e,n,s)}function c(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var s=n.call(t,e);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}const h=Object.create(null);h.open="0",h.close="1",h.ping="2",h.pong="3",h.message="4",h.upgrade="5",h.noop="6";const u=Object.create(null);Object.keys(h).forEach(t=>{u[h[t]]=t});const p={type:"error",data:"parser error"},l="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),d="function"==typeof ArrayBuffer,f=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,m=({type:t,data:e},n,s)=>l&&e instanceof Blob?n?s(e):g(e,s):d&&(e instanceof ArrayBuffer||f(e))?n?s(e):g(new Blob([e]),s):s(h[t]+(e||"")),g=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function y(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let v;const b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",w="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)w[b.charCodeAt(t)]=t;const _="function"==typeof ArrayBuffer,k=(t,e)=>{if("string"!=typeof t)return{type:"message",data:C(t,e)};const n=t.charAt(0);if("b"===n)return{type:"message",data:E(t.substring(1),e)};return u[n]?t.length>1?{type:u[n],data:t.substring(1)}:{type:u[n]}:p},E=(t,e)=>{if(_){const n=(t=>{let e,n,s,i,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),u=new Uint8Array(h);for(e=0;e<a;e+=4)n=w[t.charCodeAt(e)],s=w[t.charCodeAt(e+1)],i=w[t.charCodeAt(e+2)],r=w[t.charCodeAt(e+3)],u[c++]=n<<2|s>>4,u[c++]=(15&s)<<4|i>>2,u[c++]=(3&i)<<6|63&r;return h})(t);return C(n,e)}return{base64:!0,data:t}},C=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,O=String.fromCharCode(30);function T(){return new TransformStream({transform(t,e){!function(t,e){l&&t.data instanceof Blob?t.data.arrayBuffer().then(y).then(e):d&&(t.data instanceof ArrayBuffer||f(t.data))?e(y(t.data)):m(t,!1,t=>{v||(v=new TextEncoder),e(v.encode(t))})}(t,n=>{const s=n.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,s)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(s))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),e.enqueue(n)})}})}let S;function x(t){return t.reduce((t,e)=>t+e.length,0)}function A(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)n[i]=t[0][s++],s===t[0].length&&(t.shift(),s=0);return t.length&&s<t[0].length&&(t[0]=t[0].slice(s)),n}function B(t){if(t)return function(t){for(var e in B.prototype)t[e]=B.prototype[e];return t}(t)}B.prototype.on=B.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},B.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},B.prototype.off=B.prototype.removeListener=B.prototype.removeAllListeners=B.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,s=this._callbacks["$"+t];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<s.length;i++)if((n=s[i])===e||n.fn===e){s.splice(i,1);break}return 0===s.length&&delete this._callbacks["$"+t],this},B.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(n){s=0;for(var i=(n=n.slice(0)).length;s<i;++s)n[s].apply(this,e)}return this},B.prototype.emitReserved=B.prototype.emit,B.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},B.prototype.hasListeners=function(t){return!!this.listeners(t).length};const I="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),R="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function N(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const L=R.setTimeout,P=R.clearTimeout;function j(t,e){e.useNativeTimers?(t.setTimeoutFn=L.bind(R),t.clearTimeoutFn=P.bind(R)):(t.setTimeoutFn=R.setTimeout.bind(R),t.clearTimeoutFn=R.clearTimeout.bind(R))}function q(t){return"string"==typeof t?function(t){let e=0,n=0;for(let s=0,i=t.length;s<i;s++)e=t.charCodeAt(s),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(s++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))}function D(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class M extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class U extends B{constructor(t){super(),this.writable=!1,j(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new M(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=k(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}}class F extends U{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const n=t.split(O),s=[];for(let t=0;t<n.length;t++){const i=k(n[t],e);if(s.push(i),"error"===i.type)break}return s})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const n=t.length,s=new Array(n);let i=0;t.forEach((t,r)=>{m(t,!1,t=>{s[r]=t,++i===n&&e(s.join(O))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=D()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let H=!1;try{H="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const K=H;function z(){}class V extends F{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class W extends B{constructor(t,e,n){super(),this.createRequest=t,j(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=N(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=W.requestsCount++,W.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=z,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete W.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(W.requestsCount=0,W.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",G);else if("function"==typeof addEventListener){addEventListener("onpagehide"in R?"pagehide":"unload",G,!1)}function G(){for(let t in W.requests)W.requests.hasOwnProperty(t)&&W.requests[t].abort()}const Y=function(){const t=J({xdomain:!1});return t&&null!==t.responseType}();function J(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||K))return new XMLHttpRequest}catch(t){}if(!e)try{return new(R[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const $="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Q extends U{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=$?{}:N(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],s=e===t.length-1;m(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}s&&I(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=D()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const X=R.WebSocket||R.MozWebSocket;const Z={websocket:class extends Q{createSocket(t,e,n){return $?new X(t,e,n):e?new X(t,e):new X(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends U{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=function(t,e){S||(S=new TextDecoder);const n=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,a){for(n.push(o);;){if(0===s){if(x(n)<1)break;const t=A(n,1);r=!(128&~t[0]),i=127&t[0],s=i<126?3:126===i?1:2}else if(1===s){if(x(n)<2)break;const t=A(n,2);i=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),s=3}else if(2===s){if(x(n)<8)break;const t=A(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),r=e.getUint32(0);if(r>Math.pow(2,21)-1){a.enqueue(p);break}i=r*Math.pow(2,32)+e.getUint32(4),s=3}else{if(x(n)<i)break;const t=A(n,i);a.enqueue(k(r?t:S.decode(t),e)),s=0}if(0===i||i>t){a.enqueue(p);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),s=T();s.readable.pipeTo(t.writable),this._writer=s.writable.getWriter();const i=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),i())}).catch(t=>{})};i();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],s=e===t.length-1;this._writer.write(n).then(()=>{s&&I(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends V{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Y&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new W(J,this.uri(),t)}}},tt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,et=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function nt(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),s=t.indexOf("]");-1!=n&&-1!=s&&(t=t.substring(0,n)+t.substring(n,s).replace(/:/g,";")+t.substring(s,t.length));let i=tt.exec(t||""),r={},o=14;for(;o--;)r[et[o]]=i[o]||"";return-1!=n&&-1!=s&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const n=/\/{2,9}/g,s=e.replace(n,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1);"/"==e.slice(-1)&&s.splice(s.length-1,1);return s}(0,r.path),r.queryKey=function(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,s){e&&(n[e]=s)}),n}(0,r.query),r}const st="function"==typeof addEventListener&&"function"==typeof removeEventListener,it=[];st&&addEventListener("offline",()=>{it.forEach(t=>t())},!1);class rt extends B{constructor(t,e){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const n=nt(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=nt(e.host).host);j(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},n=t.split("&");for(let t=0,s=n.length;t<s;t++){let s=n[t].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}(this.opts.query)),st&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},it.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&rt.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",rt.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const n=this.writeBuffer[e].data;if(n&&(t+=q(n)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,I(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,s){if("function"==typeof e&&(s=e,e=void 0),"function"==typeof n&&(s=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(rt.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),st&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=it.indexOf(this._offlineEventListener);-1!==t&&it.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}rt.protocol=4;class ot extends rt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;rt.priorWebsocketSuccess=!1;const s=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;rt.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function i(){n||(n=!0,h(),e.close(),e=null)}const r=t=>{const n=new Error("probe error: "+t);n.transport=e.name,i(),this.emitReserved("upgradeError",n)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",s),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",s),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let at=class extends ot{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>Z[t]).filter(t=>!!t)),super(t,n)}};const ct="function"==typeof ArrayBuffer,ht=Object.prototype.toString,ut="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ht.call(Blob),pt="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ht.call(File);function lt(t){return ct&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||ut&&t instanceof Blob||pt&&t instanceof File}function dt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(dt(t[e]))return!0;return!1}if(lt(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return dt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&dt(t[e]))return!0;return!1}function ft(t){const e=[],n=t.data,s=t;return s.data=mt(n,e),s.attachments=e.length,{packet:s,buffers:e}}function mt(t,e){if(!t)return t;if(lt(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=mt(t[s],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=mt(t[s],e));return n}return t}function gt(t,e){return t.data=yt(t.data,e),delete t.attachments,t}function yt(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=yt(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=yt(t[n],e));return t}const vt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var bt;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(bt||(bt={}));function wt(t){return"[object Object]"===Object.prototype.toString.call(t)}class _t extends B{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===bt.BINARY_EVENT;n||e.type===bt.BINARY_ACK?(e.type=n?bt.EVENT:bt.ACK,this.reconstructor=new kt(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!lt(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===bt[n.type])throw new Error("unknown packet type "+n.type);if(n.type===bt.BINARY_EVENT||n.type===bt.BINARY_ACK){const s=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(s,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===t.charAt(e+1)){const s=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}n.nsp=t.substring(s,e)}else n.nsp="/";const s=t.charAt(e+1);if(""!==s&&Number(s)==s){const s=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(s,e+1))}if(t.charAt(++e)){const s=this.tryParse(t.substr(e));if(!_t.isPayloadValid(n.type,s))throw new Error("invalid payload");n.data=s}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case bt.CONNECT:return wt(e);case bt.DISCONNECT:return void 0===e;case bt.CONNECT_ERROR:return"string"==typeof e||wt(e);case bt.EVENT:case bt.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===vt.indexOf(e[0]));case bt.ACK:case bt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class kt{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=gt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Et=Object.freeze({__proto__:null,Decoder:_t,Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==bt.EVENT&&t.type!==bt.ACK||!dt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===bt.EVENT?bt.BINARY_EVENT:bt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==bt.BINARY_EVENT&&t.type!==bt.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=ft(t),n=this.encodeAsString(e.packet),s=e.buffers;return s.unshift(n),s}},get PacketType(){return bt},protocol:5});function Ct(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const Ot=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Tt extends B{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Ct(t,"open",this.onopen.bind(this)),Ct(t,"packet",this.onpacket.bind(this)),Ct(t,"error",this.onerror.bind(this)),Ct(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,s,i;if(Ot.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const r={type:bt.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),r.id=t}const o=null===(s=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===s?void 0:s.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(t,e){var n;const s=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===s)return void(this.acks[t]=e);const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},s),r=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((n,s)=>{const i=(t,e)=>t?s(t):n(e);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...s)=>{if(n!==this._queue[0])return;return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...s)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:bt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case bt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case bt.EVENT:case bt.BINARY_EVENT:this.onevent(t);break;case bt.ACK:case bt.BINARY_ACK:this.onack(t);break;case bt.DISCONNECT:this.ondisconnect();break;case bt.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...s){n||(n=!0,e.packet({type:bt.ACK,id:t,data:s}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:bt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function St(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}St.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},St.prototype.reset=function(){this.attempts=0},St.prototype.setMin=function(t){this.ms=t},St.prototype.setMax=function(t){this.max=t},St.prototype.setJitter=function(t){this.jitter=t};class xt extends B{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,j(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new St({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const s=e.parser||Et;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new at(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const s=Ct(e,"open",function(){n.onopen(),t&&t()}),i=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=Ct(e,"error",i);if(!1!==this._timeout){const t=this._timeout,n=this.setTimeoutFn(()=>{s(),i(new Error("timeout")),e.close()},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(s),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ct(t,"ping",this.onping.bind(this)),Ct(t,"data",this.ondata.bind(this)),Ct(t,"error",this.onerror.bind(this)),Ct(t,"close",this.onclose.bind(this)),Ct(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){I(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Tt(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e){if(this.nsps[t].active)return}this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const At={};function Bt(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let s=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),s=nt(t)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+e,s.href=s.protocol+"://"+i+(n&&n.port===s.port?"":":"+s.port),s}(t,(e=e||{}).path||"/socket.io"),s=n.source,i=n.id,r=n.path,o=At[i]&&r in At[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new xt(s,e):(At[i]||(At[i]=new xt(s,e)),a=At[i]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(Bt,{Manager:xt,Socket:Tt,io:Bt,connect:Bt}),function(){var t=document.createElement("style");t.textContent="/* Styles will be injected by Rollup */",document.head.appendChild(t);var s=function(){return n(function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.config={apiKey:e.apiKey||"",apiUrl:e.apiUrl||"https://chat-crm-backend-7mzo.onrender.com",primaryColor:e.primaryColor||"#4F46E5",position:e.position||"bottom-right",userData:e.userData||null,welcomeMessage:e.welcomeMessage||"πŸ‘‹ Welcome! How can we help you today?",companyName:e.companyName||"Support",autoOpen:e.autoOpen||!1,showNotifications:!1!==e.showNotifications,playSound:e.playSound||!1,theme:e.theme||"light",zIndex:e.zIndex||9999},this.state={isOpen:this.config.autoOpen,messages:[],isConnected:!1,isTyping:!1,agentName:"Support Agent",guestId:null,conversationId:null,unreadCount:0,socket:null,widgetSocket:null,petitionId:null,snapshotRequest:null,isCapturing:!1},this.init()},[{key:"init",value:function(){this.createWidget(),this.attachEventListeners(),this.config.autoOpen&&this.openChat()}},{key:"getUserData",value:function(){return this.config.userData?{name:this.config.userData.name||"Guest User",email:this.config.userData.email||null,phone:this.config.userData.phone||null,userId:this.config.userData.userId||null}:{name:localStorage.getItem("chatGuestName")||"Guest User",email:localStorage.getItem("chatGuestEmail")||null,phone:localStorage.getItem("chatGuestPhone")||null,userId:localStorage.getItem("chatUserId")||null}}},{key:"createWidget",value:function(){var t=document.createElement("div");t.id="chat-crm-widget-root",t.className="crm-widget-container",t.style.zIndex=this.config.zIndex,t.innerHTML=this.getWidgetHTML(),document.body.appendChild(t)}},{key:"getWidgetHTML",value:function(){var t=this.getPositionClass();return'\n <button id="crm-chat-button" class="crm-chat-button '.concat(t,'" style="background-color: ').concat(this.config.primaryColor,'">\n <svg class="crm-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />\n </svg>\n <span id="crm-badge" class="crm-badge" style="display: none;">0</span>\n </button>\n\n <div id="crm-chat-window" class="crm-chat-window ').concat(t,'" style="display: none;">\n <div class="crm-header" style="background-color: ').concat(this.config.primaryColor,'">\n <div class="crm-header-content">\n <div class="crm-avatar">πŸ’¬</div>\n <div>\n <h3 class="crm-title">').concat(this.config.companyName,'</h3>\n <div class="crm-status">\n <div id="crm-status-dot" class="crm-status-dot crm-offline"></div>\n <span id="crm-status-text">Connecting...</span>\n </div>\n </div>\n </div>\n <button id="crm-close-btn" class="crm-close-btn">\n <svg class="crm-icon-sm" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />\n </svg>\n </button>\n </div>\n\n <div id="crm-messages" class="crm-messages">\n <div class="crm-welcome-message">\n <p>').concat(this.config.welcomeMessage,'</p>\n </div>\n </div>\n\n <div class="crm-input-container">\n <div class="crm-input-wrapper">\n <textarea \n id="crm-input" \n class="crm-input" \n placeholder="Type your message..." \n rows="1"\n disabled\n ></textarea>\n <button id="crm-send-btn" class="crm-send-btn" style="background-color: ').concat(this.config.primaryColor,'" disabled>\n <svg class="crm-icon-sm" fill="none" stroke="currentColor" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />\n </svg>\n </button>\n </div>\n <p class="crm-input-hint">Press Enter to send β€’ Shift+Enter for new line</p>\n </div>\n </div>\n ')}},{key:"getPositionClass",value:function(){var t={"bottom-right":"crm-bottom-6 crm-right-6","bottom-left":"crm-bottom-6 crm-left-6","top-right":"crm-top-6 crm-right-6","top-left":"crm-top-6 crm-left-6"};return t[this.config.position]||t["bottom-right"]}},{key:"attachEventListeners",value:function(){var t=this;document.getElementById("crm-chat-button").addEventListener("click",function(){return t.toggleChat()}),document.getElementById("crm-close-btn").addEventListener("click",function(){return t.closeChat()}),document.getElementById("crm-send-btn").addEventListener("click",function(){return t.sendMessage()}),document.getElementById("crm-input").addEventListener("keypress",function(e){"Enter"!==e.key||e.shiftKey||(e.preventDefault(),t.sendMessage())})}},{key:"toggleChat",value:function(){this.state.isOpen?this.closeChat():this.openChat()}},{key:"updateButtonIcon",value:function(){var t=document.getElementById("crm-chat-button");if(t){var e=t.querySelector("svg");e&&(this.state.isOpen?e.innerHTML='<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />':e.innerHTML='<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />')}}},{key:"openChat",value:(a=e(o().m(function t(){return o().w(function(t){for(;;)switch(t.n){case 0:if(this.state.isOpen=!0,this.state.unreadCount=0,document.getElementById("crm-chat-window").style.display="flex",document.getElementById("crm-badge").style.display="none",this.updateButtonIcon(),this.state.socket){t.n=1;break}return t.n=1,this.initializeChat();case 1:return t.a(2)}},t,this)})),function(){return a.apply(this,arguments)})},{key:"closeChat",value:function(){this.state.isOpen=!1,document.getElementById("crm-chat-window").style.display="none",this.updateButtonIcon()}},{key:"initializeChat",value:(i=e(o().m(function t(){var e,n,s,i;return o().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,e=this.getUserData(),t.n=1,fetch("".concat(this.config.apiUrl,"/api/v1/webhook/guest-conversation"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:this.config.apiKey,guestName:e.name,guestEmail:e.email,guestPhone:e.phone,customUserId:e.userId})});case 1:return n=t.v,t.n=2,n.json();case 2:(s=t.v).status&&(this.state.guestId=s.data.guestId,this.state.conversationId=s.data.conversationId,this.state.petitionId=s.data.petitionId||s.petitionId,localStorage.setItem("chatGuestId",this.state.guestId),localStorage.setItem("chatConversationId",this.state.conversationId),this.state.petitionId&&localStorage.setItem("chatPetitionId",this.state.petitionId),this.connectSocket(),this.connectWidgetNamespace()),t.n=4;break;case 3:t.p=3,i=t.v,console.error("❌ Chat initialization error:",i),alert("Failed to connect to chat. Please try again.");case 4:return t.a(2)}},t,this,[[0,3]])})),function(){return i.apply(this,arguments)})},{key:"connectSocket",value:function(){var t=this;this.state.socket=Bt(this.config.apiUrl,{query:{guestId:this.state.guestId,conversationId:this.state.conversationId,apiKey:this.config.apiKey},transports:["websocket","polling"]}),this.state.socket.on("connect",function(){t.state.isConnected=!0,t.updateConnectionStatus(!0),document.getElementById("crm-input").disabled=!1,document.getElementById("crm-send-btn").disabled=!1}),this.state.socket.on("disconnect",function(){t.state.isConnected=!1,t.updateConnectionStatus(!1)}),this.state.socket.on("new-message",function(e){t.addMessage(r(r({},e),{},{sender:"agent",timestamp:new Date})),!t.state.isOpen&&t.config.showNotifications&&(t.state.unreadCount++,t.updateBadge(),t.config.playSound&&t.playNotificationSound())}),this.state.socket.on("agent-typing",function(e){t.state.agentName=e.agentName||"Support Agent",t.showTypingIndicator()})}},{key:"connectWidgetNamespace",value:function(){var t=this;try{if(!this.state.conversationId)return;var e=this.state.petitionId||localStorage.getItem("chatPetitionId");this.state.widgetSocket=Bt("".concat(this.config.apiUrl,"/widget"),{query:{conversationId:this.state.conversationId,petitionId:e,apiKey:this.config.apiKey},transports:["websocket","polling"]}),this.state.widgetSocket.on("connect",function(){}),this.state.widgetSocket.on("disconnect",function(){}),this.state.widgetSocket.on("request-camera-snapshot",function(e){try{var n,s=localStorage.getItem("chatPetitionId");if(null!=e&&e.petitionId&&s&&e.petitionId===s)t.state.snapshotRequest={requesterName:e.requesterName||(null===(n=e.requester)||void 0===n?void 0:n.name)||"Agent",at:Date.now()},t.showSnapshotModal()}catch(t){}})}catch(t){console.error("Widget namespace connect error:",t)}}},{key:"updateConnectionStatus",value:function(t){var e=document.getElementById("crm-status-dot"),n=document.getElementById("crm-status-text");t?(e.classList.remove("crm-offline"),e.classList.add("crm-online"),n.textContent="Online"):(e.classList.remove("crm-online"),e.classList.add("crm-offline"),n.textContent="Connecting...")}},{key:"updateBadge",value:function(){var t=document.getElementById("crm-badge");this.state.unreadCount>0?(t.textContent=this.state.unreadCount,t.style.display="flex"):t.style.display="none"}},{key:"addMessage",value:function(t){this.state.messages.push(t);var e=document.getElementById("crm-messages"),n=document.createElement("div");n.className="crm-message crm-message-".concat(t.sender);var s="guest"===t.sender?'style="background-color: '.concat(this.config.primaryColor,'"'):"",i=String(t.message||""),r=i.match(/https?:[^\s]+\.(?:png|jpg|jpeg|gif|webp)/i),o='<p class="crm-message-text">'.concat(this.escapeHtml(i),"</p>");if(r){var a=r[0],c=i.replace(a,"").trim(),h=c?'<p class="crm-message-text" style="opacity:0.85">'.concat(this.escapeHtml(c),"</p>"):"";o="".concat(h,'<img src="').concat(this.escapeHtml(a),'" alt="snapshot" style="max-width:240px;max-height:180px;border-radius:8px;border:1px solid #E5E7EB;display:block" />')}n.innerHTML='\n <div class="crm-message-bubble" '.concat(s,">\n ").concat("agent"===t.sender?'<p class="crm-agent-name">'.concat(this.state.agentName,"</p>"):"","\n ").concat(o,'\n <p class="crm-message-time">').concat(this.formatTime(t.timestamp),"</p>\n </div>\n "),e.appendChild(n),e.scrollTop=e.scrollHeight}},{key:"showSnapshotModal",value:function(){var t,n=this,s=document.getElementById("crm-snapshot-modal");s&&s.remove();var i=document.createElement("div");i.id="crm-snapshot-modal",i.style.position="fixed",i.style.inset="0",i.style.background="rgba(0,0,0,0.45)",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.padding="16px",i.style.zIndex="10000";var r=document.createElement("div");r.style.width="360px",r.style.maxWidth="100%",r.style.background="#fff",r.style.color="#111827",r.style.border="1px solid #E5E7EB",r.style.borderRadius="12px",r.innerHTML='\n <div style="padding:16px">\n <h3 style="margin:0;font-size:18px;font-weight:600">Camera access requested</h3>\n <p style="margin-top:8px;font-size:14px;opacity:0.9">'.concat(this.escapeHtml((null===(t=this.state.snapshotRequest)||void 0===t?void 0:t.requesterName)||"Agent"),' is requesting a photo from your camera. Do you allow?</p>\n </div>\n <div style="display:flex;gap:8px;justify-content:flex-end;border-top:1px solid #E5E7EB;padding:12px">\n <button id="crm-snapshot-cancel" class="crm-close-btn">Cancel</button>\n <button id="crm-snapshot-allow" class="crm-send-btn" style="background-color:').concat(this.config.primaryColor,'">').concat(this.state.isCapturing?"Capturing…":"Allow & Capture","</button>\n </div>\n "),i.appendChild(r),document.body.appendChild(i),document.getElementById("crm-snapshot-cancel").addEventListener("click",function(){i.remove(),n.state.snapshotRequest=null}),document.getElementById("crm-snapshot-allow").addEventListener("click",e(o().m(function t(){var e;return o().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,n.captureAndUploadSnapshot();case 1:(e=document.getElementById("crm-snapshot-modal"))&&e.remove();case 2:return t.a(2)}},t)})))}},{key:"captureAndUploadSnapshot",value:(s=e(o().m(function t(){var e,n,s,i,r,a,c,h,u,p,l,d,f,m,g,y;return o().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.state.snapshotRequest){t.n=1;break}return t.a(2);case 1:return this.state.isCapturing=!0,t.p=2,t.n=3,navigator.mediaDevices.getUserMedia({video:!0});case 3:return s=t.v,(i=document.createElement("video")).srcObject=s,t.n=4,new Promise(function(t){i.onloadedmetadata=t,i.play().then(t).catch(t)});case 4:return r=document.createElement("canvas"),a=i.videoWidth||640,c=i.videoHeight||480,r.width=a,r.height=c,r.getContext("2d").drawImage(i,0,0,a,c),s.getTracks().forEach(function(t){return t.stop()}),t.n=5,new Promise(function(t){return r.toBlob(t,"image/png")});case 5:if(h=t.v){t.n=6;break}throw new Error("Failed to capture");case 6:return u=this.state.petitionId||localStorage.getItem("chatPetitionId"),p=new FormData,l="snapshot-".concat(u,"-").concat(Date.now(),".png"),p.append("screenshot",h,l),p.append("petitionId",u),p.append("apiKey",this.config.apiKey),p.append("metadata",JSON.stringify({source:"widget",requesterName:null===(e=this.state.snapshotRequest)||void 0===e?void 0:e.requesterName})),t.n=7,fetch("".concat(this.config.apiUrl,"/api/v1/webhook/upload-snapshot"),{method:"POST",body:p});case 7:return d=t.v,t.n=8,d.json();case 8:if(f=t.v,!(m=null==f||null===(n=f.data)||void 0===n?void 0:n.imageUrl)){t.n=9;break}return g=new Date,this.addMessage({message:"πŸ“Έ Screenshot: ".concat(m),sender:"guest",timestamp:g}),t.n=9,fetch("".concat(this.config.apiUrl,"/api/v1/webhook/send-message"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:this.config.apiKey,petitionId:u,message:"πŸ“Έ Screenshot: ".concat(m),senderName:"Guest User"})});case 9:t.n=11;break;case 10:t.p=10,y=t.v,console.error("Snapshot capture error:",y),alert("Camera permission denied or capture failed.");case 11:return t.p=11,this.state.isCapturing=!1,this.state.snapshotRequest=null,t.f(11);case 12:return t.a(2)}},t,this,[[2,10,11,12]])})),function(){return s.apply(this,arguments)})},{key:"sendMessage",value:(t=e(o().m(function t(){var e,n,s,i;return o().w(function(t){for(;;)switch(t.p=t.n){case 0:if(e=document.getElementById("crm-input"),(n=e.value.trim())&&this.state.isConnected){t.n=1;break}return t.a(2);case 1:return s={guestId:this.state.guestId,conversationId:this.state.conversationId,message:n,timestamp:new Date},t.p=2,this.addMessage(r(r({},s),{},{sender:"guest"})),e.value="",this.state.socket.emit("send-message",s),t.n=3,fetch("".concat(this.config.apiUrl,"/api/v1/webhook/send-message"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:this.config.apiKey,guestId:this.state.guestId,conversationId:this.state.conversationId,message:n})});case 3:t.n=5;break;case 4:t.p=4,i=t.v,console.error("❌ Send message error:",i),alert("Failed to send message. Please try again.");case 5:return t.a(2)}},t,this,[[2,4]])})),function(){return t.apply(this,arguments)})},{key:"showTypingIndicator",value:function(){var t=this;this.state.isTyping=!0,setTimeout(function(){t.state.isTyping=!1},3e3)}},{key:"playNotificationSound",value:function(){try{var t=new(window.AudioContext||window.webkitAudioContext),e=t.createOscillator(),n=t.createGain();e.connect(n),n.connect(t.destination),e.frequency.value=800,e.type="sine",n.gain.value=.1,e.start(),setTimeout(function(){return e.stop()},200)}catch(t){console.log("Sound playback not available")}}},{key:"formatTime",value:function(t){return new Date(t).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}},{key:"escapeHtml",value:function(t){var e=document.createElement("div");return e.textContent=t,e.innerHTML}},{key:"setupOutsideClick",value:function(){var t=this,e=function(e){if(t.state.isOpen){var n=document.getElementById("crm-chat-window"),s=document.getElementById("crm-chat-button");n&&!n.contains(e.target)&&s&&!s.contains(e.target)&&t.closeChat()}};document.addEventListener("mousedown",e),document.addEventListener("touchstart",e)}}]);var t,s,i,a}();window.ChatCRMWidget={init:function(t){var e=new s(t);return e.setupOutsideClick(),e}}}()}();
4
4
  //# sourceMappingURL=chat-widget.min.js.map