@onedeskpro/chatbot-core 0.2.0 → 0.2.1
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 +20 -4
- package/dist/index.cjs +18 -37
- package/dist/index.d.cts +15 -2
- package/dist/index.d.ts +15 -2
- package/dist/index.iife.js +14 -33
- package/dist/index.js +229 -238
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -28,7 +28,23 @@ await chatbot.init({
|
|
|
28
28
|
});
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
`init`
|
|
31
|
+
`init` connects to the Onedesk Pro API and adds the widget to the page once the agent can reply. Only `apiKey` is required — use the publishable workspace API key, never a server secret.
|
|
32
|
+
|
|
33
|
+
### When the widget appears
|
|
34
|
+
|
|
35
|
+
Nothing is added to the page straight away. `init` first checks that the Onedesk Pro server is reachable and that the agent is ready to reply, and the launcher appears only once both hold and a returning visitor's identity has been checked:
|
|
36
|
+
|
|
37
|
+
| Situation | `blockReason` | What happens |
|
|
38
|
+
| --- | --- | --- |
|
|
39
|
+
| Ready | `null` | The launcher appears (and the panel opens, with `autoOpen`). |
|
|
40
|
+
| The server cannot be reached, times out, or answers with a 5xx | `server-unavailable` | Stays hidden and checks again after 5, 15, 30 and 60 seconds, then gives up until the next page load. |
|
|
41
|
+
| The agent has no system prompt or no knowledge base | `no-prompt`, `no-collections` | Stays hidden. |
|
|
42
|
+
| The platform's AI models are not configured | `ai-unavailable` | Stays hidden. |
|
|
43
|
+
| The workspace has used its AI token budget | `no-credits` | Stays hidden. |
|
|
44
|
+
| No agent is assigned to the Website channel | `no-agent` | Stays hidden. |
|
|
45
|
+
| The API key is rejected or the site's origin is not allowed | `null`, with `error` set | Stays hidden. |
|
|
46
|
+
|
|
47
|
+
`init` resolves after the first check, and the `ready` event fires once the outcome is settled: when the widget appears, when a configuration problem rules it out, or when the last retry fails. A custom UI built on the state can show `blockReason` to explain why chat is unavailable.
|
|
32
48
|
|
|
33
49
|
### Visitor identification
|
|
34
50
|
|
|
@@ -111,9 +127,9 @@ The IIFE build exposes a `window.OnedeskProChatbot` global:
|
|
|
111
127
|
| --- | --- | --- |
|
|
112
128
|
| `isOpen` | `boolean` | The panel is showing. |
|
|
113
129
|
| `isLoading` | `boolean` | A send, identify, or human request is in flight. |
|
|
114
|
-
| `isReady` | `boolean` |
|
|
130
|
+
| `isReady` | `boolean` | The server answered and the agent can reply; the widget is on the page. |
|
|
115
131
|
| `needsIdentify` | `boolean` | The visitor has not identified yet. |
|
|
116
|
-
| `blockReason` | `ChatbotBlockReason` | Why the agent cannot answer, or `null`. |
|
|
132
|
+
| `blockReason` | `ChatbotBlockReason` | Why the agent cannot answer, or `null`. See [When the widget appears](#when-the-widget-appears). |
|
|
117
133
|
| `messages` | `ChatMessage[]` | The conversation so far. `message.type` is `'human'`, `'ai'`, or `'agent'`. |
|
|
118
134
|
| `visitorToken` | `string \| null` | The identified visitor's token. |
|
|
119
135
|
| `visitorName` | `string \| null` | The identified visitor's name. |
|
|
@@ -126,7 +142,7 @@ The IIFE build exposes a `window.OnedeskProChatbot` global:
|
|
|
126
142
|
| --- | --- | --- |
|
|
127
143
|
| `message` | `ChatMessage` | A message is added — visitor, AI, and human agent alike. |
|
|
128
144
|
| `state-change` | `ChatbotState` | Any state changes, including `isLoading` while a reply is in flight. |
|
|
129
|
-
| `ready` | — |
|
|
145
|
+
| `ready` | — | The readiness check settled: the widget appeared, or it will not (see `blockReason` and `error`). |
|
|
130
146
|
| `open` / `close` | — | The panel is shown or hidden. |
|
|
131
147
|
| `ticket-status` | `TicketStatusData` | The mode changed — on restore, after a send, or pushed live. |
|
|
132
148
|
| `human-requested` | — | `requestHuman()` succeeded. |
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},n=3e4;function r(e){return typeof e==`object`&&!!e&&typeof e.message==`string`}function i(e){return e instanceof Error&&`apiError`in e&&`status`in e&&typeof e.status==`number`&&r(e.apiError)}var a=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,``),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??3e4}fail(e,t,n,r){let i={statusCode:t,message:e,code:n,timestamp:new Date().toISOString(),path:r};throw Object.assign(Error(e),{apiError:i,status:t})}async request(e,t,n,i,a){let o=new URL(`${this.baseUrl}${t}`);if(i)for(let[e,t]of Object.entries(i))o.searchParams.set(e,t);let s={"Content-Type":`application/json`,"X-API-Key":this.apiKey,...a},c=new AbortController,l=setTimeout(()=>c.abort(),this.timeoutMs),u;try{u=await fetch(o.toString(),{method:e,headers:s,signal:c.signal,...n===void 0?{}:{body:JSON.stringify(n)}})}catch(e){c.signal.aborted&&this.fail(`Request timed out after ${this.timeoutMs}ms.`,0,`TIMEOUT`,t),this.fail(e instanceof Error?e.message:`Network request failed.`,0,`NETWORK_ERROR`,t)}finally{clearTimeout(l)}let d=await u.text(),f=null;if(d)try{f=JSON.parse(d)}catch{f=null}if(!u.ok){if(r(f))throw Object.assign(Error(f.message),{apiError:f,status:u.status});this.fail(`Request failed with status ${u.status} ${u.statusText}`.trim(),u.status,`HTTP_ERROR`,t)}return f===null&&this.fail(`The server returned an empty or malformed response.`,u.status,`BAD_RESPONSE`,t),f.data}async identify(e){return this.request(`POST`,`/sdk/identify`,e)}async verifyVisitor(e){return this.request(`GET`,`/sdk/visitor`,void 0,void 0,{"X-Visitor-Token":e})}async sendMessage(e){return this.request(`POST`,`/sdk/chat`,e)}async fetchConfig(){return this.request(`GET`,`/sdk/config`)}async requestHuman(e){return this.request(`POST`,`/sdk/human-request`,{visitorToken:e})}async fetchTicketStatus(e){return this.request(`GET`,`/sdk/ticket-status`,void 0,void 0,{"X-Visitor-Token":e})}},o=`https://api.onedeskpro.com`,s=class{constructor(){this._listeners={}}on(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),()=>this.off(e,t)}off(e,t){let n=this._listeners[e];n&&(this._listeners[e]=n.filter(e=>e!==t))}emit(e,...t){let n=this._listeners[e];if(n)for(let e of n)e(...t)}removeAllListeners(){for(let e of Object.keys(this._listeners))delete this._listeners[e]}},c=Object.create(null);c.open=`0`,c.close=`1`,c.ping=`2`,c.pong=`3`,c.message=`4`,c.upgrade=`5`,c.noop=`6`;var l=Object.create(null);Object.keys(c).forEach(e=>{l[c[e]]=e});var u={type:`error`,data:`parser error`},d=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,f=typeof ArrayBuffer==`function`,p=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,m=({type:e,data:t},n,r)=>d&&t instanceof Blob?n?r(t):ee(t,r):f&&(t instanceof ArrayBuffer||p(t))?n?r(t):ee(new Blob([t]),r):r(c[e]+(t||``)),ee=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function te(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var h;function ne(e,t){if(d&&e.data instanceof Blob)return e.data.arrayBuffer().then(te).then(t);if(f&&(e.data instanceof ArrayBuffer||p(e.data)))return t(te(e.data));m(e,!1,e=>{h||=new TextEncoder,t(h.encode(e))})}var re=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,g=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)g[re.charCodeAt(e)]=e;var ie=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=g[e.charCodeAt(r)],o=g[e.charCodeAt(r+1)],s=g[e.charCodeAt(r+2)],c=g[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},ae=typeof ArrayBuffer==`function`,_=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:v(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:oe(e.substring(1),t)}:l[n]?e.length>1?{type:l[n],data:e.substring(1)}:{type:l[n]}:u},oe=(e,t)=>ae?v(ie(e),t):{base64:!0,data:e},v=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},y=``,se=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{m(e,!1,e=>{r[a]=e,++i===n&&t(r.join(y))})})},ce=(e,t)=>{let n=e.split(y),r=[];for(let e=0;e<n.length;e++){let i=_(n[e],t);if(r.push(i),i.type===`error`)break}return r};function le(){return new TransformStream({transform(e,t){ne(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var ue;function b(e){return e.reduce((e,t)=>e+t.length,0)}function x(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function de(e,t){ue||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(b(n)<1)break;let e=x(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(b(n)<2)break;let e=x(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(b(n)<8)break;let e=x(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(u);break}i=a*2**32+t.getUint32(4),r=3}else{if(b(n)<i)break;let e=x(n,i);s.enqueue(_(a?e:ue.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(u);break}}}})}function S(e){if(e)return fe(e)}function fe(e){for(var t in S.prototype)e[t]=S.prototype[t];return e}S.prototype.on=S.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},S.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},S.prototype.off=S.prototype.removeListener=S.prototype.removeAllListeners=S.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},S.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},S.prototype.emitReserved=S.prototype.emit,S.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},S.prototype.hasListeners=function(e){return!!this.listeners(e).length};var C=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),w=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),pe=`arraybuffer`;function me(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var he=w.setTimeout,ge=w.clearTimeout;function T(e,t){t.useNativeTimers?(e.setTimeoutFn=he.bind(w),e.clearTimeoutFn=ge.bind(w)):(e.setTimeoutFn=w.setTimeout.bind(w),e.clearTimeoutFn=w.clearTimeout.bind(w))}var _e=1.33;function ve(e){return typeof e==`string`?ye(e):Math.ceil((e.byteLength||e.size)*_e)}function ye(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function be(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function xe(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Se(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var Ce=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},E=class extends S{constructor(e){super(),this.writable=!1,T(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new Ce(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=_(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=xe(e);return t.length?`?`+t:``}},we=class extends E{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){ce(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,se(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=be()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},Te=!1;try{Te=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Ee=Te;function De(){}var Oe=class extends we{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},D=class e extends S{constructor(e,t,n){super(),this.createRequest=e,T(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=me(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(this._xhr!==void 0&&this._xhr!==null){if(this._xhr.onreadystatechange=De,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(D.requestsCount=0,D.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,O);else if(typeof addEventListener==`function`){let e=`onpagehide`in w?`pagehide`:`unload`;addEventListener(e,O,!1)}}function O(){for(let e in D.requests)D.requests.hasOwnProperty(e)&&D.requests[e].abort()}var ke=(function(){let e=je({xdomain:!1});return e&&e.responseType!==null})(),Ae=class extends Oe{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=ke&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new D(je,this.uri(),e)}};function je(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Ee))return new XMLHttpRequest}catch{}if(!t)try{return new w[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var Me=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,Ne=class extends E{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Me?{}:me(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(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;m(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&C(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=be()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},k=w.WebSocket||w.MozWebSocket,Pe={websocket:class extends Ne{createSocket(e,t,n){return Me?new k(e,t,n):t?new k(e,t):new k(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends E{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=de(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=le();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&C(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:Ae},Fe=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Ie=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function A(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=Fe.exec(e||``),a={},o=14;for(;o--;)a[Ie[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=Le(a,a.path),a.queryKey=Re(a,a.query),a}function Le(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function Re(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var j=typeof addEventListener==`function`&&typeof removeEventListener==`function`,M=[];j&&addEventListener(`offline`,()=>{M.forEach(e=>e())},!1);var N=class e extends S{constructor(e,t){if(super(),this.binaryType=pe,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=A(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=A(t.host).host);T(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),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},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=Se(this.opts.query)),j&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},M.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data)}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=ve(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,C(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),j&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=M.indexOf(this._offlineEventListener);e!==-1&&M.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};N.protocol=4;var ze=class extends N{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;N.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n){if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;N.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},Be=class extends ze{constructor(e,t={}){let n=typeof e==`object`,r=n?{...e}:{...t};(!r.transports||r.transports&&typeof r.transports[0]==`string`)&&(r.transports=(r.transports||[`polling`,`websocket`,`webtransport`]).map(e=>Pe[e]).filter(e=>!!e)),super(n?r:e,r)}};Be.protocol;function Ve(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=A(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var He=typeof ArrayBuffer==`function`,Ue=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,P=Object.prototype.toString,We=typeof Blob==`function`||typeof Blob<`u`&&P.call(Blob)===`[object BlobConstructor]`,Ge=typeof File==`function`||typeof File<`u`&&P.call(File)===`[object FileConstructor]`;function F(e){return He&&(e instanceof ArrayBuffer||Ue(e))||We&&e instanceof Blob||Ge&&e instanceof File}function I(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(I(e[t]))return!0;return!1}if(F(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return I(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&I(e[t]))return!0;return!1}function Ke(e){let t=[],n=e.data,r=e;return r.data=L(n,t),r.attachments=t.length,{packet:r,buffers:t}}function L(e,t,n){if(!e)return e;if(F(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=L(e[r],t);return n}if(typeof e==`object`&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON==`function`&&!n)return L(e.toJSON(),t,!0);let r={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=L(e[n],t));return r}return e}function qe(e,t){return e.data=R(e.data,t),delete e.attachments,e}function R(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=R(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=R(e[n],t));return e}var Je=t({Decoder:()=>Xe,Encoder:()=>Ye,PacketType:()=>B,isPacketValid:()=>tt,protocol:()=>5}),z=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],B;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(B||={});var Ye=class{constructor(e){this.replacer=e}encode(e){return(e.type===B.EVENT||e.type===B.ACK)&&I(e)?this.encodeAsBinary({type:e.type===B.EVENT?B.BINARY_EVENT:B.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===B.BINARY_EVENT||e.type===B.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Ke(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Xe=class e extends S{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===B.BINARY_EVENT;n||t.type===B.BINARY_ACK?(t.type=n?B.EVENT:B.ACK,this.reconstructor=new Ze(t)):super.emitReserved(`decoded`,t)}else if(F(e)||e.base64){if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`)}else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(B[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===B.BINARY_EVENT||r.type===B.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!V(a)||a<1)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&t.charAt(n)!==`,`&&n!==t.length;);r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case B.CONNECT:return H(t);case B.DISCONNECT:return t===void 0;case B.CONNECT_ERROR:return typeof t==`string`||H(t);case B.EVENT:case B.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&z.indexOf(t[0])===-1);case B.ACK:case B.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Ze=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=qe(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Qe(e){return typeof e==`string`}var V=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function $e(e){return e===void 0||V(e)}function H(e){return Object.prototype.toString.call(e)===`[object Object]`}function et(e,t){switch(e){case B.CONNECT:return t===void 0||H(t);case B.DISCONNECT:return t===void 0;case B.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&z.indexOf(t[0])===-1);case B.ACK:return Array.isArray(t);case B.CONNECT_ERROR:return typeof t==`string`||H(t);default:return!1}}function tt(e){return Qe(e.nsp)&&$e(e.id)&&et(e.type,e.data)}function U(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var nt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),rt=class extends S{constructor(e,t,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=e,this.nsp=t,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;let e=this.io;this.subs=[U(e,`open`,this.onopen.bind(this)),U(e,`packet`,this.onpacket.bind(this)),U(e,`error`,this.onerror.bind(this)),U(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(nt.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:B.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];(!t.pending||e)&&(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:B.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case B.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,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 B.EVENT:case B.BINARY_EVENT:this.onevent(e);break;case B.ACK:case B.BINARY_ACK:this.onack(e);break;case B.DISCONNECT:this.ondisconnect();break;case B.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t)}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:B.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:B.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function W(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}W.prototype.duration=function(){var e=this.ms*this.factor**+this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},W.prototype.reset=function(){this.attempts=0},W.prototype.setMin=function(e){this.ms=e},W.prototype.setMax=function(e){this.max=e},W.prototype.setJitter=function(e){this.jitter=e};var G=class extends S{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,T(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new W({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||Je;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new Be(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=U(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=U(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(U(e,`ping`,this.onping.bind(this)),U(e,`data`,this.ondata.bind(this)),U(e,`error`,this.onerror.bind(this)),U(e,`close`,this.onclose.bind(this)),U(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){C(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new rt(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},K={};function q(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=Ve(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=K[i]&&a in K[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new G(r,t):(K[i]||(K[i]=new G(r,t)),c=K[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(q,{Manager:G,Socket:rt,io:q,connect:q});function it(e){let t=e.replace(/\/$/,``);try{return`${new URL(t).origin}/sdk`}catch{return`${t}/sdk`}}var at=class{constructor(){this.socket=null}get connected(){return this.socket?.connected??!1}connect(e){this.disconnect();let t=it(e.baseUrl);this.socket=q(t,{auth:{apiKey:e.apiKey,visitorToken:e.visitorToken},transports:[`websocket`,`polling`],autoConnect:!0,reconnection:!0});let n=!1;this.socket.on(`connect`,()=>{n?e.onReconnect?.():n=!0}),this.socket.on(`ticket:status`,t=>{e.onTicketStatus?.(t)}),this.socket.on(`message:receive`,t=>{e.onMessageReceive?.(t)}),this.socket.on(`connect_error`,t=>{e.onConnectError?.(t)})}disconnect(){this.socket&&=(this.socket.removeAllListeners(),this.socket.disconnect(),null)}},J=`onedeskpro_visitor_token`;function ot(e){try{return typeof window<`u`?window.localStorage.getItem(e):null}catch{return null}}function st(e,t){try{typeof window<`u`&&window.localStorage.setItem(e,t)}catch{}}function ct(e){try{typeof window<`u`&&window.localStorage.removeItem(e)}catch{}}var lt=class{constructor(){this.token=null,this.storageKey=J}setScope(e){this.storageKey=e?.trim()?`${J}:${e.trim()}`:J,this.token=ot(this.storageKey)}get(){return this.token??ot(this.storageKey)}set(e){this.token=e,st(this.storageKey,e)}clear(){this.token=null,ct(this.storageKey)}},Y=[{iso:`BD`,name:`Bangladesh`,dial:`880`,flag:`🇧🇩`},{iso:`US`,name:`United States`,dial:`1`,flag:`🇺🇸`},{iso:`GB`,name:`United Kingdom`,dial:`44`,flag:`🇬🇧`},{iso:`IN`,name:`India`,dial:`91`,flag:`🇮🇳`},{iso:`PK`,name:`Pakistan`,dial:`92`,flag:`🇵🇰`},{iso:`AE`,name:`United Arab Emirates`,dial:`971`,flag:`🇦🇪`},{iso:`SA`,name:`Saudi Arabia`,dial:`966`,flag:`🇸🇦`},{iso:`CA`,name:`Canada`,dial:`1`,flag:`🇨🇦`},{iso:`AU`,name:`Australia`,dial:`61`,flag:`🇦🇺`},{iso:`DE`,name:`Germany`,dial:`49`,flag:`🇩🇪`},{iso:`FR`,name:`France`,dial:`33`,flag:`🇫🇷`},{iso:`IT`,name:`Italy`,dial:`39`,flag:`🇮🇹`},{iso:`ES`,name:`Spain`,dial:`34`,flag:`🇪🇸`},{iso:`NL`,name:`Netherlands`,dial:`31`,flag:`🇳🇱`},{iso:`SE`,name:`Sweden`,dial:`46`,flag:`🇸🇪`},{iso:`NO`,name:`Norway`,dial:`47`,flag:`🇳🇴`},{iso:`DK`,name:`Denmark`,dial:`45`,flag:`🇩🇰`},{iso:`FI`,name:`Finland`,dial:`358`,flag:`🇫🇮`},{iso:`IE`,name:`Ireland`,dial:`353`,flag:`🇮🇪`},{iso:`CH`,name:`Switzerland`,dial:`41`,flag:`🇨🇭`},{iso:`AT`,name:`Austria`,dial:`43`,flag:`🇦🇹`},{iso:`BE`,name:`Belgium`,dial:`32`,flag:`🇧🇪`},{iso:`PT`,name:`Portugal`,dial:`351`,flag:`🇵🇹`},{iso:`PL`,name:`Poland`,dial:`48`,flag:`🇵🇱`},{iso:`CZ`,name:`Czechia`,dial:`420`,flag:`🇨🇿`},{iso:`RO`,name:`Romania`,dial:`40`,flag:`🇷🇴`},{iso:`HU`,name:`Hungary`,dial:`36`,flag:`🇭🇺`},{iso:`GR`,name:`Greece`,dial:`30`,flag:`🇬🇷`},{iso:`TR`,name:`Turkey`,dial:`90`,flag:`🇹🇷`},{iso:`RU`,name:`Russia`,dial:`7`,flag:`🇷🇺`},{iso:`UA`,name:`Ukraine`,dial:`380`,flag:`🇺🇦`},{iso:`CN`,name:`China`,dial:`86`,flag:`🇨🇳`},{iso:`JP`,name:`Japan`,dial:`81`,flag:`🇯🇵`},{iso:`KR`,name:`South Korea`,dial:`82`,flag:`🇰🇷`},{iso:`SG`,name:`Singapore`,dial:`65`,flag:`🇸🇬`},{iso:`MY`,name:`Malaysia`,dial:`60`,flag:`🇲🇾`},{iso:`ID`,name:`Indonesia`,dial:`62`,flag:`🇮🇩`},{iso:`TH`,name:`Thailand`,dial:`66`,flag:`🇹🇭`},{iso:`VN`,name:`Vietnam`,dial:`84`,flag:`🇻🇳`},{iso:`PH`,name:`Philippines`,dial:`63`,flag:`🇵🇭`},{iso:`HK`,name:`Hong Kong`,dial:`852`,flag:`🇭🇰`},{iso:`TW`,name:`Taiwan`,dial:`886`,flag:`🇹🇼`},{iso:`NZ`,name:`New Zealand`,dial:`64`,flag:`🇳🇿`},{iso:`ZA`,name:`South Africa`,dial:`27`,flag:`🇿🇦`},{iso:`NG`,name:`Nigeria`,dial:`234`,flag:`🇳🇬`},{iso:`KE`,name:`Kenya`,dial:`254`,flag:`🇰🇪`},{iso:`EG`,name:`Egypt`,dial:`20`,flag:`🇪🇬`},{iso:`MA`,name:`Morocco`,dial:`212`,flag:`🇲🇦`},{iso:`BR`,name:`Brazil`,dial:`55`,flag:`🇧🇷`},{iso:`MX`,name:`Mexico`,dial:`52`,flag:`🇲🇽`},{iso:`AR`,name:`Argentina`,dial:`54`,flag:`🇦🇷`},{iso:`CL`,name:`Chile`,dial:`56`,flag:`🇨🇱`},{iso:`CO`,name:`Colombia`,dial:`57`,flag:`🇨🇴`},{iso:`PE`,name:`Peru`,dial:`51`,flag:`🇵🇪`},{iso:`IL`,name:`Israel`,dial:`972`,flag:`🇮🇱`},{iso:`QA`,name:`Qatar`,dial:`974`,flag:`🇶🇦`},{iso:`KW`,name:`Kuwait`,dial:`965`,flag:`🇰🇼`},{iso:`BH`,name:`Bahrain`,dial:`973`,flag:`🇧🇭`},{iso:`OM`,name:`Oman`,dial:`968`,flag:`🇴🇲`},{iso:`LK`,name:`Sri Lanka`,dial:`94`,flag:`🇱🇰`},{iso:`NP`,name:`Nepal`,dial:`977`,flag:`🇳🇵`}],ut=Y.find(e=>e.iso===`BD`)??Y[0];function dt(e,t){let n=t.trim();if(n.startsWith(`+`)){let e=n.replace(/\D/g,``);return e?`+${e}`:``}let r=n.replace(/\D/g,``);return!r||(r=r.replace(/^0+/,``),!r)?``:`+${e}${r}`}function ft(e,t){let n=`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},n=3e4;function r(e){return typeof e==`object`&&!!e&&typeof e.message==`string`}function i(e){return e instanceof Error&&`apiError`in e&&`status`in e&&typeof e.status==`number`&&r(e.apiError)}var a=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,``),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??3e4}fail(e,t,n,r){let i={statusCode:t,message:e,code:n,timestamp:new Date().toISOString(),path:r};throw Object.assign(Error(e),{apiError:i,status:t})}async request(e,t,n,i,a){let o=new URL(`${this.baseUrl}${t}`);if(i)for(let[e,t]of Object.entries(i))o.searchParams.set(e,t);let s={"Content-Type":`application/json`,"X-API-Key":this.apiKey,...a},c=new AbortController,l=setTimeout(()=>c.abort(),this.timeoutMs),u;try{u=await fetch(o.toString(),{method:e,headers:s,signal:c.signal,...n===void 0?{}:{body:JSON.stringify(n)}})}catch(e){c.signal.aborted&&this.fail(`Request timed out after ${this.timeoutMs}ms.`,0,`TIMEOUT`,t),this.fail(e instanceof Error?e.message:`Network request failed.`,0,`NETWORK_ERROR`,t)}finally{clearTimeout(l)}let d=await u.text(),f=null;if(d)try{f=JSON.parse(d)}catch{f=null}if(!u.ok){if(r(f))throw Object.assign(Error(f.message),{apiError:f,status:u.status});this.fail(`Request failed with status ${u.status} ${u.statusText}`.trim(),u.status,`HTTP_ERROR`,t)}return f===null&&this.fail(`The server returned an empty or malformed response.`,u.status,`BAD_RESPONSE`,t),f.data}async identify(e){return this.request(`POST`,`/sdk/identify`,e)}async verifyVisitor(e){return this.request(`GET`,`/sdk/visitor`,void 0,void 0,{"X-Visitor-Token":e})}async sendMessage(e){return this.request(`POST`,`/sdk/chat`,e)}async fetchConfig(){return this.request(`GET`,`/sdk/config`)}async requestHuman(e){return this.request(`POST`,`/sdk/human-request`,{visitorToken:e})}async fetchTicketStatus(e){return this.request(`GET`,`/sdk/ticket-status`,void 0,void 0,{"X-Visitor-Token":e})}},o=`https://api.onedeskpro.com`,s=class{constructor(){this._listeners={}}on(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),()=>this.off(e,t)}off(e,t){let n=this._listeners[e];n&&(this._listeners[e]=n.filter(e=>e!==t))}emit(e,...t){let n=this._listeners[e];if(n)for(let e of n)e(...t)}removeAllListeners(){for(let e of Object.keys(this._listeners))delete this._listeners[e]}},c=Object.create(null);c.open=`0`,c.close=`1`,c.ping=`2`,c.pong=`3`,c.message=`4`,c.upgrade=`5`,c.noop=`6`;var l=Object.create(null);Object.keys(c).forEach(e=>{l[c[e]]=e});var u={type:`error`,data:`parser error`},d=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,f=typeof ArrayBuffer==`function`,p=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,m=({type:e,data:t},n,r)=>d&&t instanceof Blob?n?r(t):ee(t,r):f&&(t instanceof ArrayBuffer||p(t))?n?r(t):ee(new Blob([t]),r):r(c[e]+(t||``)),ee=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function te(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var h;function ne(e,t){if(d&&e.data instanceof Blob)return e.data.arrayBuffer().then(te).then(t);if(f&&(e.data instanceof ArrayBuffer||p(e.data)))return t(te(e.data));m(e,!1,e=>{h||=new TextEncoder,t(h.encode(e))})}var re=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,g=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)g[re.charCodeAt(e)]=e;var ie=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=g[e.charCodeAt(r)],o=g[e.charCodeAt(r+1)],s=g[e.charCodeAt(r+2)],c=g[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},ae=typeof ArrayBuffer==`function`,_=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:v(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:oe(e.substring(1),t)}:l[n]?e.length>1?{type:l[n],data:e.substring(1)}:{type:l[n]}:u},oe=(e,t)=>ae?v(ie(e),t):{base64:!0,data:e},v=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},y=``,se=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{m(e,!1,e=>{r[a]=e,++i===n&&t(r.join(y))})})},ce=(e,t)=>{let n=e.split(y),r=[];for(let e=0;e<n.length;e++){let i=_(n[e],t);if(r.push(i),i.type===`error`)break}return r};function le(){return new TransformStream({transform(e,t){ne(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var ue;function b(e){return e.reduce((e,t)=>e+t.length,0)}function x(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function de(e,t){ue||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(b(n)<1)break;let e=x(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(b(n)<2)break;let e=x(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(b(n)<8)break;let e=x(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(u);break}i=a*2**32+t.getUint32(4),r=3}else{if(b(n)<i)break;let e=x(n,i);s.enqueue(_(a?e:ue.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(u);break}}}})}function S(e){if(e)return fe(e)}function fe(e){for(var t in S.prototype)e[t]=S.prototype[t];return e}S.prototype.on=S.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},S.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},S.prototype.off=S.prototype.removeListener=S.prototype.removeAllListeners=S.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},S.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},S.prototype.emitReserved=S.prototype.emit,S.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},S.prototype.hasListeners=function(e){return!!this.listeners(e).length};var C=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),w=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),pe=`arraybuffer`;function me(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var he=w.setTimeout,ge=w.clearTimeout;function T(e,t){t.useNativeTimers?(e.setTimeoutFn=he.bind(w),e.clearTimeoutFn=ge.bind(w)):(e.setTimeoutFn=w.setTimeout.bind(w),e.clearTimeoutFn=w.clearTimeout.bind(w))}var _e=1.33;function ve(e){return typeof e==`string`?ye(e):Math.ceil((e.byteLength||e.size)*_e)}function ye(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function be(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function xe(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Se(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var Ce=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},E=class extends S{constructor(e){super(),this.writable=!1,T(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new Ce(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=_(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=xe(e);return t.length?`?`+t:``}},we=class extends E{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){ce(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,se(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=be()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},Te=!1;try{Te=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Ee=Te;function De(){}var Oe=class extends we{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},D=class e extends S{constructor(e,t,n){super(),this.createRequest=e,T(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=me(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(this._xhr!==void 0&&this._xhr!==null){if(this._xhr.onreadystatechange=De,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(D.requestsCount=0,D.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,ke);else if(typeof addEventListener==`function`){let e=`onpagehide`in w?`pagehide`:`unload`;addEventListener(e,ke,!1)}}function ke(){for(let e in D.requests)D.requests.hasOwnProperty(e)&&D.requests[e].abort()}var Ae=(function(){let e=Me({xdomain:!1});return e&&e.responseType!==null})(),je=class extends Oe{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Ae&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new D(Me,this.uri(),e)}};function Me(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Ee))return new XMLHttpRequest}catch{}if(!t)try{return new w[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var Ne=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,Pe=class extends E{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Ne?{}:me(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(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;m(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&C(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=be()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},O=w.WebSocket||w.MozWebSocket,Fe={websocket:class extends Pe{createSocket(e,t,n){return Ne?new O(e,t,n):t?new O(e,t):new O(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends E{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=de(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=le();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&C(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:je},Ie=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Le=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function k(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=Ie.exec(e||``),a={},o=14;for(;o--;)a[Le[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=Re(a,a.path),a.queryKey=ze(a,a.query),a}function Re(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function ze(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var A=typeof addEventListener==`function`&&typeof removeEventListener==`function`,j=[];A&&addEventListener(`offline`,()=>{j.forEach(e=>e())},!1);var M=class e extends S{constructor(e,t){if(super(),this.binaryType=pe,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=k(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=k(t.host).host);T(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),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},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=Se(this.opts.query)),A&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},j.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data)}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=ve(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,C(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),A&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=j.indexOf(this._offlineEventListener);e!==-1&&j.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};M.protocol=4;var Be=class extends M{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;M.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n){if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;M.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},N=class extends Be{constructor(e,t={}){let n=typeof e==`object`,r=n?{...e}:{...t};(!r.transports||r.transports&&typeof r.transports[0]==`string`)&&(r.transports=(r.transports||[`polling`,`websocket`,`webtransport`]).map(e=>Fe[e]).filter(e=>!!e)),super(n?r:e,r)}};N.protocol;function Ve(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=k(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var He=typeof ArrayBuffer==`function`,Ue=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,P=Object.prototype.toString,We=typeof Blob==`function`||typeof Blob<`u`&&P.call(Blob)===`[object BlobConstructor]`,Ge=typeof File==`function`||typeof File<`u`&&P.call(File)===`[object FileConstructor]`;function F(e){return He&&(e instanceof ArrayBuffer||Ue(e))||We&&e instanceof Blob||Ge&&e instanceof File}function I(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(I(e[t]))return!0;return!1}if(F(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return I(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&I(e[t]))return!0;return!1}function Ke(e){let t=[],n=e.data,r=e;return r.data=L(n,t),r.attachments=t.length,{packet:r,buffers:t}}function L(e,t,n){if(!e)return e;if(F(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=L(e[r],t);return n}if(typeof e==`object`&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON==`function`&&!n)return L(e.toJSON(),t,!0);let r={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=L(e[n],t));return r}return e}function qe(e,t){return e.data=R(e.data,t),delete e.attachments,e}function R(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=R(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=R(e[n],t));return e}var Je=t({Decoder:()=>Xe,Encoder:()=>Ye,PacketType:()=>B,isPacketValid:()=>nt,protocol:()=>5}),z=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],B;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(B||={});var Ye=class{constructor(e){this.replacer=e}encode(e){return(e.type===B.EVENT||e.type===B.ACK)&&I(e)?this.encodeAsBinary({type:e.type===B.EVENT?B.BINARY_EVENT:B.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===B.BINARY_EVENT||e.type===B.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Ke(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Xe=class e extends S{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===B.BINARY_EVENT;n||t.type===B.BINARY_ACK?(t.type=n?B.EVENT:B.ACK,this.reconstructor=new Ze(t)):super.emitReserved(`decoded`,t)}else if(F(e)||e.base64){if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`)}else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(B[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===B.BINARY_EVENT||r.type===B.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!$e(a)||a<1)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&t.charAt(n)!==`,`&&n!==t.length;);r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case B.CONNECT:return V(t);case B.DISCONNECT:return t===void 0;case B.CONNECT_ERROR:return typeof t==`string`||V(t);case B.EVENT:case B.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&z.indexOf(t[0])===-1);case B.ACK:case B.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Ze=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=qe(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Qe(e){return typeof e==`string`}var $e=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function et(e){return e===void 0||$e(e)}function V(e){return Object.prototype.toString.call(e)===`[object Object]`}function tt(e,t){switch(e){case B.CONNECT:return t===void 0||V(t);case B.DISCONNECT:return t===void 0;case B.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&z.indexOf(t[0])===-1);case B.ACK:return Array.isArray(t);case B.CONNECT_ERROR:return typeof t==`string`||V(t);default:return!1}}function nt(e){return Qe(e.nsp)&&et(e.id)&&tt(e.type,e.data)}function H(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var rt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),it=class extends S{constructor(e,t,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=e,this.nsp=t,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;let e=this.io;this.subs=[H(e,`open`,this.onopen.bind(this)),H(e,`packet`,this.onpacket.bind(this)),H(e,`error`,this.onerror.bind(this)),H(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(rt.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:B.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];(!t.pending||e)&&(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:B.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case B.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,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 B.EVENT:case B.BINARY_EVENT:this.onevent(e);break;case B.ACK:case B.BINARY_ACK:this.onack(e);break;case B.DISCONNECT:this.ondisconnect();break;case B.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t)}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:B.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:B.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function U(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}U.prototype.duration=function(){var e=this.ms*this.factor**+this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},U.prototype.reset=function(){this.attempts=0},U.prototype.setMin=function(e){this.ms=e},U.prototype.setMax=function(e){this.max=e},U.prototype.setJitter=function(e){this.jitter=e};var W=class extends S{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,T(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new U({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||Je;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new N(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=H(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=H(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(H(e,`ping`,this.onping.bind(this)),H(e,`data`,this.ondata.bind(this)),H(e,`error`,this.onerror.bind(this)),H(e,`close`,this.onclose.bind(this)),H(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){C(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new it(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},G={};function K(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=Ve(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=G[i]&&a in G[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new W(r,t):(G[i]||(G[i]=new W(r,t)),c=G[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(K,{Manager:W,Socket:it,io:K,connect:K});function at(e){let t=e.replace(/\/$/,``);try{return`${new URL(t).origin}/sdk`}catch{return`${t}/sdk`}}var ot=class{constructor(){this.socket=null}get connected(){return this.socket?.connected??!1}connect(e){this.disconnect();let t=at(e.baseUrl);this.socket=K(t,{auth:{apiKey:e.apiKey,visitorToken:e.visitorToken},transports:[`websocket`,`polling`],autoConnect:!0,reconnection:!0});let n=!1;this.socket.on(`connect`,()=>{n?e.onReconnect?.():n=!0}),this.socket.on(`ticket:status`,t=>{e.onTicketStatus?.(t)}),this.socket.on(`message:receive`,t=>{e.onMessageReceive?.(t)}),this.socket.on(`connect_error`,t=>{e.onConnectError?.(t)})}disconnect(){this.socket&&=(this.socket.removeAllListeners(),this.socket.disconnect(),null)}},q=`onedeskpro_visitor_token`;function st(e){try{return typeof window<`u`?window.localStorage.getItem(e):null}catch{return null}}function ct(e,t){try{typeof window<`u`&&window.localStorage.setItem(e,t)}catch{}}function lt(e){try{typeof window<`u`&&window.localStorage.removeItem(e)}catch{}}var ut=class{constructor(){this.token=null,this.storageKey=q}setScope(e){this.storageKey=e?.trim()?`${q}:${e.trim()}`:q,this.token=st(this.storageKey)}get(){return this.token??st(this.storageKey)}set(e){this.token=e,ct(this.storageKey,e)}clear(){this.token=null,lt(this.storageKey)}},J=[{iso:`BD`,name:`Bangladesh`,dial:`880`,flag:`🇧🇩`},{iso:`US`,name:`United States`,dial:`1`,flag:`🇺🇸`},{iso:`GB`,name:`United Kingdom`,dial:`44`,flag:`🇬🇧`},{iso:`IN`,name:`India`,dial:`91`,flag:`🇮🇳`},{iso:`PK`,name:`Pakistan`,dial:`92`,flag:`🇵🇰`},{iso:`AE`,name:`United Arab Emirates`,dial:`971`,flag:`🇦🇪`},{iso:`SA`,name:`Saudi Arabia`,dial:`966`,flag:`🇸🇦`},{iso:`CA`,name:`Canada`,dial:`1`,flag:`🇨🇦`},{iso:`AU`,name:`Australia`,dial:`61`,flag:`🇦🇺`},{iso:`DE`,name:`Germany`,dial:`49`,flag:`🇩🇪`},{iso:`FR`,name:`France`,dial:`33`,flag:`🇫🇷`},{iso:`IT`,name:`Italy`,dial:`39`,flag:`🇮🇹`},{iso:`ES`,name:`Spain`,dial:`34`,flag:`🇪🇸`},{iso:`NL`,name:`Netherlands`,dial:`31`,flag:`🇳🇱`},{iso:`SE`,name:`Sweden`,dial:`46`,flag:`🇸🇪`},{iso:`NO`,name:`Norway`,dial:`47`,flag:`🇳🇴`},{iso:`DK`,name:`Denmark`,dial:`45`,flag:`🇩🇰`},{iso:`FI`,name:`Finland`,dial:`358`,flag:`🇫🇮`},{iso:`IE`,name:`Ireland`,dial:`353`,flag:`🇮🇪`},{iso:`CH`,name:`Switzerland`,dial:`41`,flag:`🇨🇭`},{iso:`AT`,name:`Austria`,dial:`43`,flag:`🇦🇹`},{iso:`BE`,name:`Belgium`,dial:`32`,flag:`🇧🇪`},{iso:`PT`,name:`Portugal`,dial:`351`,flag:`🇵🇹`},{iso:`PL`,name:`Poland`,dial:`48`,flag:`🇵🇱`},{iso:`CZ`,name:`Czechia`,dial:`420`,flag:`🇨🇿`},{iso:`RO`,name:`Romania`,dial:`40`,flag:`🇷🇴`},{iso:`HU`,name:`Hungary`,dial:`36`,flag:`🇭🇺`},{iso:`GR`,name:`Greece`,dial:`30`,flag:`🇬🇷`},{iso:`TR`,name:`Turkey`,dial:`90`,flag:`🇹🇷`},{iso:`RU`,name:`Russia`,dial:`7`,flag:`🇷🇺`},{iso:`UA`,name:`Ukraine`,dial:`380`,flag:`🇺🇦`},{iso:`CN`,name:`China`,dial:`86`,flag:`🇨🇳`},{iso:`JP`,name:`Japan`,dial:`81`,flag:`🇯🇵`},{iso:`KR`,name:`South Korea`,dial:`82`,flag:`🇰🇷`},{iso:`SG`,name:`Singapore`,dial:`65`,flag:`🇸🇬`},{iso:`MY`,name:`Malaysia`,dial:`60`,flag:`🇲🇾`},{iso:`ID`,name:`Indonesia`,dial:`62`,flag:`🇮🇩`},{iso:`TH`,name:`Thailand`,dial:`66`,flag:`🇹🇭`},{iso:`VN`,name:`Vietnam`,dial:`84`,flag:`🇻🇳`},{iso:`PH`,name:`Philippines`,dial:`63`,flag:`🇵🇭`},{iso:`HK`,name:`Hong Kong`,dial:`852`,flag:`🇭🇰`},{iso:`TW`,name:`Taiwan`,dial:`886`,flag:`🇹🇼`},{iso:`NZ`,name:`New Zealand`,dial:`64`,flag:`🇳🇿`},{iso:`ZA`,name:`South Africa`,dial:`27`,flag:`🇿🇦`},{iso:`NG`,name:`Nigeria`,dial:`234`,flag:`🇳🇬`},{iso:`KE`,name:`Kenya`,dial:`254`,flag:`🇰🇪`},{iso:`EG`,name:`Egypt`,dial:`20`,flag:`🇪🇬`},{iso:`MA`,name:`Morocco`,dial:`212`,flag:`🇲🇦`},{iso:`BR`,name:`Brazil`,dial:`55`,flag:`🇧🇷`},{iso:`MX`,name:`Mexico`,dial:`52`,flag:`🇲🇽`},{iso:`AR`,name:`Argentina`,dial:`54`,flag:`🇦🇷`},{iso:`CL`,name:`Chile`,dial:`56`,flag:`🇨🇱`},{iso:`CO`,name:`Colombia`,dial:`57`,flag:`🇨🇴`},{iso:`PE`,name:`Peru`,dial:`51`,flag:`🇵🇪`},{iso:`IL`,name:`Israel`,dial:`972`,flag:`🇮🇱`},{iso:`QA`,name:`Qatar`,dial:`974`,flag:`🇶🇦`},{iso:`KW`,name:`Kuwait`,dial:`965`,flag:`🇰🇼`},{iso:`BH`,name:`Bahrain`,dial:`973`,flag:`🇧🇭`},{iso:`OM`,name:`Oman`,dial:`968`,flag:`🇴🇲`},{iso:`LK`,name:`Sri Lanka`,dial:`94`,flag:`🇱🇰`},{iso:`NP`,name:`Nepal`,dial:`977`,flag:`🇳🇵`}],dt=J.find(e=>e.iso===`BD`)??J[0];function ft(e,t){let n=t.trim();if(n.startsWith(`+`)){let e=n.replace(/\D/g,``);return e?`+${e}`:``}let r=n.replace(/\D/g,``);return!r||(r=r.replace(/^0+/,``),!r)?``:`+${e}${r}`}function pt(e,t){let n=`
|
|
2
2
|
--ttcb-bg: #ffffff;
|
|
3
3
|
--ttcb-bg-secondary: #f3f4f6;
|
|
4
4
|
--ttcb-text: #111827;
|
|
@@ -209,21 +209,6 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
209
209
|
}
|
|
210
210
|
@keyframes ttcb-spin { to { transform: rotate(360deg); } }
|
|
211
211
|
|
|
212
|
-
.ttcb-blocked {
|
|
213
|
-
display: flex; flex-direction: column; align-items: center;
|
|
214
|
-
justify-content: center; text-align: center;
|
|
215
|
-
padding: 32px 20px; flex: 1;
|
|
216
|
-
}
|
|
217
|
-
.ttcb-blocked-icon {
|
|
218
|
-
width: 44px; height: 44px; border-radius: 50%;
|
|
219
|
-
background: var(--ttcb-bg-secondary);
|
|
220
|
-
display: flex; align-items: center; justify-content: center;
|
|
221
|
-
margin-bottom: 14px;
|
|
222
|
-
}
|
|
223
|
-
.ttcb-blocked-icon svg { width: 20px; height: 20px; fill: var(--ttcb-text-muted); }
|
|
224
|
-
.ttcb-blocked-title { font-size: 14px; font-weight: 600; color: var(--ttcb-text); margin-bottom: 8px; }
|
|
225
|
-
.ttcb-blocked-desc { font-size: 12px; color: var(--ttcb-text-muted); line-height: 1.5; max-width: 220px; }
|
|
226
|
-
|
|
227
212
|
.ttcb-msg { display: flex; gap: 8px; max-width: 100%; }
|
|
228
213
|
.ttcb-msg.human { flex-direction: row-reverse; }
|
|
229
214
|
.ttcb-msg-body { display: flex; flex-direction: column; gap: 3px; max-width: 78%; }
|
|
@@ -503,54 +488,50 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
503
488
|
.ttcb-fab.bottom-right { right: 16px; }
|
|
504
489
|
.ttcb-fab.bottom-left { left: 16px; }
|
|
505
490
|
}
|
|
506
|
-
`}function
|
|
491
|
+
`}function Y(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}function mt(e){let t=[],n=e.replace(/```[\w]*\n?([\s\S]*?)```/g,(e,n)=>{let r=t.length;return t.push(`<pre><code>${Y(n.trim())}</code></pre>`),`\x04${r}\x05`});n=n.replace(/`([^`\n]+)`/g,(e,n)=>{let r=t.length;return t.push(`<code>${Y(n)}</code>`),`\x02${r}\x03`}),n=Y(n);let r=n.split(`
|
|
507
492
|
`),i=[],a=``,o=()=>{a&&=(i.push(`</${a}>`),``)};for(let e of r){let t;(t=e.match(/^### (.+)/))?(o(),i.push(`<h3>${t[1]}</h3>`)):(t=e.match(/^## (.+)/))?(o(),i.push(`<h2>${t[1]}</h2>`)):(t=e.match(/^# (.+)/))?(o(),i.push(`<h1>${t[1]}</h1>`)):(t=e.match(/^[*-] (.+)/))?(a!==`ul`&&(o(),i.push(`<ul>`),a=`ul`),i.push(`<li>${t[1]}</li>`)):(t=e.match(/^\d+\. (.+)/))?(a!==`ol`&&(o(),i.push(`<ol>`),a=`ol`),i.push(`<li>${t[1]}</li>`)):(o(),i.push(e))}return o(),n=i.join(`
|
|
508
|
-
`),n=n.replace(/\*\*(.+?)\*\*/gs,`<strong>$1</strong>`).replace(/__(.+?)__/gs,`<strong>$1</strong>`).replace(/\*(.+?)\*/gs,`<em>$1</em>`).replace(/_(.+?)_/gs,`<em>$1</em>`).replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`),n=n.split(/\n{2,}/).map(e=>{let t=e.trim();return t?/^<(h[1-3]|ul|ol|pre|li)/.test(t)?t:t.split(/(\x04\d+\x05)/g).map(e=>{if(/^\x04\d+\x05$/.test(e))return e;let t=e.trim();return t?`<p>${t.replace(/\n/g,`<br>`)}</p>`:``}).join(``):``}).filter(Boolean).join(``),n=n.replace(/\x04(\d+)\x05/g,(e,n)=>t[+n]??``).replace(/\x02(\d+)\x03/g,(e,n)=>t[+n]??``),n}function
|
|
509
|
-
<path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"/>
|
|
510
|
-
</svg>`}function ht(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
511
|
-
<path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"/>
|
|
512
|
-
</svg>`}function gt(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
493
|
+
`),n=n.replace(/\*\*(.+?)\*\*/gs,`<strong>$1</strong>`).replace(/__(.+?)__/gs,`<strong>$1</strong>`).replace(/\*(.+?)\*/gs,`<em>$1</em>`).replace(/_(.+?)_/gs,`<em>$1</em>`).replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`),n=n.split(/\n{2,}/).map(e=>{let t=e.trim();return t?/^<(h[1-3]|ul|ol|pre|li)/.test(t)?t:t.split(/(\x04\d+\x05)/g).map(e=>{if(/^\x04\d+\x05$/.test(e))return e;let t=e.trim();return t?`<p>${t.replace(/\n/g,`<br>`)}</p>`:``}).join(``):``}).filter(Boolean).join(``),n=n.replace(/\x04(\d+)\x05/g,(e,n)=>t[+n]??``).replace(/\x02(\d+)\x03/g,(e,n)=>t[+n]??``),n}function ht(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
513
494
|
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
|
514
495
|
<line x1="12" y1="8" x2="12" y2="14"/>
|
|
515
496
|
<line x1="9" y1="11" x2="15" y2="11"/>
|
|
516
|
-
</svg>`}function
|
|
497
|
+
</svg>`}function gt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
517
498
|
<path d="M20 2H4C2.9 2 2 2.9 2 4v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/>
|
|
518
|
-
</svg>`}function
|
|
499
|
+
</svg>`}function _t(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
519
500
|
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
|
|
520
|
-
</svg>`}function
|
|
501
|
+
</svg>`}function vt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
521
502
|
<path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
|
|
522
|
-
</svg>`}function
|
|
503
|
+
</svg>`}function X(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
523
504
|
<path d="M20 9V7c0-1.1-.9-2-2-2h-3c0-1.66-1.34-3-3-3S9 3.34 9 5H6c-1.1 0-2 .9-2 2v2c-1.66 0-3 1.34-3 3s1.34 3 3 3v4c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-4c1.66 0 3-1.34 3-3s-1.34-3-3-3zm-2 10H6V7h12v12zm-9-6c-.83 0-1.5-.67-1.5-1.5S8.17 10 9 10s1.5.67 1.5 1.5S9.83 13 9 13zm6 0c-.83 0-1.5-.67-1.5-1.5S14.17 10 15 10s1.5.67 1.5 1.5S15.83 13 15 13z"/>
|
|
524
|
-
</svg>`}function
|
|
505
|
+
</svg>`}function yt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
525
506
|
<path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
|
|
526
|
-
</svg>`}function
|
|
507
|
+
</svg>`}function bt(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
527
508
|
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
|
|
528
509
|
<circle cx="12" cy="7" r="4"/>
|
|
529
|
-
</svg>`}function
|
|
510
|
+
</svg>`}function xt(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
530
511
|
<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
|
|
531
512
|
<polyline points="22,6 12,13 2,6"/>
|
|
532
|
-
</svg>`}function
|
|
513
|
+
</svg>`}function St(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
533
514
|
<polyline points="6 9 12 15 18 9"/>
|
|
534
|
-
</svg>`}function
|
|
515
|
+
</svg>`}function Ct(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
535
516
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
536
517
|
<polyline points="12 5 19 12 12 19"/>
|
|
537
|
-
</svg>`}function
|
|
518
|
+
</svg>`}function wt(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
538
519
|
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
|
|
539
520
|
<polyline points="9 12 11 14 15 10"/>
|
|
540
|
-
</svg>`}function
|
|
521
|
+
</svg>`}function Tt(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
541
522
|
<circle cx="12" cy="12" r="10" fill="currentColor"/>
|
|
542
523
|
<path d="M9 12l2 2 4-4" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
|
|
543
|
-
</svg>`}function
|
|
524
|
+
</svg>`}function Et(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
544
525
|
<path fill="#F59E0B" d="M8 2.5l1.1 2.2 2.4.3-1.7 1.7.4 2.4L8 8l-2.2 1.1.4-2.4L4.5 5l2.4-.3L8 2.5z"/>
|
|
545
526
|
<path fill="#F59E0B" d="M16 3.5l.8 1.6 1.8.2-1.3 1.3.3 1.8L16 7.5l-1.6.9.3-1.8-1.3-1.3 1.8-.2L16 3.5z"/>
|
|
546
527
|
<path fill="#FBBF24" d="M12 11.5l1 2 2.2.3-1.6 1.6.4 2.2-2-1.1-2 1.1.4-2.2-1.6-1.6 2.2-.3 1-2z"/>
|
|
547
|
-
</svg>`}function
|
|
528
|
+
</svg>`}function Dt(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
548
529
|
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
|
|
549
530
|
<circle cx="9" cy="7" r="4"/>
|
|
550
531
|
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
|
|
551
532
|
<path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
|
552
|
-
</svg>`}function kt(e,t){let n=document.createElement(`div`);n.className=`ttcb-msg ${t}`;let r=document.createElement(`div`);r.className=`ttcb-msg-avatar`,r.innerHTML=t===`human`?bt():t===`agent`?xt():Z();let i=document.createElement(`div`);if(i.className=`ttcb-msg-body`,t===`agent`){let e=document.createElement(`span`);e.className=`ttcb-msg-label`,e.textContent=`Agent`,i.appendChild(e)}let a=document.createElement(`div`);return a.className=`ttcb-bubble`,t===`human`?a.textContent=e:a.innerHTML=pt(e),i.appendChild(a),n.appendChild(r),n.appendChild(i),n}function At(){let e=document.createElement(`div`);e.className=`ttcb-msg ai`,e.id=`ttcb-typing`;let t=document.createElement(`div`);t.className=`ttcb-msg-avatar`,t.innerHTML=Z();let n=document.createElement(`div`);return n.className=`ttcb-typing`,n.innerHTML=`<span></span><span></span><span></span>`,e.appendChild(t),e.appendChild(n),e}var jt=class{constructor(e,t){this.selectedCountry=ut,this.countryOpen=!1,this.isOpen=!1,this.destroyed=!1,this.position=e.position??`bottom-right`,this.callbacks=t,this.mount(e)}mount(e){this.host=document.createElement(`div`),this.host.id=`onedeskpro-chatbot-host`,this.shadow=this.host.attachShadow({mode:`closed`});let t=document.createElement(`style`);t.textContent=ft(e.primaryColor??`#2563EB`,e.theme??`auto`),this.shadow.appendChild(t);let n=document.createElement(`button`);n.className=`ttcb-fab ${this.position}`,n.setAttribute(`aria-label`,`Open chat`),n.innerHTML=_t(),n.addEventListener(`click`,()=>this.toggle()),this.shadow.appendChild(n),this.panel=document.createElement(`div`),this.panel.className=`ttcb-panel ${this.position} hidden ttcb-mode-compact`,this.panel.setAttribute(`role`,`dialog`),this.panel.setAttribute(`aria-modal`,`true`),this.panel.setAttribute(`aria-label`,e.chatbotName??`AI Assistant`),this.panel.appendChild(this.buildHeader(e)),this.identifyContainer=document.createElement(`div`),this.identifyContainer.className=`ttcb-identify`,this.buildIdentifyForm(this.identifyContainer),this.panel.appendChild(this.identifyContainer),this.messagesContainer=document.createElement(`div`),this.messagesContainer.className=`ttcb-messages`,this.messagesContainer.setAttribute(`aria-live`,`polite`),this.messagesContainer.setAttribute(`aria-label`,`Chat messages`),this.panel.appendChild(this.messagesContainer),this.modeBanner=document.createElement(`div`),this.modeBanner.className=`ttcb-mode-banner`,this.modeBanner.setAttribute(`role`,`status`),this.panel.appendChild(this.modeBanner),this.footer=document.createElement(`div`),this.footer.className=`ttcb-footer`;let r=document.createElement(`form`);r.className=`ttcb-form`,r.addEventListener(`submit`,e=>{e.preventDefault(),this.handleSend()}),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`ttcb-input`,this.input.placeholder=e.placeholder??`Type your message…`,this.input.setAttribute(`aria-label`,`Message input`),this.input.setAttribute(`autocomplete`,`off`),this.sendBtn=document.createElement(`button`),this.sendBtn.type=`submit`,this.sendBtn.className=`ttcb-send-btn`,this.sendBtn.innerHTML=yt(),this.sendBtn.setAttribute(`aria-label`,`Send message`),r.appendChild(this.input),r.appendChild(this.sendBtn),this.footer.appendChild(r),this.panel.appendChild(this.footer),this.shadow.appendChild(this.panel),this.shadow.addEventListener(`click`,e=>{if(!this.countryOpen)return;let t=e.target;t&&(this.dialBtn.contains(t)||this.countryPopover.contains(t))||this.closeCountryPopover()}),this.attachToDocument(),this.showInitialLoading(),e.autoOpen&&this.open()}buildHeader(e){let t=document.createElement(`div`);t.className=`ttcb-header`;let n=document.createElement(`div`);n.className=`ttcb-avatar-wrap`;let r=document.createElement(`div`);r.className=`ttcb-avatar`,r.innerHTML=Z(),n.appendChild(r);let i=document.createElement(`div`);i.className=`ttcb-header-main`;let a=document.createElement(`div`);a.className=`ttcb-header-title-row`,this.headerTitle=document.createElement(`span`),this.headerTitle.className=`ttcb-header-title`,this.headerTitle.textContent=e.chatbotName??`AI Assistant`;let o=document.createElement(`span`);o.className=`ttcb-verified`,o.setAttribute(`aria-label`,`Verified`),o.innerHTML=Et(),a.appendChild(this.headerTitle),a.appendChild(o);let s=document.createElement(`div`);s.className=`ttcb-header-meta`;let c=document.createElement(`span`);c.className=`ttcb-meta-online`,c.textContent=`Online`;let l=document.createElement(`span`);l.className=`ttcb-meta-sep`,l.setAttribute(`aria-hidden`,`true`);let u=document.createElement(`span`);u.className=`ttcb-meta-replies`,u.innerHTML=`${Dt()}<span>Replies instantly</span>`,s.appendChild(c),s.appendChild(l),s.appendChild(u),i.appendChild(a),i.appendChild(s);let d=document.createElement(`div`);d.className=`ttcb-header-actions`,this.requestHumanBtn=document.createElement(`button`),this.requestHumanBtn.type=`button`,this.requestHumanBtn.className=`ttcb-request-human-btn hidden`,this.requestHumanBtn.id=`ttcb-request-human-btn`,this.requestHumanBtn.setAttribute(`aria-label`,`Request human agent`),this.requestHumanBtn.title=`Request human agent`,this.requestHumanBtn.innerHTML=Ot(),this.requestHumanBtn.addEventListener(`click`,()=>this.callbacks.onRequestHuman()),this.newSessionBtn=document.createElement(`button`),this.newSessionBtn.className=`ttcb-new-session-btn hidden`,this.newSessionBtn.setAttribute(`aria-label`,`New conversation`),this.newSessionBtn.title=`New conversation`,this.newSessionBtn.innerHTML=gt(),this.newSessionBtn.addEventListener(`click`,()=>this.callbacks.onReset());let f=document.createElement(`button`);return f.className=`ttcb-close-btn`,f.setAttribute(`aria-label`,`Close chat`),f.innerHTML=vt(),f.addEventListener(`click`,()=>this.close()),d.appendChild(this.requestHumanBtn),d.appendChild(this.newSessionBtn),d.appendChild(f),t.appendChild(n),t.appendChild(i),t.appendChild(d),t}setPanelMode(e){this.panel.classList.remove(`ttcb-mode-form`,`ttcb-mode-chat`,`ttcb-mode-compact`),this.panel.classList.add(`ttcb-mode-${e}`),e!==`chat`&&(this.requestHumanBtn.classList.add(`hidden`),this.newSessionBtn.classList.add(`hidden`),this.hideModeBanner())}buildIdentifyForm(e){let t=document.createElement(`form`);t.className=`ttcb-identify-form`,t.addEventListener(`submit`,e=>{e.preventDefault(),this.handleIdentifySubmit()}),this.nameInput=this.createIconField(t,{id:`name`,label:`Name`,required:!0,hint:`Required`,placeholder:`Your name`,type:`text`,autocomplete:`name`,icon:xt()}),this.createPhoneField(t),this.emailInput=this.createIconField(t,{id:`email`,label:`Email (optional)`,required:!1,hint:`For chat transcript`,placeholder:`Email (optional)`,type:`email`,autocomplete:`email`,icon:St()}),this.identifyError=document.createElement(`p`),this.identifyError.className=`ttcb-identify-error`,t.appendChild(this.identifyError),this.identifySubmit=document.createElement(`button`),this.identifySubmit.type=`submit`,this.identifySubmit.className=`ttcb-identify-submit`,this.identifySubmit.innerHTML=`<span>Start Chatting</span>${wt()}`,t.appendChild(this.identifySubmit),e.appendChild(t);let n=document.createElement(`div`);n.className=`ttcb-trust`,n.innerHTML=`${Tt()}<span>Encrypted connection • No spam, ever</span>`,e.appendChild(n)}createIconField(e,t){let n=document.createElement(`div`);n.className=`ttcb-field`;let r=document.createElement(`div`);r.className=`ttcb-field-label-row`;let i=document.createElement(`label`);i.className=`ttcb-label`,i.htmlFor=`ttcb-${t.id}`,t.required?i.innerHTML=`${t.label.replace(` (optional)`,``)} <span class="ttcb-req">*</span>`:i.textContent=t.label;let a=document.createElement(`span`);a.className=`ttcb-field-hint`,a.textContent=t.hint,r.appendChild(i),r.appendChild(a);let o=document.createElement(`div`);o.className=`ttcb-input-wrap`;let s=document.createElement(`span`);s.className=`ttcb-input-icon`,s.setAttribute(`aria-hidden`,`true`),s.innerHTML=t.icon;let c=document.createElement(`input`);return c.id=`ttcb-${t.id}`,c.name=t.id,c.type=t.type,c.className=`ttcb-identify-input`,c.placeholder=t.placeholder,c.required=t.required,c.autocomplete=t.autocomplete,o.appendChild(s),o.appendChild(c),n.appendChild(r),n.appendChild(o),e.appendChild(n),c}createPhoneField(e){let t=document.createElement(`div`);t.className=`ttcb-field`;let n=document.createElement(`div`);n.className=`ttcb-field-label-row`;let r=document.createElement(`label`);r.className=`ttcb-label`,r.htmlFor=`ttcb-tel`,r.innerHTML=`Phone <span class="ttcb-req">*</span>`;let i=document.createElement(`span`);i.className=`ttcb-field-hint`,i.textContent=`SMS / WhatsApp sync`,n.appendChild(r),n.appendChild(i);let a=document.createElement(`div`);a.className=`ttcb-phone-row`,a.id=`ttcb-phone-row`,this.dialBtn=document.createElement(`button`),this.dialBtn.type=`button`,this.dialBtn.className=`ttcb-dial-btn`,this.dialBtn.setAttribute(`aria-label`,`Select country code`),this.dialBtn.setAttribute(`aria-haspopup`,`listbox`),this.dialBtn.setAttribute(`aria-expanded`,`false`),this.dialFlag=document.createElement(`span`),this.dialFlag.className=`ttcb-dial-flag`,this.dialCode=document.createElement(`span`),this.dialCode.className=`ttcb-dial-code`,this.syncDialButton(),this.dialBtn.appendChild(this.dialFlag),this.dialBtn.appendChild(this.dialCode);let o=document.createElement(`span`);o.setAttribute(`aria-hidden`,`true`),o.innerHTML=Ct(),this.dialBtn.appendChild(o),this.dialBtn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.toggleCountryPopover()}),this.phoneInput=document.createElement(`input`),this.phoneInput.id=`ttcb-tel`,this.phoneInput.name=`tel`,this.phoneInput.type=`tel`,this.phoneInput.className=`ttcb-phone-national`,this.phoneInput.placeholder=`1712-345678`,this.phoneInput.required=!0,this.phoneInput.autocomplete=`tel-national`,this.phoneInput.setAttribute(`inputmode`,`tel`),a.appendChild(this.dialBtn),a.appendChild(this.phoneInput),this.countryPopover=document.createElement(`div`),this.countryPopover.className=`ttcb-country-popover`,this.countryPopover.setAttribute(`role`,`listbox`),this.countrySearch=document.createElement(`input`),this.countrySearch.type=`search`,this.countrySearch.className=`ttcb-country-search`,this.countrySearch.placeholder=`Search country…`,this.countrySearch.setAttribute(`aria-label`,`Search countries`),this.countrySearch.addEventListener(`input`,()=>this.renderCountryList()),this.countryList=document.createElement(`div`),this.countryList.className=`ttcb-country-list`,this.countryPopover.appendChild(this.countrySearch),this.countryPopover.appendChild(this.countryList),this.renderCountryList(),t.appendChild(n),t.appendChild(a),t.appendChild(this.countryPopover),e.appendChild(t)}syncDialButton(){this.dialFlag.textContent=this.selectedCountry.flag,this.dialCode.textContent=`+${this.selectedCountry.dial}`}toggleCountryPopover(){this.countryOpen?this.closeCountryPopover():this.openCountryPopover()}openCountryPopover(){this.countryOpen=!0,this.countryPopover.classList.add(`open`),this.dialBtn.setAttribute(`aria-expanded`,`true`),this.countrySearch.value=``,this.renderCountryList(),queueMicrotask(()=>this.countrySearch.focus())}closeCountryPopover(){this.countryOpen=!1,this.countryPopover.classList.remove(`open`),this.dialBtn.setAttribute(`aria-expanded`,`false`)}renderCountryList(){let e=this.countrySearch.value.trim().toLowerCase(),t=Y.filter(t=>!e||t.name.toLowerCase().includes(e)||t.dial.includes(e)||t.iso.toLowerCase().includes(e)||`+${t.dial}`.includes(e));this.countryList.innerHTML=``;for(let e of t){let t=document.createElement(`button`);t.type=`button`,t.className=`ttcb-country-item`,t.setAttribute(`role`,`option`),t.setAttribute(`aria-selected`,e.iso===this.selectedCountry.iso?`true`:`false`),t.innerHTML=`
|
|
533
|
+
</svg>`}function Ot(e,t){let n=document.createElement(`div`);n.className=`ttcb-msg ${t}`;let r=document.createElement(`div`);r.className=`ttcb-msg-avatar`,r.innerHTML=t===`human`?yt():t===`agent`?bt():X();let i=document.createElement(`div`);if(i.className=`ttcb-msg-body`,t===`agent`){let e=document.createElement(`span`);e.className=`ttcb-msg-label`,e.textContent=`Agent`,i.appendChild(e)}let a=document.createElement(`div`);return a.className=`ttcb-bubble`,t===`human`?a.textContent=e:a.innerHTML=mt(e),i.appendChild(a),n.appendChild(r),n.appendChild(i),n}function kt(){let e=document.createElement(`div`);e.className=`ttcb-msg ai`,e.id=`ttcb-typing`;let t=document.createElement(`div`);t.className=`ttcb-msg-avatar`,t.innerHTML=X();let n=document.createElement(`div`);return n.className=`ttcb-typing`,n.innerHTML=`<span></span><span></span><span></span>`,e.appendChild(t),e.appendChild(n),e}var At=class{constructor(e,t){this.selectedCountry=dt,this.countryOpen=!1,this.isOpen=!1,this.destroyed=!1,this.position=e.position??`bottom-right`,this.callbacks=t,this.autoOpen=e.autoOpen===!0,this.mount(e)}mount(e){this.host=document.createElement(`div`),this.host.id=`onedeskpro-chatbot-host`,this.host.style.display=`none`,this.shadow=this.host.attachShadow({mode:`closed`});let t=document.createElement(`style`);t.textContent=pt(e.primaryColor??`#2563EB`,e.theme??`auto`),this.shadow.appendChild(t);let n=document.createElement(`button`);n.className=`ttcb-fab ${this.position}`,n.setAttribute(`aria-label`,`Open chat`),n.innerHTML=gt(),n.addEventListener(`click`,()=>this.toggle()),this.shadow.appendChild(n),this.panel=document.createElement(`div`),this.panel.className=`ttcb-panel ${this.position} hidden ttcb-mode-compact`,this.panel.setAttribute(`role`,`dialog`),this.panel.setAttribute(`aria-modal`,`true`),this.panel.setAttribute(`aria-label`,e.chatbotName??`AI Assistant`),this.panel.appendChild(this.buildHeader(e)),this.identifyContainer=document.createElement(`div`),this.identifyContainer.className=`ttcb-identify`,this.buildIdentifyForm(this.identifyContainer),this.panel.appendChild(this.identifyContainer),this.messagesContainer=document.createElement(`div`),this.messagesContainer.className=`ttcb-messages`,this.messagesContainer.setAttribute(`aria-live`,`polite`),this.messagesContainer.setAttribute(`aria-label`,`Chat messages`),this.panel.appendChild(this.messagesContainer),this.modeBanner=document.createElement(`div`),this.modeBanner.className=`ttcb-mode-banner`,this.modeBanner.setAttribute(`role`,`status`),this.panel.appendChild(this.modeBanner),this.footer=document.createElement(`div`),this.footer.className=`ttcb-footer`;let r=document.createElement(`form`);r.className=`ttcb-form`,r.addEventListener(`submit`,e=>{e.preventDefault(),this.handleSend()}),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`ttcb-input`,this.input.placeholder=e.placeholder??`Type your message…`,this.input.setAttribute(`aria-label`,`Message input`),this.input.setAttribute(`autocomplete`,`off`),this.sendBtn=document.createElement(`button`),this.sendBtn.type=`submit`,this.sendBtn.className=`ttcb-send-btn`,this.sendBtn.innerHTML=vt(),this.sendBtn.setAttribute(`aria-label`,`Send message`),r.appendChild(this.input),r.appendChild(this.sendBtn),this.footer.appendChild(r),this.panel.appendChild(this.footer),this.shadow.appendChild(this.panel),this.shadow.addEventListener(`click`,e=>{if(!this.countryOpen)return;let t=e.target;t&&(this.dialBtn.contains(t)||this.countryPopover.contains(t))||this.closeCountryPopover()}),this.attachToDocument(),this.showInitialLoading()}reveal(){this.host.style.removeProperty(`display`),this.autoOpen&&!this.isOpen&&this.open()}buildHeader(e){let t=document.createElement(`div`);t.className=`ttcb-header`;let n=document.createElement(`div`);n.className=`ttcb-avatar-wrap`;let r=document.createElement(`div`);r.className=`ttcb-avatar`,r.innerHTML=X(),n.appendChild(r);let i=document.createElement(`div`);i.className=`ttcb-header-main`;let a=document.createElement(`div`);a.className=`ttcb-header-title-row`,this.headerTitle=document.createElement(`span`),this.headerTitle.className=`ttcb-header-title`,this.headerTitle.textContent=e.chatbotName??`AI Assistant`;let o=document.createElement(`span`);o.className=`ttcb-verified`,o.setAttribute(`aria-label`,`Verified`),o.innerHTML=Tt(),a.appendChild(this.headerTitle),a.appendChild(o);let s=document.createElement(`div`);s.className=`ttcb-header-meta`;let c=document.createElement(`span`);c.className=`ttcb-meta-online`,c.textContent=`Online`;let l=document.createElement(`span`);l.className=`ttcb-meta-sep`,l.setAttribute(`aria-hidden`,`true`);let u=document.createElement(`span`);u.className=`ttcb-meta-replies`,u.innerHTML=`${Et()}<span>Replies instantly</span>`,s.appendChild(c),s.appendChild(l),s.appendChild(u),i.appendChild(a),i.appendChild(s);let d=document.createElement(`div`);d.className=`ttcb-header-actions`,this.requestHumanBtn=document.createElement(`button`),this.requestHumanBtn.type=`button`,this.requestHumanBtn.className=`ttcb-request-human-btn hidden`,this.requestHumanBtn.id=`ttcb-request-human-btn`,this.requestHumanBtn.setAttribute(`aria-label`,`Request human agent`),this.requestHumanBtn.title=`Request human agent`,this.requestHumanBtn.innerHTML=Dt(),this.requestHumanBtn.addEventListener(`click`,()=>this.callbacks.onRequestHuman()),this.newSessionBtn=document.createElement(`button`),this.newSessionBtn.className=`ttcb-new-session-btn hidden`,this.newSessionBtn.setAttribute(`aria-label`,`New conversation`),this.newSessionBtn.title=`New conversation`,this.newSessionBtn.innerHTML=ht(),this.newSessionBtn.addEventListener(`click`,()=>this.callbacks.onReset());let f=document.createElement(`button`);return f.className=`ttcb-close-btn`,f.setAttribute(`aria-label`,`Close chat`),f.innerHTML=_t(),f.addEventListener(`click`,()=>this.close()),d.appendChild(this.requestHumanBtn),d.appendChild(this.newSessionBtn),d.appendChild(f),t.appendChild(n),t.appendChild(i),t.appendChild(d),t}setPanelMode(e){this.panel.classList.remove(`ttcb-mode-form`,`ttcb-mode-chat`,`ttcb-mode-compact`),this.panel.classList.add(`ttcb-mode-${e}`),e!==`chat`&&(this.requestHumanBtn.classList.add(`hidden`),this.newSessionBtn.classList.add(`hidden`),this.hideModeBanner())}buildIdentifyForm(e){let t=document.createElement(`form`);t.className=`ttcb-identify-form`,t.addEventListener(`submit`,e=>{e.preventDefault(),this.handleIdentifySubmit()}),this.nameInput=this.createIconField(t,{id:`name`,label:`Name`,required:!0,hint:`Required`,placeholder:`Your name`,type:`text`,autocomplete:`name`,icon:bt()}),this.createPhoneField(t),this.emailInput=this.createIconField(t,{id:`email`,label:`Email (optional)`,required:!1,hint:`For chat transcript`,placeholder:`Email (optional)`,type:`email`,autocomplete:`email`,icon:xt()}),this.identifyError=document.createElement(`p`),this.identifyError.className=`ttcb-identify-error`,t.appendChild(this.identifyError),this.identifySubmit=document.createElement(`button`),this.identifySubmit.type=`submit`,this.identifySubmit.className=`ttcb-identify-submit`,this.identifySubmit.innerHTML=`<span>Start Chatting</span>${Ct()}`,t.appendChild(this.identifySubmit),e.appendChild(t);let n=document.createElement(`div`);n.className=`ttcb-trust`,n.innerHTML=`${wt()}<span>Encrypted connection • No spam, ever</span>`,e.appendChild(n)}createIconField(e,t){let n=document.createElement(`div`);n.className=`ttcb-field`;let r=document.createElement(`div`);r.className=`ttcb-field-label-row`;let i=document.createElement(`label`);i.className=`ttcb-label`,i.htmlFor=`ttcb-${t.id}`,t.required?i.innerHTML=`${t.label.replace(` (optional)`,``)} <span class="ttcb-req">*</span>`:i.textContent=t.label;let a=document.createElement(`span`);a.className=`ttcb-field-hint`,a.textContent=t.hint,r.appendChild(i),r.appendChild(a);let o=document.createElement(`div`);o.className=`ttcb-input-wrap`;let s=document.createElement(`span`);s.className=`ttcb-input-icon`,s.setAttribute(`aria-hidden`,`true`),s.innerHTML=t.icon;let c=document.createElement(`input`);return c.id=`ttcb-${t.id}`,c.name=t.id,c.type=t.type,c.className=`ttcb-identify-input`,c.placeholder=t.placeholder,c.required=t.required,c.autocomplete=t.autocomplete,o.appendChild(s),o.appendChild(c),n.appendChild(r),n.appendChild(o),e.appendChild(n),c}createPhoneField(e){let t=document.createElement(`div`);t.className=`ttcb-field`;let n=document.createElement(`div`);n.className=`ttcb-field-label-row`;let r=document.createElement(`label`);r.className=`ttcb-label`,r.htmlFor=`ttcb-tel`,r.innerHTML=`Phone <span class="ttcb-req">*</span>`;let i=document.createElement(`span`);i.className=`ttcb-field-hint`,i.textContent=`SMS / WhatsApp sync`,n.appendChild(r),n.appendChild(i);let a=document.createElement(`div`);a.className=`ttcb-phone-row`,a.id=`ttcb-phone-row`,this.dialBtn=document.createElement(`button`),this.dialBtn.type=`button`,this.dialBtn.className=`ttcb-dial-btn`,this.dialBtn.setAttribute(`aria-label`,`Select country code`),this.dialBtn.setAttribute(`aria-haspopup`,`listbox`),this.dialBtn.setAttribute(`aria-expanded`,`false`),this.dialFlag=document.createElement(`span`),this.dialFlag.className=`ttcb-dial-flag`,this.dialCode=document.createElement(`span`),this.dialCode.className=`ttcb-dial-code`,this.syncDialButton(),this.dialBtn.appendChild(this.dialFlag),this.dialBtn.appendChild(this.dialCode);let o=document.createElement(`span`);o.setAttribute(`aria-hidden`,`true`),o.innerHTML=St(),this.dialBtn.appendChild(o),this.dialBtn.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.toggleCountryPopover()}),this.phoneInput=document.createElement(`input`),this.phoneInput.id=`ttcb-tel`,this.phoneInput.name=`tel`,this.phoneInput.type=`tel`,this.phoneInput.className=`ttcb-phone-national`,this.phoneInput.placeholder=`1712-345678`,this.phoneInput.required=!0,this.phoneInput.autocomplete=`tel-national`,this.phoneInput.setAttribute(`inputmode`,`tel`),a.appendChild(this.dialBtn),a.appendChild(this.phoneInput),this.countryPopover=document.createElement(`div`),this.countryPopover.className=`ttcb-country-popover`,this.countryPopover.setAttribute(`role`,`listbox`),this.countrySearch=document.createElement(`input`),this.countrySearch.type=`search`,this.countrySearch.className=`ttcb-country-search`,this.countrySearch.placeholder=`Search country…`,this.countrySearch.setAttribute(`aria-label`,`Search countries`),this.countrySearch.addEventListener(`input`,()=>this.renderCountryList()),this.countryList=document.createElement(`div`),this.countryList.className=`ttcb-country-list`,this.countryPopover.appendChild(this.countrySearch),this.countryPopover.appendChild(this.countryList),this.renderCountryList(),t.appendChild(n),t.appendChild(a),t.appendChild(this.countryPopover),e.appendChild(t)}syncDialButton(){this.dialFlag.textContent=this.selectedCountry.flag,this.dialCode.textContent=`+${this.selectedCountry.dial}`}toggleCountryPopover(){this.countryOpen?this.closeCountryPopover():this.openCountryPopover()}openCountryPopover(){this.countryOpen=!0,this.countryPopover.classList.add(`open`),this.dialBtn.setAttribute(`aria-expanded`,`true`),this.countrySearch.value=``,this.renderCountryList(),queueMicrotask(()=>this.countrySearch.focus())}closeCountryPopover(){this.countryOpen=!1,this.countryPopover.classList.remove(`open`),this.dialBtn.setAttribute(`aria-expanded`,`false`)}renderCountryList(){let e=this.countrySearch.value.trim().toLowerCase(),t=J.filter(t=>!e||t.name.toLowerCase().includes(e)||t.dial.includes(e)||t.iso.toLowerCase().includes(e)||`+${t.dial}`.includes(e));this.countryList.innerHTML=``;for(let e of t){let t=document.createElement(`button`);t.type=`button`,t.className=`ttcb-country-item`,t.setAttribute(`role`,`option`),t.setAttribute(`aria-selected`,e.iso===this.selectedCountry.iso?`true`:`false`),t.innerHTML=`
|
|
553
534
|
<span class="ttcb-dial-flag">${e.flag}</span>
|
|
554
535
|
<span class="ttcb-country-item-name">${e.name}</span>
|
|
555
536
|
<span class="ttcb-country-item-dial">+${e.dial}</span>
|
|
556
|
-
`,t.addEventListener(`click`,()=>{this.selectedCountry=e,this.syncDialButton(),this.closeCountryPopover(),this.phoneInput.focus()}),this.countryList.appendChild(t)}}attachToDocument(){let e=()=>{this.destroyed||(document.body??document.documentElement).appendChild(this.host)};document.body?e():document.addEventListener(`DOMContentLoaded`,e,{once:!0})}showInitialLoading(){this.setPanelMode(`compact`),this.identifyContainer.classList.remove(`visible`),this.messagesContainer.classList.remove(`hidden`),this.footer.classList.add(`hidden`),this.messagesContainer.innerHTML=``,this.input.disabled=!0,this.sendBtn.disabled=!0;let e=document.createElement(`div`);e.className=`ttcb-initial-loading`,e.id=`ttcb-initial-loading`;let t=document.createElement(`div`);t.className=`ttcb-spinner`;let n=document.createElement(`p`);n.textContent=`Loading…`,e.appendChild(t),e.appendChild(n),this.messagesContainer.appendChild(e)}showEmptyState(e){let t=document.createElement(`div`);t.className=`ttcb-empty`,t.id=`ttcb-empty`;let n=document.createElement(`div`);n.className=`ttcb-empty-icon`,n.innerHTML=Z();let r=document.createElement(`p`),i=document.createElement(`strong`);i.textContent=e,r.appendChild(document.createTextNode(`Welcome to `)),r.appendChild(i);let a=document.createElement(`p`);a.textContent=`Ask me anything — I'm here to help!`,a.style.marginTop=`6px`,a.style.fontSize=`12px`,t.appendChild(n),t.appendChild(r),t.appendChild(a),this.messagesContainer.appendChild(t)}removeEmptyState(){let e=this.shadow.getElementById(`ttcb-empty`);e&&e.remove()}handleSend(){let e=this.input.value.trim();e&&!this.sendBtn.disabled&&(this.input.value=``,this.callbacks.onSend(e),this.input.focus())}handleIdentifySubmit(){let e=this.nameInput.value.trim(),t=dt(this.selectedCountry.dial,this.phoneInput.value),n=this.emailInput.value.trim();!e||!t?this.showIdentifyError(`Name and phone are required.`):(this.showIdentifyError(``),this.callbacks.onIdentify({name:e,phone:t,...n?{email:n}:{}}))}appendMessage(e){this.removeEmptyState();let t=`message`in e?e.message:e,n=kt(t.content,t.type);this.messagesContainer.appendChild(n),this.scrollToBottom()}setMessages(e){if(this.messagesContainer.innerHTML=``,e.length!==0){for(let t of e){let e=kt(t.message.content,t.message.type);this.messagesContainer.appendChild(e)}this.scrollToBottom()}}setLoading(e){if(this.sendBtn.disabled=e||this.input.disabled,e)this.shadow.getElementById(`ttcb-typing`)||(this.messagesContainer.appendChild(At()),this.scrollToBottom()),this.input.focus();else{let e=this.shadow.getElementById(`ttcb-typing`);e&&e.remove(),this.input.disabled||this.input.focus()}}setIdentifyLoading(e){this.identifySubmit.disabled=e,this.nameInput.disabled=e,this.phoneInput.disabled=e,this.emailInput.disabled=e,this.dialBtn.disabled=e,this.shadow.getElementById(`ttcb-phone-row`)?.classList.toggle(`disabled`,e);for(let t of this.identifyContainer.querySelectorAll(`.ttcb-input-wrap`))t.classList.toggle(`disabled`,e);this.identifySubmit.innerHTML=e?`<span>Starting…</span>`:`<span>Start Chatting</span>${wt()}`,e&&this.closeCountryPopover()}showIdentifyError(e){this.identifyError.textContent=e}open(){this.isOpen=!0,this.panel.classList.remove(`hidden`),this.identifyContainer.classList.contains(`visible`)?this.nameInput.focus():this.input.focus(),this.callbacks.onOpen()}close(){this.isOpen=!1,this.closeCountryPopover(),this.panel.classList.add(`hidden`),this.callbacks.onClose()}toggle(){this.isOpen?this.close():this.open()}showIdentifyForm(e){this.setPanelMode(`form`),e.chatbotName&&(this.headerTitle.textContent=e.chatbotName),this.messagesContainer.classList.add(`hidden`),this.footer.classList.add(`hidden`),this.identifyContainer.classList.add(`visible`),this.showIdentifyError(``),this.setIdentifyLoading(!1)}readyToChat(e){this.setPanelMode(`chat`),this.closeCountryPopover(),this.identifyContainer.classList.remove(`visible`),this.messagesContainer.classList.remove(`hidden`),this.footer.classList.remove(`hidden`),this.messagesContainer.innerHTML=``,e.chatbotName&&(this.headerTitle.textContent=e.chatbotName),e.welcomeMessage?this.appendMessage({type:`ai`,content:e.welcomeMessage}):this.showEmptyState(e.chatbotName??`AI Assistant`),this.setMode(`ai`)}showBlocked(e,t){this.setPanelMode(`compact`),this.closeCountryPopover(),this.identifyContainer.classList.remove(`visible`),this.messagesContainer.classList.remove(`hidden`),this.footer.classList.add(`hidden`),this.messagesContainer.innerHTML=``;let n=document.createElement(`div`);n.className=`ttcb-blocked`;let r=document.createElement(`div`);r.className=`ttcb-blocked-icon`;let i=document.createElement(`p`);i.className=`ttcb-blocked-title`;let a=document.createElement(`p`);a.className=`ttcb-blocked-desc`,e===`no-prompt`?(r.innerHTML=ht(),i.textContent=`Business Context Required`,a.textContent=t??`Add a system prompt for this agent in the admin panel.`):e===`no-agent`?(r.innerHTML=mt(),i.textContent=`Channel Not Connected`,a.textContent=t??`Connect this Website channel under AI Agents → Connected Channels.`):e===`no-directories`||e===`no-collections`?(r.innerHTML=ht(),i.textContent=`Knowledge Base Required`,a.textContent=t??`Assign at least one knowledge-base collection to this agent in the admin panel.`):(r.innerHTML=mt(),i.textContent=`Chatbot Settings Required`,a.textContent=t??`The chatbot has not been configured yet. Please set it up in the admin panel.`),n.appendChild(r),n.appendChild(i),n.appendChild(a),this.messagesContainer.appendChild(n)}clearMessages(e){this.messagesContainer.innerHTML=``,this.showEmptyState(e)}setMode(e,t){let n=this.panel.classList.contains(`ttcb-mode-chat`),r=t?.agentName,i=t?.canRequestHuman===!0,a=n&&i,o=n&&e===`closed`,s=e===`closed`;this.requestHumanBtn.classList.toggle(`hidden`,!a),this.newSessionBtn.classList.toggle(`hidden`,!o),this.input.disabled=s,s?this.sendBtn.disabled=!0:this.shadow.getElementById(`ttcb-typing`)||(this.sendBtn.disabled=!1),n?e===`waiting`?this.showModeBanner(`Waiting for a human agent…`,`waiting`):e===`closed`?this.showModeBanner(`This conversation is closed`,`closed`):e===`human`&&r?.trim()?this.showModeBanner(`Connected with ${r.trim()}`,`human`):this.hideModeBanner():this.hideModeBanner()}showModeBanner(e,t){this.modeBanner.textContent=e,this.modeBanner.className=`ttcb-mode-banner visible ${t}`}hideModeBanner(){this.modeBanner.textContent=``,this.modeBanner.className=`ttcb-mode-banner`}destroy(){this.destroyed=!0,this.host.remove()}scrollToBottom(){this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight}},Mt={apiBaseUrl:o,chatbotName:`AI Assistant`,primaryColor:`#2563EB`,theme:`auto`,position:`bottom-right`,welcomeMessage:``,placeholder:`Type your message…`,autoOpen:!1,sessionId:``,requestTimeoutMs:n};function Nt(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}var Pt=0,Q=()=>Date.now()*1e3+Pt++%1e3;function Ft(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.textMessage==`string`&&t.textMessage.trim())return t.textMessage.trim();if(typeof t.content==`string`&&t.content.trim())return t.content.trim();if(t.message&&typeof t.message==`object`){let e=t.message;if(typeof e.content==`string`&&e.content.trim())return e.content.trim();if(typeof e.textMessage==`string`&&e.textMessage.trim())return e.textMessage.trim()}return null}function It(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id==`string`&&t.id)return t.id;if(t.message&&typeof t.message==`object`){let e=t.message;if(typeof e.id==`string`&&e.id)return e.id}return null}var Lt=class{constructor(){this.emitter=new s,this.visitorTokens=new lt,this.widget=null,this.sdkSocket=null,this.callerSetName=!1,this.hasActiveTicket=!1,this.lastPushId=null,this.initToken=0,this._state={isOpen:!1,isLoading:!1,isReady:!1,needsIdentify:!0,blockReason:null,messages:[],visitorToken:null,visitorName:null,error:null,mode:`ai`}}setState(e){this._state={...this._state,...e},this.emitter.emit(`state-change`,this._state)}applyMode(e,t){t?this.syncHasActiveTicket(t):e!==`ai`&&(this.hasActiveTicket=!0),this.setState({mode:e}),this.syncWidgetMode(e,t?.agentName),t&&this.emitter.emit(`ticket-status`,t)}syncHasActiveTicket(e){this.hasActiveTicket=!!(e.conversationId||e.mode!==`ai`)}syncWidgetMode(e,t){this.widget?.setMode(e,{agentName:t,canRequestHuman:e===`ai`&&this.hasActiveTicket})}async init(e){if(!e.apiKey)throw Error("[onedeskpro-chatbot] `apiKey` is required to initialise the chatbot.");let t=++this.initToken;this.disconnectSdkSocket(),this.widget?.destroy(),this.widget=null,this.callerSetName=e.chatbotName!==void 0,this.options={...Mt,...Nt(e)},this.apiClient=new a({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,timeoutMs:this.options.requestTimeoutMs}),this.hasActiveTicket=!1,this.setState({visitorToken:null,visitorName:null,needsIdentify:!0,messages:[],error:null,mode:`ai`}),typeof window<`u`&&typeof document<`u`&&(this.widget=new jt(this.options,{onSend:e=>void this.sendMessage(e),onIdentify:e=>void this.submitIdentify(e),onOpen:()=>{this.setState({isOpen:!0}),this.emitter.emit(`open`)},onClose:()=>{this.setState({isOpen:!1}),this.emitter.emit(`close`)},onReset:()=>this.resetSession(),onRequestHuman:()=>void this.requestHuman()}));let n=null,r=null;try{n=await this.apiClient.fetchConfig()}catch(e){r=e}if(t!==this.initToken)return;if(r){this.handleConfigError(r),this.emitter.emit(`ready`);return}if(!n){this.emitter.emit(`ready`);return}!this.callerSetName&&n.agentName.trim()&&(this.options.chatbotName=n.agentName);let i=n.blockReason??null;if(this.setState({blockReason:i,isReady:i===null,error:null}),i)this.widget?.showBlocked(i);else if(this.visitorTokens.setScope(n.agentId),await this.resolveVisitorGate(t),t!==this.initToken)return;this.emitter.emit(`ready`)}handleConfigError(e){let t=i(e)?e:null,n=t?.apiError.message??(e instanceof Error?e.message:`Failed to load chatbot config.`),r=t?.apiError.code,a=t?.status;r===`agent_not_assigned`?(this.setState({isReady:!1,blockReason:`no-agent`,error:n}),this.widget?.showBlocked(`no-agent`)):a===403?(this.setState({isReady:!1,blockReason:null,error:n}),this.widget?.showBlocked(null,n)):this.setState({isReady:!1,blockReason:null,error:n})}async resolveVisitorGate(e){let t=this.visitorTokens.get();if(t){try{let n=await this.apiClient.verifyVisitor(t);if(e!==this.initToken)return;if(n.valid){await this.enterChat(t,n.name,e);return}}catch{}this.visitorTokens.clear()}this.setState({needsIdentify:!0,visitorToken:null,visitorName:null}),this.widget?.showIdentifyForm(this.options)}async enterChat(e,t,n=this.initToken){this.visitorTokens.set(e),this.setState({visitorToken:e,visitorName:t,needsIdentify:!1,messages:[],error:null}),this.widget?.readyToChat(this.options),this.connectSdkSocket(e),await this.restoreTicketStatus(e,n)}connectSdkSocket(e){this.sdkSocket||=new at,this.sdkSocket.connect({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,visitorToken:e,onTicketStatus:e=>this.handleTicketStatus(e),onMessageReceive:e=>this.handleMessageReceive(e),onReconnect:()=>{let e=this.visitorTokens.get()??this._state.visitorToken;e&&this.restoreTicketStatus(e,this.initToken)},onConnectError:e=>{this.emitter.emit(`error`,e)}})}disconnectSdkSocket(){this.sdkSocket?.disconnect(),this.sdkSocket=null}async restoreTicketStatus(e,t){try{let n=await this.apiClient.fetchTicketStatus(e);if(t!==this.initToken)return;this.applyMode(n.mode,n)}catch{}}handleTicketStatus(e){e?.mode&&this.applyMode(e.mode,e)}handleMessageReceive(e){if(this._state.mode===`ai`)return;let t=Ft(e);if(!t)return;let n=It(e),r=this._state.messages[this._state.messages.length-1];if(r?.message.content===t&&(r.message.type===`ai`||r.message.type===`agent`&&(!n||n===this.lastPushId)))return;this.lastPushId=n;let i=this.visitorTokens.get()??this._state.visitorToken??``,a={id:Q(),sessionId:i,message:{type:`agent`,content:t}};this.setState({messages:[...this._state.messages,a]}),this.widget?.appendMessage(a),this.emitter.emit(`message`,a)}async submitIdentify(e){if(!this.apiClient||this._state.isLoading||!this._state.isReady)return;let t=e.name.trim(),n=e.phone.trim();if(t&&n){this.setState({isLoading:!0,error:null}),this.widget?.setIdentifyLoading(!0);try{let r=await this.apiClient.identify({name:t,phone:n,...e.email?.trim()?{email:e.email.trim()}:{}});await this.enterChat(r.visitorToken,t)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message}),this.widget?.showIdentifyError(t.message),this.emitter.emit(`error`,t)}finally{this.setState({isLoading:!1}),this.widget?.setIdentifyLoading(!1)}}}async requestHuman(){if(!this.apiClient||this._state.mode!==`ai`||!this.hasActiveTicket||this._state.isLoading)return;let e=this.visitorTokens.get()??this._state.visitorToken;if(!e)throw Error(`[onedeskpro-chatbot] Identify before requestHuman().`);this.setState({isLoading:!0,error:null});try{let t=await this.apiClient.requestHuman(e);this.applyMode(t.mode,t),this.emitter.emit(`human-requested`)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message}),this.emitter.emit(`error`,t)}finally{this.setState({isLoading:!1})}}async sendMessage(e){let t=this.visitorTokens.get()??this._state.visitorToken;if(!this.apiClient||!t)throw Error(`[onedeskpro-chatbot] Identify before sendMessage().`);if(this._state.mode===`closed`){this.setState({error:`Conversation is closed`});return}let n=e.trim();if(!n||this._state.isLoading||this._state.needsIdentify)return;let r={id:Q(),sessionId:t,message:{type:`human`,content:n}},i=this._state.mode,a=i===`ai`;this.setState({messages:[...this._state.messages,r],isLoading:!0,error:null}),this.widget?.appendMessage(r),a&&this.widget?.setLoading(!0),this.emitter.emit(`message`,r);try{let e=await this.apiClient.sendMessage({chatInput:n,visitorToken:t});this.hasActiveTicket=!0;let r=e.mode??i,a=[...this._state.messages],o=(e.text??``).trim();if(r!==i&&(this.setState({mode:r}),this.syncWidgetMode(r),this.emitter.emit(`ticket-status`,{mode:r})),o){let t=a[a.length-1];if(t?.message.type!==`agent`&&t?.message.type!==`ai`||t.message.content!==o){let t={id:Q(),sessionId:e.sessionId,message:{type:`ai`,content:o}};a.push(t),this.widget?.appendMessage(t),this.emitter.emit(`message`,t)}}this.setState({messages:a,isLoading:!1,mode:r}),this.syncWidgetMode(r)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message,isLoading:!1}),this.emitter.emit(`error`,t)}finally{this.widget?.setLoading(!1)}}on(e,t){return this.emitter.on(e,t)}resetSession(){this._state.isReady&&!this._state.needsIdentify&&this._state.mode===`closed`&&(this.hasActiveTicket=!1,this.setState({messages:[],error:null,mode:`ai`}),this.widget?.clearMessages(this.options.chatbotName),this.syncWidgetMode(`ai`),this.emitter.emit(`session-reset`))}open(){this.widget?.open()}close(){this.widget?.close()}toggle(){this.widget?.toggle()}getState(){return{...this._state}}destroy(){this.initToken++,this.disconnectSdkSocket(),this.widget?.destroy(),this.widget=null,this.setState({isOpen:!1,isLoading:!1,isReady:!1,needsIdentify:!0})}},$=null,Rt={async init(e){return $=new Lt,await $.init(e),$},getInstance(){return $}};exports.ApiClient=a,exports.ChatbotCore=Lt,exports.DEFAULT_API_BASE_URL=o,exports.DEFAULT_REQUEST_TIMEOUT_MS=n,exports.EventEmitter=s,exports.OnedeskProChatbot=Rt,exports.SdkSocket=at,exports.SessionManager=lt,exports.isChatbotRequestError=i,exports.resolveSdkSocketUrl=it;
|
|
537
|
+
`,t.addEventListener(`click`,()=>{this.selectedCountry=e,this.syncDialButton(),this.closeCountryPopover(),this.phoneInput.focus()}),this.countryList.appendChild(t)}}attachToDocument(){let e=()=>{this.destroyed||(document.body??document.documentElement).appendChild(this.host)};document.body?e():document.addEventListener(`DOMContentLoaded`,e,{once:!0})}showInitialLoading(){this.setPanelMode(`compact`),this.identifyContainer.classList.remove(`visible`),this.messagesContainer.classList.remove(`hidden`),this.footer.classList.add(`hidden`),this.messagesContainer.innerHTML=``,this.input.disabled=!0,this.sendBtn.disabled=!0;let e=document.createElement(`div`);e.className=`ttcb-initial-loading`,e.id=`ttcb-initial-loading`;let t=document.createElement(`div`);t.className=`ttcb-spinner`;let n=document.createElement(`p`);n.textContent=`Loading…`,e.appendChild(t),e.appendChild(n),this.messagesContainer.appendChild(e)}showEmptyState(e){let t=document.createElement(`div`);t.className=`ttcb-empty`,t.id=`ttcb-empty`;let n=document.createElement(`div`);n.className=`ttcb-empty-icon`,n.innerHTML=X();let r=document.createElement(`p`),i=document.createElement(`strong`);i.textContent=e,r.appendChild(document.createTextNode(`Welcome to `)),r.appendChild(i);let a=document.createElement(`p`);a.textContent=`Ask me anything — I'm here to help!`,a.style.marginTop=`6px`,a.style.fontSize=`12px`,t.appendChild(n),t.appendChild(r),t.appendChild(a),this.messagesContainer.appendChild(t)}removeEmptyState(){let e=this.shadow.getElementById(`ttcb-empty`);e&&e.remove()}handleSend(){let e=this.input.value.trim();e&&!this.sendBtn.disabled&&(this.input.value=``,this.callbacks.onSend(e),this.input.focus())}handleIdentifySubmit(){let e=this.nameInput.value.trim(),t=ft(this.selectedCountry.dial,this.phoneInput.value),n=this.emailInput.value.trim();!e||!t?this.showIdentifyError(`Name and phone are required.`):(this.showIdentifyError(``),this.callbacks.onIdentify({name:e,phone:t,...n?{email:n}:{}}))}appendMessage(e){this.removeEmptyState();let t=`message`in e?e.message:e,n=Ot(t.content,t.type);this.messagesContainer.appendChild(n),this.scrollToBottom()}setMessages(e){if(this.messagesContainer.innerHTML=``,e.length!==0){for(let t of e){let e=Ot(t.message.content,t.message.type);this.messagesContainer.appendChild(e)}this.scrollToBottom()}}setLoading(e){if(this.sendBtn.disabled=e||this.input.disabled,e)this.shadow.getElementById(`ttcb-typing`)||(this.messagesContainer.appendChild(kt()),this.scrollToBottom()),this.input.focus();else{let e=this.shadow.getElementById(`ttcb-typing`);e&&e.remove(),this.input.disabled||this.input.focus()}}setIdentifyLoading(e){this.identifySubmit.disabled=e,this.nameInput.disabled=e,this.phoneInput.disabled=e,this.emailInput.disabled=e,this.dialBtn.disabled=e,this.shadow.getElementById(`ttcb-phone-row`)?.classList.toggle(`disabled`,e);for(let t of this.identifyContainer.querySelectorAll(`.ttcb-input-wrap`))t.classList.toggle(`disabled`,e);this.identifySubmit.innerHTML=e?`<span>Starting…</span>`:`<span>Start Chatting</span>${Ct()}`,e&&this.closeCountryPopover()}showIdentifyError(e){this.identifyError.textContent=e}open(){this.isOpen=!0,this.panel.classList.remove(`hidden`),this.identifyContainer.classList.contains(`visible`)?this.nameInput.focus():this.input.focus(),this.callbacks.onOpen()}close(){this.isOpen=!1,this.closeCountryPopover(),this.panel.classList.add(`hidden`),this.callbacks.onClose()}toggle(){this.isOpen?this.close():this.open()}showIdentifyForm(e){this.setPanelMode(`form`),e.chatbotName&&(this.headerTitle.textContent=e.chatbotName),this.messagesContainer.classList.add(`hidden`),this.footer.classList.add(`hidden`),this.identifyContainer.classList.add(`visible`),this.showIdentifyError(``),this.setIdentifyLoading(!1)}readyToChat(e){this.setPanelMode(`chat`),this.closeCountryPopover(),this.identifyContainer.classList.remove(`visible`),this.messagesContainer.classList.remove(`hidden`),this.footer.classList.remove(`hidden`),this.messagesContainer.innerHTML=``,e.chatbotName&&(this.headerTitle.textContent=e.chatbotName),e.welcomeMessage?this.appendMessage({type:`ai`,content:e.welcomeMessage}):this.showEmptyState(e.chatbotName??`AI Assistant`),this.setMode(`ai`)}clearMessages(e){this.messagesContainer.innerHTML=``,this.showEmptyState(e)}setMode(e,t){let n=this.panel.classList.contains(`ttcb-mode-chat`),r=t?.agentName,i=t?.canRequestHuman===!0,a=n&&i,o=n&&e===`closed`,s=e===`closed`;this.requestHumanBtn.classList.toggle(`hidden`,!a),this.newSessionBtn.classList.toggle(`hidden`,!o),this.input.disabled=s,s?this.sendBtn.disabled=!0:this.shadow.getElementById(`ttcb-typing`)||(this.sendBtn.disabled=!1),n?e===`waiting`?this.showModeBanner(`Waiting for a human agent…`,`waiting`):e===`closed`?this.showModeBanner(`This conversation is closed`,`closed`):e===`human`&&r?.trim()?this.showModeBanner(`Connected with ${r.trim()}`,`human`):this.hideModeBanner():this.hideModeBanner()}showModeBanner(e,t){this.modeBanner.textContent=e,this.modeBanner.className=`ttcb-mode-banner visible ${t}`}hideModeBanner(){this.modeBanner.textContent=``,this.modeBanner.className=`ttcb-mode-banner`}destroy(){this.destroyed=!0,this.host.remove()}scrollToBottom(){this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight}},jt={apiBaseUrl:o,chatbotName:`AI Assistant`,primaryColor:`#2563EB`,theme:`auto`,position:`bottom-right`,welcomeMessage:``,placeholder:`Type your message…`,autoOpen:!1,sessionId:``,requestTimeoutMs:n};function Mt(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}var Nt=[5e3,15e3,3e4,6e4];function Pt(e){return i(e)?e.status===0||e.status>=500||e.apiError.code===`BAD_RESPONSE`:!1}function Ft(e){return i(e)?e.apiError.message:e instanceof Error?e.message:`Failed to load chatbot config.`}var It=0,Z=()=>Date.now()*1e3+It++%1e3;function Lt(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.textMessage==`string`&&t.textMessage.trim())return t.textMessage.trim();if(typeof t.content==`string`&&t.content.trim())return t.content.trim();if(t.message&&typeof t.message==`object`){let e=t.message;if(typeof e.content==`string`&&e.content.trim())return e.content.trim();if(typeof e.textMessage==`string`&&e.textMessage.trim())return e.textMessage.trim()}return null}function Rt(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id==`string`&&t.id)return t.id;if(t.message&&typeof t.message==`object`){let e=t.message;if(typeof e.id==`string`&&e.id)return e.id}return null}var Q=class{constructor(){this.emitter=new s,this.visitorTokens=new ut,this.widget=null,this.sdkSocket=null,this.callerSetName=!1,this.hasActiveTicket=!1,this.retryTimer=null,this.lastPushId=null,this.initToken=0,this._state={isOpen:!1,isLoading:!1,isReady:!1,needsIdentify:!0,blockReason:null,messages:[],visitorToken:null,visitorName:null,error:null,mode:`ai`}}setState(e){this._state={...this._state,...e},this.emitter.emit(`state-change`,this._state)}applyMode(e,t){t?this.syncHasActiveTicket(t):e!==`ai`&&(this.hasActiveTicket=!0),this.setState({mode:e}),this.syncWidgetMode(e,t?.agentName),t&&this.emitter.emit(`ticket-status`,t)}syncHasActiveTicket(e){this.hasActiveTicket=!!(e.conversationId||e.mode!==`ai`)}syncWidgetMode(e,t){this.widget?.setMode(e,{agentName:t,canRequestHuman:e===`ai`&&this.hasActiveTicket})}async init(e){if(!e.apiKey)throw Error("[onedeskpro-chatbot] `apiKey` is required to initialise the chatbot.");let t=++this.initToken;this.clearRetry(),this.disconnectSdkSocket(),this.widget?.destroy(),this.widget=null,this.callerSetName=e.chatbotName!==void 0,this.options={...jt,...Mt(e)},this.apiClient=new a({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,timeoutMs:this.options.requestTimeoutMs}),this.hasActiveTicket=!1,this.setState({isReady:!1,blockReason:null,visitorToken:null,visitorName:null,needsIdentify:!0,messages:[],error:null,mode:`ai`}),await this.checkReadiness(t,0)}async checkReadiness(e,t){let n;try{n=await this.apiClient.fetchConfig()}catch(n){if(e!==this.initToken)return;if(Pt(n)){this.setState({isReady:!1,blockReason:`server-unavailable`,error:Ft(n)});let r=Nt[t];if(r!==void 0){this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.checkReadiness(e,t+1)},r);return}}else this.handleConfigError(n);this.emitter.emit(`ready`);return}if(e!==this.initToken)return;!this.callerSetName&&n.agentName.trim()&&(this.options.chatbotName=n.agentName);let r=n.blockReason??null,i=n.ready&&r===null;this.setState({blockReason:r,isReady:i,error:null}),i?(this.mountWidget(),this.visitorTokens.setScope(n.agentId),await this.resolveVisitorGate(e),e===this.initToken&&(this.widget?.reveal(),this.emitter.emit(`ready`))):this.emitter.emit(`ready`)}mountWidget(){typeof window<`u`&&typeof document<`u`&&(this.widget=new At(this.options,{onSend:e=>void this.sendMessage(e),onIdentify:e=>void this.submitIdentify(e),onOpen:()=>{this.setState({isOpen:!0}),this.emitter.emit(`open`)},onClose:()=>{this.setState({isOpen:!1}),this.emitter.emit(`close`)},onReset:()=>this.resetSession(),onRequestHuman:()=>void this.requestHuman()}))}clearRetry(){this.retryTimer!==null&&(clearTimeout(this.retryTimer),this.retryTimer=null)}handleConfigError(e){let t=(i(e)?e:null)?.apiError.code===`agent_not_assigned`?`no-agent`:null;this.setState({isReady:!1,blockReason:t,error:Ft(e)})}async resolveVisitorGate(e){let t=this.visitorTokens.get();if(t){try{let n=await this.apiClient.verifyVisitor(t);if(e!==this.initToken)return;if(n.valid){await this.enterChat(t,n.name,e);return}}catch{}this.visitorTokens.clear()}this.setState({needsIdentify:!0,visitorToken:null,visitorName:null}),this.widget?.showIdentifyForm(this.options)}async enterChat(e,t,n=this.initToken){this.visitorTokens.set(e),this.setState({visitorToken:e,visitorName:t,needsIdentify:!1,messages:[],error:null}),this.widget?.readyToChat(this.options),this.connectSdkSocket(e),await this.restoreTicketStatus(e,n)}connectSdkSocket(e){this.sdkSocket||=new ot,this.sdkSocket.connect({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,visitorToken:e,onTicketStatus:e=>this.handleTicketStatus(e),onMessageReceive:e=>this.handleMessageReceive(e),onReconnect:()=>{let e=this.visitorTokens.get()??this._state.visitorToken;e&&this.restoreTicketStatus(e,this.initToken)},onConnectError:e=>{this.emitter.emit(`error`,e)}})}disconnectSdkSocket(){this.sdkSocket?.disconnect(),this.sdkSocket=null}async restoreTicketStatus(e,t){try{let n=await this.apiClient.fetchTicketStatus(e);if(t!==this.initToken)return;this.applyMode(n.mode,n)}catch{}}handleTicketStatus(e){e?.mode&&this.applyMode(e.mode,e)}handleMessageReceive(e){if(this._state.mode===`ai`)return;let t=Lt(e);if(!t)return;let n=Rt(e),r=this._state.messages[this._state.messages.length-1];if(r?.message.content===t&&(r.message.type===`ai`||r.message.type===`agent`&&(!n||n===this.lastPushId)))return;this.lastPushId=n;let i=this.visitorTokens.get()??this._state.visitorToken??``,a={id:Z(),sessionId:i,message:{type:`agent`,content:t}};this.setState({messages:[...this._state.messages,a]}),this.widget?.appendMessage(a),this.emitter.emit(`message`,a)}async submitIdentify(e){if(!this.apiClient||this._state.isLoading||!this._state.isReady)return;let t=e.name.trim(),n=e.phone.trim();if(t&&n){this.setState({isLoading:!0,error:null}),this.widget?.setIdentifyLoading(!0);try{let r=await this.apiClient.identify({name:t,phone:n,...e.email?.trim()?{email:e.email.trim()}:{}});await this.enterChat(r.visitorToken,t)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message}),this.widget?.showIdentifyError(t.message),this.emitter.emit(`error`,t)}finally{this.setState({isLoading:!1}),this.widget?.setIdentifyLoading(!1)}}}async requestHuman(){if(!this.apiClient||this._state.mode!==`ai`||!this.hasActiveTicket||this._state.isLoading)return;let e=this.visitorTokens.get()??this._state.visitorToken;if(!e)throw Error(`[onedeskpro-chatbot] Identify before requestHuman().`);this.setState({isLoading:!0,error:null});try{let t=await this.apiClient.requestHuman(e);this.applyMode(t.mode,t),this.emitter.emit(`human-requested`)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message}),this.emitter.emit(`error`,t)}finally{this.setState({isLoading:!1})}}async sendMessage(e){let t=this.visitorTokens.get()??this._state.visitorToken;if(!this.apiClient||!t)throw Error(`[onedeskpro-chatbot] Identify before sendMessage().`);if(this._state.mode===`closed`){this.setState({error:`Conversation is closed`});return}let n=e.trim();if(!n||this._state.isLoading||this._state.needsIdentify)return;let r={id:Z(),sessionId:t,message:{type:`human`,content:n}},i=this._state.mode,a=i===`ai`;this.setState({messages:[...this._state.messages,r],isLoading:!0,error:null}),this.widget?.appendMessage(r),a&&this.widget?.setLoading(!0),this.emitter.emit(`message`,r);try{let e=await this.apiClient.sendMessage({chatInput:n,visitorToken:t});this.hasActiveTicket=!0;let r=e.mode??i,a=[...this._state.messages],o=(e.text??``).trim();if(r!==i&&(this.setState({mode:r}),this.syncWidgetMode(r),this.emitter.emit(`ticket-status`,{mode:r})),o){let t=a[a.length-1];if(t?.message.type!==`agent`&&t?.message.type!==`ai`||t.message.content!==o){let t={id:Z(),sessionId:e.sessionId,message:{type:`ai`,content:o}};a.push(t),this.widget?.appendMessage(t),this.emitter.emit(`message`,t)}}this.setState({messages:a,isLoading:!1,mode:r}),this.syncWidgetMode(r)}catch(e){let t=e instanceof Error?e:Error(String(e));this.setState({error:t.message,isLoading:!1}),this.emitter.emit(`error`,t)}finally{this.widget?.setLoading(!1)}}on(e,t){return this.emitter.on(e,t)}resetSession(){this._state.isReady&&!this._state.needsIdentify&&this._state.mode===`closed`&&(this.hasActiveTicket=!1,this.setState({messages:[],error:null,mode:`ai`}),this.widget?.clearMessages(this.options.chatbotName),this.syncWidgetMode(`ai`),this.emitter.emit(`session-reset`))}open(){this.widget?.open()}close(){this.widget?.close()}toggle(){this.widget?.toggle()}getState(){return{...this._state}}destroy(){this.initToken++,this.clearRetry(),this.disconnectSdkSocket(),this.widget?.destroy(),this.widget=null,this.setState({isOpen:!1,isLoading:!1,isReady:!1,needsIdentify:!0})}},$=null,zt={async init(e){return $=new Q,await $.init(e),$},getInstance(){return $}};exports.ApiClient=a,exports.ChatbotCore=Q,exports.DEFAULT_API_BASE_URL=o,exports.DEFAULT_REQUEST_TIMEOUT_MS=n,exports.EventEmitter=s,exports.OnedeskProChatbot=zt,exports.SdkSocket=ot,exports.SessionManager=ut,exports.isChatbotRequestError=i,exports.resolveSdkSocketUrl=at;
|
package/dist/index.d.cts
CHANGED
|
@@ -57,6 +57,8 @@ export declare class ChatbotCore {
|
|
|
57
57
|
* before a ticket exists.
|
|
58
58
|
*/
|
|
59
59
|
private hasActiveTicket;
|
|
60
|
+
/** Pending readiness re-check while the server is unreachable. */
|
|
61
|
+
private retryTimer;
|
|
60
62
|
/** Server id of the last `message:receive` push rendered as an agent bubble. */
|
|
61
63
|
private lastPushId;
|
|
62
64
|
/**
|
|
@@ -79,8 +81,19 @@ export declare class ChatbotCore {
|
|
|
79
81
|
private syncWidgetMode;
|
|
80
82
|
init(options: ChatbotInitOptions): Promise<void>;
|
|
81
83
|
/**
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
+
* Asks `/sdk/config` whether the server is up and the agent can reply, and
|
|
85
|
+
* shows the widget only when both hold. An unreachable server is retried on
|
|
86
|
+
* READINESS_RETRY_DELAYS_MS; a configuration problem is final for this page.
|
|
87
|
+
* `ready` fires once the outcome is settled either way.
|
|
88
|
+
*/
|
|
89
|
+
private checkReadiness;
|
|
90
|
+
/** Creates the widget hidden; checkReadiness reveals it once every check passed. */
|
|
91
|
+
private mountWidget;
|
|
92
|
+
private clearRetry;
|
|
93
|
+
/**
|
|
94
|
+
* Maps `/sdk/config` rejections other than an unreachable server: missing
|
|
95
|
+
* Connected Channels becomes `no-agent`; anything else (an invalid key, a
|
|
96
|
+
* disallowed origin) is recorded as `state.error`.
|
|
84
97
|
*/
|
|
85
98
|
private handleConfigError;
|
|
86
99
|
private resolveVisitorGate;
|
package/dist/index.d.ts
CHANGED
|
@@ -57,6 +57,8 @@ export declare class ChatbotCore {
|
|
|
57
57
|
* before a ticket exists.
|
|
58
58
|
*/
|
|
59
59
|
private hasActiveTicket;
|
|
60
|
+
/** Pending readiness re-check while the server is unreachable. */
|
|
61
|
+
private retryTimer;
|
|
60
62
|
/** Server id of the last `message:receive` push rendered as an agent bubble. */
|
|
61
63
|
private lastPushId;
|
|
62
64
|
/**
|
|
@@ -79,8 +81,19 @@ export declare class ChatbotCore {
|
|
|
79
81
|
private syncWidgetMode;
|
|
80
82
|
init(options: ChatbotInitOptions): Promise<void>;
|
|
81
83
|
/**
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
+
* Asks `/sdk/config` whether the server is up and the agent can reply, and
|
|
85
|
+
* shows the widget only when both hold. An unreachable server is retried on
|
|
86
|
+
* READINESS_RETRY_DELAYS_MS; a configuration problem is final for this page.
|
|
87
|
+
* `ready` fires once the outcome is settled either way.
|
|
88
|
+
*/
|
|
89
|
+
private checkReadiness;
|
|
90
|
+
/** Creates the widget hidden; checkReadiness reveals it once every check passed. */
|
|
91
|
+
private mountWidget;
|
|
92
|
+
private clearRetry;
|
|
93
|
+
/**
|
|
94
|
+
* Maps `/sdk/config` rejections other than an unreachable server: missing
|
|
95
|
+
* Connected Channels becomes `no-agent`; anything else (an invalid key, a
|
|
96
|
+
* disallowed origin) is recorded as `state.error`.
|
|
84
97
|
*/
|
|
85
98
|
private handleConfigError;
|
|
86
99
|
private resolveVisitorGate;
|