@v-tilt/browser 1.13.0 → 1.13.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/dist/all-external-dependencies.js.map +1 -1
- package/dist/array.chat.js +2 -0
- package/dist/array.chat.js.map +1 -0
- package/dist/array.chat.no-external.js +2 -0
- package/dist/array.chat.no-external.js.map +1 -0
- package/dist/array.full.chat.js +2 -0
- package/dist/array.full.chat.js.map +1 -0
- package/dist/array.full.chat.no-external.js +2 -0
- package/dist/array.full.chat.no-external.js.map +1 -0
- package/dist/array.full.js +1 -1
- package/dist/array.full.js.map +1 -1
- package/dist/array.full.no-external.js +2 -0
- package/dist/array.full.no-external.js.map +1 -0
- package/dist/array.js +1 -1
- package/dist/array.js.map +1 -1
- package/dist/array.no-external.js +1 -1
- package/dist/array.no-external.js.map +1 -1
- package/dist/chat.js +1 -1
- package/dist/chat.js.map +1 -1
- package/dist/entrypoints/all-external-dependencies.d.ts +10 -3
- package/dist/entrypoints/array.chat.d.ts +10 -0
- package/dist/entrypoints/array.chat.no-external.d.ts +6 -0
- package/dist/entrypoints/array.full.chat.d.ts +13 -0
- package/dist/entrypoints/array.full.chat.no-external.d.ts +7 -0
- package/dist/entrypoints/array.full.d.ts +5 -9
- package/dist/entrypoints/array.full.no-external.d.ts +12 -0
- package/dist/entrypoints/module.chat.es.d.ts +7 -0
- package/dist/entrypoints/module.full.chat.es.d.ts +12 -0
- package/dist/entrypoints/module.full.es.d.ts +12 -0
- package/dist/entrypoints/module.no-external.es.d.ts +1 -0
- package/dist/extensions/chat/bubble-drag.d.ts +20 -5
- package/dist/extensions/chat/chat-wrapper.d.ts +8 -2
- package/dist/extensions/chat/chat.d.ts +21 -351
- package/dist/extensions/chat/controller/__tests__/fakes/ably-realtime-fake.d.ts +84 -0
- package/dist/extensions/chat/controller/ably-client.d.ts +160 -0
- package/dist/extensions/chat/controller/ably-handlers.d.ts +95 -0
- package/dist/extensions/chat/controller/ably-token.d.ts +67 -0
- package/dist/extensions/chat/controller/chat-controller.d.ts +194 -0
- package/dist/extensions/chat/controller/message-delivery-status.d.ts +6 -0
- package/dist/extensions/chat/controller/message-order.d.ts +12 -0
- package/dist/extensions/chat/controller/message-stream.d.ts +49 -0
- package/dist/extensions/chat/lib/bubble-offset.d.ts +18 -0
- package/dist/extensions/chat/lib/merge-chat-config.d.ts +3 -0
- package/dist/extensions/chat/normalize-send-content.d.ts +2 -0
- package/dist/extensions/chat/outbox/message-delivery.d.ts +17 -0
- package/dist/extensions/chat/outbox/message-outbox.d.ts +57 -0
- package/dist/extensions/chat/store/chat-store.d.ts +122 -0
- package/dist/extensions/chat/types.d.ts +1 -19
- package/dist/extensions/chat/ui/ChannelItem.d.ts +12 -0
- package/dist/extensions/chat/ui/ChannelListView.d.ts +14 -0
- package/dist/extensions/chat/ui/ChatBubble.d.ts +14 -0
- package/dist/extensions/chat/ui/ChatHeader.d.ts +13 -0
- package/dist/extensions/chat/ui/ChatPanel.d.ts +14 -0
- package/dist/extensions/chat/ui/ChatRoot.d.ts +31 -0
- package/dist/extensions/chat/ui/ClosedBanner.d.ts +7 -0
- package/dist/extensions/chat/ui/ConnectionBanner.d.ts +32 -0
- package/dist/extensions/chat/ui/ConversationView.d.ts +14 -0
- package/dist/extensions/chat/ui/MessageBubble.d.ts +25 -0
- package/dist/extensions/chat/ui/MessageInput.d.ts +14 -0
- package/dist/extensions/chat/ui/MessageList.d.ts +19 -0
- package/dist/extensions/chat/ui/NewMessagesPill.d.ts +13 -0
- package/dist/extensions/chat/ui/Skeletons.d.ts +14 -0
- package/dist/extensions/chat/ui/TypingBubble.d.ts +23 -0
- package/dist/extensions/chat/ui/TypingIndicator.d.ts +12 -0
- package/dist/extensions/chat/ui/WidgetSlot.d.ts +20 -0
- package/dist/extensions/chat/ui/hooks/use-auto-mark-read.d.ts +18 -0
- package/dist/extensions/chat/ui/hooks/use-scroll-preservation.d.ts +33 -0
- package/dist/extensions/chat/ui/icons.d.ts +18 -0
- package/dist/extensions/chat/ui/message-render.d.ts +18 -0
- package/dist/extensions/chat/ui/shadow-styles.d.ts +13 -0
- package/dist/extensions/chat/ui/utils/mobile-body-scroll-lock.d.ts +14 -0
- package/dist/extensions/chat/widget-registry.d.ts +21 -5
- package/dist/extensions/chat/widgets/collect-email.d.ts +4 -2
- package/dist/extensions/chat/widgets/escalate-to-human.d.ts +2 -1
- package/dist/external-scripts-loader.js +1 -1
- package/dist/external-scripts-loader.js.map +1 -1
- package/dist/feature.d.ts +1 -0
- package/dist/lib/merge-vtilt-config.d.ts +9 -0
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/module.chat.d.ts +1788 -0
- package/dist/module.chat.js +2 -0
- package/dist/module.chat.js.map +1 -0
- package/dist/module.d.ts +48 -3
- package/dist/module.full.chat.d.ts +1792 -0
- package/dist/module.full.chat.js +2 -0
- package/dist/module.full.chat.js.map +1 -0
- package/dist/module.full.d.ts +1793 -0
- package/dist/module.full.js +2 -0
- package/dist/module.full.js.map +1 -0
- package/dist/module.js +1 -1
- package/dist/module.js.map +1 -1
- package/dist/module.no-external.d.ts +48 -3
- package/dist/module.no-external.js +1 -1
- package/dist/module.no-external.js.map +1 -1
- package/dist/recorder.js.map +1 -1
- package/dist/snippet-stub-methods.d.ts +14 -0
- package/dist/utils/globals.d.ts +53 -27
- package/dist/utils/index.d.ts +8 -0
- package/dist/vtilt.d.ts +6 -1
- package/dist/web-vitals.js.map +1 -1
- package/package.json +74 -71
- package/dist/extensions/chat/chat-styles.d.ts +0 -27
- package/dist/extensions/chat/message-content-styles.d.ts +0 -1
- package/dist/extensions/chat/message-html.d.ts +0 -6
- package/dist/extensions/chat/message-markdown.d.ts +0 -8
- package/dist/extensions/ga4-proxy.d.ts +0 -59
- package/dist/utils/type-utils.d.ts +0 -4
- package/dist/web-vitals.d.ts +0 -81
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var t="undefined"!=typeof window?window:void 0,e="undefined"!=typeof globalThis?globalThis:t,n=null==e?void 0:e.navigator,i=null==e?void 0:e.document,r=null==e?void 0:e.location,s=null==e?void 0:e.fetch;t&&i&&i.createElement,null==e||e.XMLHttpRequest,null==e||e.AbortController;var o=null==n?void 0:n.userAgent,a=null!=t?t:{};function l(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(t){return void n(t)}a.done?e(l):Promise.resolve(l).then(i,r)}function u(t){return function(){var e=this,n=arguments;return new Promise(function(i,r){var s=t.apply(e,n);function o(t){l(s,i,r,o,a,"next",t)}function a(t){l(s,i,r,o,a,"throw",t)}o(void 0)})}}function h(){return h=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},h.apply(null,arguments)}var d="x-api-key";function c(t,e,n){void 0===n&&(n={});var{api_host:i,token:r}=t,s=""+(i?i.replace(/\/+$/gm,""):"")+e;if(n.includeTokenQuery&&r){var o=s.includes("?")?"&":"?";s=""+s+o+"token="+r}return s}function v(t){return t.token?{[d]:t.token}:{}}function f(t){return"string"==typeof t}function p(t){return void 0===t}function g(t){return null==t}function m(t){return Array.isArray(t)}function b(t){return"function"==typeof t}var y={none:0,error:1,warn:2,info:3,debug:4},w="[vTilt]",x=new Set(["none","error","warn","info","debug"]);function _(){return"undefined"!=typeof console}function k(t){var e=t.length>0&&"string"==typeof t[0]?t[0]:"",n=e?t.slice(1):t;return[e?w+":"+e:w,...n]}var S="warn",C=!1;var T=null;function A(){return T||(T={setLevel(t,e){void 0===e&&(e=!1),S=t,e&&(C=!0)},setLevelFromRemote(t){C||t&&x.has(t)&&(S=t)},getLevel:()=>S,isLockedByInit:()=>C,debug(){if(!(y[S]<y.debug)&&_()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.log(...k(e))}},info(){if(!(y[S]<y.info)&&_()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.log(...k(e))}},warn(){if(!(y[S]<y.warn)&&_()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.warn(...k(e))}},error(){if(!(y[S]<y.error)&&_()){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.error(...k(e))}}}),T}function E(t,e){void 0===e&&(e=!0);var n=void 0!==t.log_level||!!t.debug,i=function(t){return t.log_level&&x.has(t.log_level)?t.log_level:t.debug?"debug":"warn"}(t);return A().setLevel(i,e&&n),i}function I(t,e){try{return t()}catch(t){return e}}class M{constructor(){this.k=new Map,this.C=new Map}on(t,e){return this.k.has(t)||this.k.set(t,new Set),this.k.get(t).add(e),()=>{var n;null===(n=this.k.get(t))||void 0===n||n.delete(e)}}once(t,e){return this.C.has(t)||this.C.set(t,new Set),this.C.get(t).add(e),()=>{var n;null===(n=this.C.get(t))||void 0===n||n.delete(e)}}emit(t,e){var n,i;null===(n=this.k.get(t))||void 0===n||n.forEach(n=>{try{n(e)}catch(e){A().error("emitter",'error in event listener for "'+t+'":',e)}});var r=this.C.get(t);r&&(r.forEach(n=>{try{n(e)}catch(e){A().error("emitter",'error in once listener for "'+t+'":',e)}}),this.C.delete(t)),null===(i=this.k.get("*"))||void 0===i||i.forEach(n=>{try{n({event:t,payload:e})}catch(t){A().error("emitter","error in wildcard listener:",t)}})}off(t){t?(this.k.delete(t),this.C.delete(t)):(this.k.clear(),this.C.clear())}listenerCount(t){var e,n,i,r;return(null!==(n=null===(e=this.k.get(t))||void 0===e?void 0:e.size)&&void 0!==n?n:0)+(null!==(r=null===(i=this.C.get(t))||void 0===i?void 0:i.size)&&void 0!==r?r:0)}hasListeners(t){return this.listenerCount(t)>0}}var O="sdk:initialized",P="sdk:config_updated",R="sdk:remote_config_loaded",D="consent:updated",U="event:captured",j="recording:started",B="recording:stopped",N=0,L=!1,z=!1;function q(t){(N+=1)<2||(L=!0,z||(z=!0,A().warn(t,"vTilt network requests are being cancelled before reaching the server (likely an ad blocker, privacy extension, or DNS-level filter). Further retries and snapshots have been suspended for this page. Route SDK traffic through your own domain to avoid this — see https://www.vtilt.com/docs/browser/reverse-proxy.")))}function F(){N=0}function H(){return L}var W="23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function J(t){for(var e=(2<<31-Math.clz32(57))-1,n=Math.ceil(1.6*e*t/57),i="";i.length<t;)for(var r=crypto.getRandomValues(new Uint8Array(n)),s=0;s<n&&i.length<t;s++){var o=r[s]&e;o<57&&(i+=W[o])}return i}var V=1048576;function K(t,e,n){if(t)if(Array.isArray(t))t.forEach((t,i)=>{e.call(n,t,i)});else for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.call(n,t[i],i)}function G(t,e,n,i){var{capture:r=!1,passive:s=!0}=null!=i?i:{};null==t||t.addEventListener(e,n,{capture:r,passive:s})}function X(t,e){if(!e)return t;for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}function Q(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];for(var r of n)for(var s of r)t.push(s);return t}function Z(t){var e={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var i=t[n];null!=i&&""!==i&&(e[n]=i)}return e}var Y="/api/chat/widget/channels",tt=t=>"/api/chat/widget/channels/"+t+"/messages",et=t=>"/api/chat/widget/channels/"+t+"/read",nt="/api/chat/token/widget";function it(t,e,n){return rt.apply(this,arguments)}function rt(){return(rt=u(function*(t,e,n){void 0===n&&(n={});var i=t.getConfig(),r=c(i,e);try{var s=yield fetch(r,h({},n,{headers:h({"Content-Type":"application/json"},v(i),n.headers)}));if(!s.ok)throw new Error("API error: "+s.status);return yield s.json()}catch(t){return A().error("chat","API request failed:",t),null}})).apply(this,arguments)}var st="rich_format",ot="markdown",at=/^[a-zA-Z0-9_-]{1,64}$/;function lt(t){return"user"===t.sender_type?function(t){var e;return"html"===t.content_type||(null===(e=t.metadata)||void 0===e?void 0:e[st])===ot}(t):"ai"===t.sender_type||"agent"===t.sender_type}function ut(t,e){var n,i=function(t){return"string"==typeof t?{raw:t,format:"text"}:"markdown"in t?{raw:t.markdown,format:"markdown"}:"html"in t?{raw:t.html,format:"html"}:"text"in t?{raw:t.text,format:"text"}:null}(t);if(!i)return null;var r="string"==typeof t?null!==(n=null==e?void 0:e.format)&&void 0!==n?n:"text":i.format,s=i.raw.trim();if(!s)return null;var o={};if(null==e?void 0:e.source){var a=function(t){var e=t.trim();if(at.test(e))return e}(e.source);a&&(o.message_source=a)}return"html"===r?{content:s,content_type:"html",metadata:o}:"markdown"===r?(o[st]=ot,{content:s,content_type:"text",metadata:o}):{content:s,content_type:"text",metadata:o}}var ht="$channel_message";class dt{constructor(){this.T=new Map}register(t){this.T.has(t.type)||this.T.set(t.type,t)}get(t){return this.T.get(t)}getAll(){return Array.from(this.T.values())}getToolDefinitions(){var t={};for(var e of this.T.values())t[e.type]={description:e.toolDescription,parameters:e.parameters};return t}}var ct,vt,ft,pt,gt,mt,bt,yt,wt,xt,_t,kt,St,Ct,Tt,At={},Et=[],It=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Mt=Array.isArray;function Ot(t,e){for(var n in e)t[n]=e[n];return t}function Pt(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Rt(t,e,n){var i,r,s,o={};for(s in e)"key"==s?i=e[s]:"ref"==s?r=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?ct.call(arguments,2):n),"function"==typeof t&&null!=t.defaultProps)for(s in t.defaultProps)void 0===o[s]&&(o[s]=t.defaultProps[s]);return Dt(t,o,i,r,null)}function Dt(t,e,n,i,r){var s={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++ft:r,__i:-1,__u:0};return null==r&&null!=vt.vnode&&vt.vnode(s),s}function Ut(t){return t.children}function jt(t,e){this.props=t,this.context=e}function $(t,e){if(null==e)return t.__?$(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if(null!=(n=t.__k[e])&&null!=n.__e)return n.__e;return"function"==typeof t.type?$(t):null}function Bt(t){if(t.__P&&t.__d){var e=t.__v,n=e.__e,i=[],r=[],s=Ot({},e);s.__v=e.__v+1,vt.vnode&&vt.vnode(s),Kt(t.__P,s,e,t.__n,t.__P.namespaceURI,32&e.__u?[n]:null,i,null==n?$(e):n,!!(32&e.__u),r),s.__v=e.__v,s.__.__k[s.__i]=s,Xt(i,s,r),e.__e=e.__=null,s.__e!=n&&Nt(s)}}function Nt(t){if(null!=(t=t.__)&&null!=t.__c)return t.__e=t.__c.base=null,t.__k.some(function(e){if(null!=e&&null!=e.__e)return t.__e=t.__c.base=e.__e}),Nt(t)}function Lt(t){(!t.__d&&(t.__d=!0)&>.push(t)&&!$t.__r++||mt!=vt.debounceRendering)&&((mt=vt.debounceRendering)||bt)($t)}function $t(){try{for(var t,e=1;gt.length;)gt.length>e&>.sort(yt),t=gt.shift(),e=gt.length,Bt(t)}finally{gt.length=$t.__r=0}}function zt(t,e,n,i,r,s,o,a,l,u,h){var d,c,v,f,p,g,m,b=i&&i.__k||Et,y=e.length;for(l=function(t,e,n,i,r){var s,o,a,l,u,h=n.length,d=h,c=0;for(t.__k=new Array(r),s=0;s<r;s++)null!=(o=e[s])&&"boolean"!=typeof o&&"function"!=typeof o?("string"==typeof o||"number"==typeof o||"bigint"==typeof o||o.constructor==String?o=t.__k[s]=Dt(null,o,null,null,null):Mt(o)?o=t.__k[s]=Dt(Ut,{children:o},null,null,null):void 0===o.constructor&&o.__b>0?o=t.__k[s]=Dt(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):t.__k[s]=o,l=s+c,o.__=t,o.__b=t.__b+1,a=null,-1!=(u=o.__i=Ht(o,n,l,d))&&(d--,(a=n[u])&&(a.__u|=2)),null==a||null==a.__v?(-1==u&&(r>h?c--:r<h&&c++),"function"!=typeof o.type&&(o.__u|=4)):u!=l&&(u==l-1?c--:u==l+1?c++:(u>l?c--:c++,o.__u|=4))):t.__k[s]=null;if(d)for(s=0;s<h;s++)null!=(a=n[s])&&!(2&a.__u)&&(a.__e==i&&(i=$(a)),te(a,a));return i}(n,e,b,l,y),d=0;d<y;d++)null!=(v=n.__k[d])&&(c=-1!=v.__i&&b[v.__i]||At,v.__i=d,g=Kt(t,v,c,r,s,o,a,l,u,h),f=v.__e,v.ref&&c.ref!=v.ref&&(c.ref&&Yt(c.ref,null,v),h.push(v.ref,v.__c||f,v)),null==p&&null!=f&&(p=f),(m=!!(4&v.__u))||c.__k===v.__k?(l=qt(v,l,t,m),m&&c.__e&&(c.__e=null)):"function"==typeof v.type&&void 0!==g?l=g:f&&(l=f.nextSibling),v.__u&=-7);return n.__e=p,l}function qt(t,e,n,i){var r,s;if("function"==typeof t.type){for(r=t.__k,s=0;r&&s<r.length;s++)r[s]&&(r[s].__=t,e=qt(r[s],e,n,i));return e}t.__e!=e&&(i&&(e&&t.type&&!e.parentNode&&(e=$(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do{e=e&&e.nextSibling}while(null!=e&&8==e.nodeType);return e}function Ft(t,e){return e=e||[],null==t||"boolean"==typeof t||(Mt(t)?t.some(function(t){Ft(t,e)}):e.push(t)),e}function Ht(t,e,n,i){var r,s,o,a=t.key,l=t.type,u=e[n],h=null!=u&&!(2&u.__u);if(null===u&&null==a||h&&a==u.key&&l==u.type)return n;if(i>(h?1:0))for(r=n-1,s=n+1;r>=0||s<e.length;)if(null!=(u=e[o=r>=0?r--:s++])&&!(2&u.__u)&&a==u.key&&l==u.type)return o;return-1}function Wt(t,e,n){"-"==e[0]?t.setProperty(e,null==n?"":n):t[e]=null==n?"":"number"!=typeof n||It.test(e)?n:n+"px"}function Jt(t,e,n,i,r){var s,o;t:if("style"==e)if("string"==typeof n)t.style.cssText=n;else{if("string"==typeof i&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Wt(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Wt(t.style,e,n[e])}else if("o"==e[0]&&"n"==e[1])s=e!=(e=e.replace(kt,"$1")),o=e.toLowerCase(),e=o in t||"onFocusOut"==e||"onFocusIn"==e?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?i?n[_t]=i[_t]:(n[_t]=St,t.addEventListener(e,s?Tt:Ct,s)):t.removeEventListener(e,s?Tt:Ct,s);else{if("http://www.w3.org/2000/svg"==r)e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=e&&"height"!=e&&"href"!=e&&"list"!=e&&"form"!=e&&"tabIndex"!=e&&"download"!=e&&"rowSpan"!=e&&"colSpan"!=e&&"role"!=e&&"popover"!=e&&e in t)try{t[e]=null==n?"":n;break t}catch(t){}"function"==typeof n||(null==n||!1===n&&"-"!=e[4]?t.removeAttribute(e):t.setAttribute(e,"popover"==e&&1==n?"":n))}}function Vt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(null==e[xt])e[xt]=St++;else if(e[xt]<n[_t])return;return n(vt.event?vt.event(e):e)}}}function Kt(t,e,n,i,r,s,o,a,l,u){var h,d,c,v,f,p,g,m,b,y,$,w,x,_,k,S=e.type;if(void 0!==e.constructor)return null;128&n.__u&&(l=!!(32&n.__u),s=[a=e.__e=n.__e]),(h=vt.__b)&&h(e);t:if("function"==typeof S)try{if(m=e.props,b=S.prototype&&S.prototype.render,y=(h=S.contextType)&&i[h.__c],$=h?y?y.props.value:h.__:i,n.__c?g=(d=e.__c=n.__c).__=d.__E:(b?e.__c=d=new S(m,$):(e.__c=d=new jt(m,$),d.constructor=S,d.render=ee),y&&y.sub(d),d.state||(d.state={}),d.__n=i,c=d.__d=!0,d.__h=[],d._sb=[]),b&&null==d.__s&&(d.__s=d.state),b&&null!=S.getDerivedStateFromProps&&(d.__s==d.state&&(d.__s=Ot({},d.__s)),Ot(d.__s,S.getDerivedStateFromProps(m,d.__s))),v=d.props,f=d.state,d.__v=e,c)b&&null==S.getDerivedStateFromProps&&null!=d.componentWillMount&&d.componentWillMount(),b&&null!=d.componentDidMount&&d.__h.push(d.componentDidMount);else{if(b&&null==S.getDerivedStateFromProps&&m!==v&&null!=d.componentWillReceiveProps&&d.componentWillReceiveProps(m,$),e.__v==n.__v||!d.__e&&null!=d.shouldComponentUpdate&&!1===d.shouldComponentUpdate(m,d.__s,$)){e.__v!=n.__v&&(d.props=m,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(t){t&&(t.__=e)}),Et.push.apply(d.__h,d._sb),d._sb=[],d.__h.length&&o.push(d);break t}null!=d.componentWillUpdate&&d.componentWillUpdate(m,d.__s,$),b&&null!=d.componentDidUpdate&&d.__h.push(function(){d.componentDidUpdate(v,f,p)})}if(d.context=$,d.props=m,d.__P=t,d.__e=!1,w=vt.__r,x=0,b)d.state=d.__s,d.__d=!1,w&&w(e),h=d.render(d.props,d.state,d.context),Et.push.apply(d.__h,d._sb),d._sb=[];else do{d.__d=!1,w&&w(e),h=d.render(d.props,d.state,d.context),d.state=d.__s}while(d.__d&&++x<25);d.state=d.__s,null!=d.getChildContext&&(i=Ot(Ot({},i),d.getChildContext())),b&&!c&&null!=d.getSnapshotBeforeUpdate&&(p=d.getSnapshotBeforeUpdate(v,f)),_=null!=h&&h.type===Ut&&null==h.key?Qt(h.props.children):h,a=zt(t,Mt(_)?_:[_],e,n,i,r,s,o,a,l,u),d.base=e.__e,e.__u&=-161,d.__h.length&&o.push(d),g&&(d.__E=d.__=null)}catch(t){if(e.__v=null,l||null!=s)if(t.then){for(e.__u|=l?160:128;a&&8==a.nodeType&&a.nextSibling;)a=a.nextSibling;s[s.indexOf(a)]=null,e.__e=a}else{for(k=s.length;k--;)Pt(s[k]);Gt(e)}else e.__e=n.__e,e.__k=n.__k,t.then||Gt(e);vt.__e(t,e,n)}else null==s&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Zt(n.__e,e,n,i,r,s,o,l,u);return(h=vt.diffed)&&h(e),128&e.__u?void 0:a}function Gt(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(Gt))}function Xt(t,e,n){for(var i=0;i<n.length;i++)Yt(n[i],n[++i],n[++i]);vt.__c&&vt.__c(e,t),t.some(function(e){try{t=e.__h,e.__h=[],t.some(function(t){t.call(e)})}catch(t){vt.__e(t,e.__v)}})}function Qt(t){return"object"!=typeof t||null==t||t.__b>0?t:Mt(t)?t.map(Qt):void 0!==t.constructor?null:Ot({},t)}function Zt(t,e,n,i,r,s,o,a,l){var u,h,d,c,v,f,p,g=n.props||At,m=e.props,b=e.type;if("svg"==b?r="http://www.w3.org/2000/svg":"math"==b?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=s)for(u=0;u<s.length;u++)if((v=s[u])&&"setAttribute"in v==!!b&&(b?v.localName==b:3==v.nodeType)){t=v,s[u]=null;break}if(null==t){if(null==b)return document.createTextNode(m);t=document.createElementNS(r,b,m.is&&m),a&&(vt.__m&&vt.__m(e,s),a=!1),s=null}if(null==b)g===m||a&&t.data==m||(t.data=m);else{if(s="textarea"==b&&null!=m.defaultValue?null:s&&ct.call(t.childNodes),!a&&null!=s)for(g={},u=0;u<t.attributes.length;u++)g[(v=t.attributes[u]).name]=v.value;for(u in g)v=g[u],"dangerouslySetInnerHTML"==u?d=v:"children"==u||u in m||"value"==u&&"defaultValue"in m||"checked"==u&&"defaultChecked"in m||Jt(t,u,null,v,r);for(u in m)v=m[u],"children"==u?c=v:"dangerouslySetInnerHTML"==u?h=v:"value"==u?f=v:"checked"==u?p=v:a&&"function"!=typeof v||g[u]===v||Jt(t,u,v,g[u],r);if(h)a||d&&(h.__html==d.__html||h.__html==t.innerHTML)||(t.innerHTML=h.__html),e.__k=[];else if(d&&(t.innerHTML=""),zt("template"==e.type?t.content:t,Mt(c)?c:[c],e,n,i,"foreignObject"==b?"http://www.w3.org/1999/xhtml":r,s,o,s?s[0]:n.__k&&$(n,0),a,l),null!=s)for(u=s.length;u--;)Pt(s[u]);a&&"textarea"!=b||(u="value","progress"==b&&null==f?t.removeAttribute("value"):null!=f&&(f!==t[u]||"progress"==b&&!f||"option"==b&&f!=g[u])&&Jt(t,u,f,g[u],r),u="checked",null!=p&&p!=t[u]&&Jt(t,u,p,g[u],r))}return t}function Yt(t,e,n){try{if("function"==typeof t){var i="function"==typeof t.__u;i&&t.__u(),i&&null==e||(t.__u=t(e))}else t.current=e}catch(t){vt.__e(t,n)}}function te(t,e,n){var i,r;if(vt.unmount&&vt.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||Yt(i,null,e)),null!=(i=t.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(t){vt.__e(t,e)}i.base=i.__P=null}if(i=t.__k)for(r=0;r<i.length;r++)i[r]&&te(i[r],e,n||"function"!=typeof t.type);n||Pt(t.__e),t.__c=t.__=t.__e=void 0}function ee(t,e,n){return this.constructor(t,n)}function ne(t,e,n){var i,r,s;e==document&&(e=document.documentElement),vt.__&&vt.__(t,e),i=!1?null:e.__k,r=[],s=[],Kt(e,t=e.__k=Rt(Ut,null,[t]),i||At,At,e.namespaceURI,i?null:e.firstChild?ct.call(e.childNodes):null,r,i?i.__e:e.firstChild,false,s),Xt(r,t,s)}ct=Et.slice,vt={__e:function(t,e,n,i){for(var r,s,o;e=e.__;)if((r=e.__c)&&!r.__)try{if((s=r.constructor)&&null!=s.getDerivedStateFromError&&(r.setState(s.getDerivedStateFromError(t)),o=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(t,i||{}),o=r.__d),o)return r.__E=r}catch(e){t=e}throw t}},ft=0,pt=function(t){return null!=t&&void 0===t.constructor},jt.prototype.setState=function(t,e){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=Ot({},this.state),"function"==typeof t&&(t=t(Ot({},n),this.props)),t&&Ot(n,t),null!=t&&this.__v&&(e&&this._sb.push(e),Lt(this))},jt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Lt(this))},jt.prototype.render=Ut,gt=[],bt="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,yt=function(t,e){return t.__v.__b-e.__v.__b},$t.__r=0,wt=Math.random().toString(8),xt="__d"+wt,_t="__a"+wt,kt=/(PointerCapture)$|Capture$/i,St=0,Ct=Vt(!1),Tt=Vt(!0);var ie=0;function re(t,e,n,i,r,s){e||(e={});var o,a,l=e;if("ref"in l)for(a in l={},e)"ref"==a?o=e[a]:l[a]=e[a];var u={type:t,props:l,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ie,__i:-1,__u:0,__source:r,__self:s};if("function"==typeof t&&(o=t.defaultProps))for(a in o)void 0===l[a]&&(l[a]=o[a]);return vt.vnode&&vt.vnode(u),u}var se,oe,ae,le,ue=0,he=[],de=vt,ce=de.__b,ve=de.__r,fe=de.diffed,pe=de.__c,ge=de.unmount,me=de.__;function be(t,e){de.__h&&de.__h(oe,t,ue||e),ue=0;var n=oe.__H||(oe.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function ye(t){return ue=1,function(t,e,n){var i=be(se++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Me(void 0,e),function(t){var e=i.__N?i.__N[0]:i.__[0],n=i.t(e,t);e!==n&&(i.__N=[n,i.__[1]],i.__c.setState({}))}],i.__c=oe,!oe.__f)){var r=function(t,e,n){if(!i.__c.__H)return!0;var r=i.__c.__H.__.filter(function(t){return t.__c});if(r.every(function(t){return!t.__N}))return!s||s.call(this,t,e,n);var o=i.__c.props!==t;return r.some(function(t){if(t.__N){var e=t.__[0];t.__=t.__N,t.__N=void 0,e!==t.__[0]&&(o=!0)}}),s&&s.call(this,t,e,n)||o};oe.__f=!0;var s=oe.shouldComponentUpdate,o=oe.componentWillUpdate;oe.componentWillUpdate=function(t,e,n){if(this.__e){var i=s;s=void 0,r(t,e,n),s=i}o&&o.call(this,t,e,n)},oe.shouldComponentUpdate=r}return i.__N||i.__}(Me,t)}function we(t,e){var n=be(se++,3);!de.__s&&Ie(n.__H,e)&&(n.__=t,n.u=e,oe.__H.__h.push(n))}function xe(t){return ue=5,_e(function(){return{current:t}},[])}function _e(t,e){var n=be(se++,7);return Ie(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function ke(t,e){return ue=8,_e(function(){return t},e)}function Se(){for(var t;t=he.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(Ae),e.__h.some(Ee),e.__h=[]}catch(n){e.__h=[],de.__e(n,t.__v)}}}de.__b=function(t){oe=null,ce&&ce(t)},de.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),me&&me(t,e)},de.__r=function(t){ve&&ve(t),se=0;var e=(oe=t.__c).__H;e&&(ae===oe?(e.__h=[],oe.__h=[],e.__.some(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.some(Ae),e.__h.some(Ee),e.__h=[],se=0)),ae=oe},de.diffed=function(t){fe&&fe(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(1!==he.push(e)&&le===de.requestAnimationFrame||((le=de.requestAnimationFrame)||Te)(Se)),e.__H.__.some(function(t){t.u&&(t.__H=t.u),t.u=void 0})),ae=oe=null},de.__c=function(t,e){e.some(function(t){try{t.__h.some(Ae),t.__h=t.__h.filter(function(t){return!t.__||Ee(t)})}catch(n){e.some(function(t){t.__h&&(t.__h=[])}),e=[],de.__e(n,t.__v)}}),pe&&pe(t,e)},de.unmount=function(t){ge&&ge(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.some(function(t){try{Ae(t)}catch(t){e=t}}),n.__H=void 0,e&&de.__e(e,n.__v))};var Ce="function"==typeof requestAnimationFrame;function Te(t){var e,n=function(){clearTimeout(i),Ce&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Ce&&(e=requestAnimationFrame(n))}function Ae(t){var e=oe,n=t.__c;"function"==typeof n&&(t.__c=void 0,n()),oe=e}function Ee(t){var e=oe;t.__c=t.__(),oe=e}function Ie(t,e){return!t||t.length!==e.length||e.some(function(e,n){return e!==t[n]})}function Me(t,e){return"function"==typeof e?e(t):e}var Oe=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function Pe(t){var{prompt:e,ctx:n}=t,[i,r]=ye(""),[s,o]=ye(""),[a,l]=ye(!1),h=Oe.test(s.trim())&&!a,d=function(){var t=u(function*(){if(h){l(!0);try{yield n.dispatch("submit",{email:s.trim(),name:i.trim()})}finally{l(!1)}}});return function(){return t.apply(this,arguments)}}();return re("div",{class:"vt-widget",children:[re("p",{children:e}),re("div",{style:"display: flex; flex-direction: column; gap: 8px;",children:[re("input",{type:"text",class:"vt-widget-input",placeholder:"Your name",value:i,onInput:t=>r(t.currentTarget.value),disabled:a}),re("div",{style:"display: flex; gap: 8px; align-items: center;",children:[re("input",{type:"email",class:"vt-widget-input",style:"flex: 1; min-width: 0; margin: 0;",placeholder:"your@email.com",value:s,onInput:t=>o(t.currentTarget.value),onKeyDown:t=>{"Enter"===t.key&&(t.preventDefault(),d())},disabled:a}),re("button",{type:"button",class:"vt-widget-btn","data-style":"outline",onClick:()=>{d()},disabled:!h,children:"Submit"})]})]})]})}var Re={type:"collect_email",toolDescription:"ALWAYS use this tool instead of asking for email in plain text. Renders an interactive form to collect the user's name and email. Use whenever the user wants follow-up, a demo, a meeting, pricing info, or shows buying intent. NEVER ask for name or email via plain text.",parameters:{prompt:{type:"string",description:"Message to show above the input fields"}},render:(t,e)=>re(Pe,{prompt:"string"==typeof t.prompt?t.prompt:"What's your name and email?",ctx:e}),onAction:(t,e,n)=>u(function*(){if("submit"!==t)return{};var i="string"==typeof e.email?e.email.trim():"";if(!i||!Oe.test(i))return{};var r=n.buildEndpointUrl("/api/chat/widget/channels/"+n.channelId+"/actions"),s=n.token?{"x-api-key":n.token,"Content-Type":"application/json"}:{"Content-Type":"application/json"};try{var o=yield fetch(r,{method:"POST",headers:s,body:JSON.stringify({widget_type:"collect_email",action:"submit",data:{email:i,name:"string"==typeof e.name?e.name.trim():""},channel_id:n.channelId,distinct_id:n.distinctId,message_id:n.messageId})});return{success:!!(yield o.json()).success}}catch(t){return{}}})()},De={fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function Ue(t){return re("svg",h({width:24,height:24,viewBox:"0 0 24 24"},De,t,{children:re("path",{d:"M18 6L6 18M6 6l12 12"})}))}function je(t){return re("svg",h({width:24,height:24,viewBox:"0 0 24 24"},De,t,{children:re("path",{d:"M15 18l-6-6 6-6"})}))}function Be(t){return re("svg",h({width:16,height:16,viewBox:"0 0 24 24",fill:"currentColor"},t,{children:re("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}))}function Ne(t){return re("svg",h({width:28,height:28,viewBox:"0 0 28 28",fill:"white"},t,{children:re("path",{d:"M14 3C7.925 3 3 7.262 3 12.5c0 2.56 1.166 4.884 3.063 6.606L4.5 24l5.25-2.625C11.1 21.79 12.52 22 14 22c6.075 0 11-4.262 11-9.5S20.075 3 14 3z"})}))}function Le(t){return re("svg",h({width:22,height:22,viewBox:"0 0 24 24",fill:"currentColor"},t,{children:re("path",{d:"M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1H2a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h1a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2M7.5 13A1.5 1.5 0 0 0 6 14.5A1.5 1.5 0 0 0 7.5 16A1.5 1.5 0 0 0 9 14.5A1.5 1.5 0 0 0 7.5 13m9 0a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 0 0 1.5 1.5a1.5 1.5 0 0 0 1.5-1.5a1.5 1.5 0 0 0-1.5-1.5"})}))}function $e(t){return re("svg",h({width:22,height:22,viewBox:"0 0 24 24",fill:"currentColor"},t,{children:re("path",{d:"M12 4a4 4 0 0 1 4 4a4 4 0 0 1-4 4a4 4 0 0 1-4-4a4 4 0 0 1 4-4m0 10c4.42 0 8 1.79 8 4v2H4v-2c0-2.21 3.58-4 8-4"})}))}function ze(t){return re("svg",h({width:36,height:36,viewBox:"0 0 24 24",fill:"white"},t,{children:re("path",{d:"M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"})}))}function qe(t){return re("svg",h({width:16,height:16,viewBox:"0 0 24 24"},De,t,{children:[re("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),re("circle",{cx:"12",cy:"7",r:"4"})]}))}function Fe(t){var{prompt:e,ctx:n}=t,[i,r]=ye(!1),s=function(){var t=u(function*(){if(!i){r(!0);try{yield n.dispatch("escalate",{})}finally{r(!1)}}});return function(){return t.apply(this,arguments)}}();return re("div",{class:"vt-widget",children:[re("p",{children:e}),re("button",{type:"button",class:"vt-widget-btn","data-style":"outline",onClick:()=>{s()},disabled:i,children:[re(qe,{}),"Connect with a person"]})]})}var He={type:"escalate_to_human",toolDescription:"Offer to connect the user with a human agent. Use when the user explicitly asks to speak with a person, when you cannot adequately help them, or when the conversation requires human judgment (billing, complaints, complex issues).",parameters:{prompt:{type:"string",description:"Message to show above the connect button"}},render:(t,e)=>re(Fe,{prompt:"string"==typeof t.prompt?t.prompt:"Would you like me to connect you with a team member?",ctx:e}),onAction:(t,e,n)=>u(function*(){if("escalate"!==t)return{};var e=n.buildEndpointUrl("/api/chat/widget/channels/"+n.channelId+"/actions"),i=n.token?{"x-api-key":n.token,"Content-Type":"application/json"}:{"Content-Type":"application/json"};try{var r=yield fetch(e,{method:"POST",headers:i,body:JSON.stringify({widget_type:"escalate_to_human",action:"escalate",data:{},channel_id:n.channelId,distinct_id:n.distinctId,message_id:n.messageId})});return{success:!!(yield r.json()).success}}catch(t){return{}}})()},We=Symbol.for("preact-signals");function Je(){if(Qe>1)Qe--;else{var t,e=!1;for(!function(){var t=Ye;for(Ye=void 0;void 0!==t;)t.S.v===t.v&&(t.S.i=t.i),t=t.o}();void 0!==Xe;){var n=Xe;for(Xe=void 0,Ze++;void 0!==n;){var i=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&sn(n))try{n.c()}catch(n){e||(t=n,e=!0)}n=i}}if(Ze=0,Qe--,e)throw t}}var Ve=void 0;function Ke(t){var e=Ve;Ve=void 0;try{return t()}finally{Ve=e}}var Ge,Xe=void 0,Qe=0,Ze=0,Ye=void 0,tn=0;function en(t){if(void 0!==Ve){var e=t.n;if(void 0===e||e.t!==Ve)return e={i:0,S:t,p:Ve.s,n:void 0,t:Ve,e:void 0,x:void 0,r:e},void 0!==Ve.s&&(Ve.s.n=e),Ve.s=e,t.n=e,32&Ve.f&&t.S(e),e;if(-1===e.i)return e.i=0,void 0!==e.n&&(e.n.p=e.p,void 0!==e.p&&(e.p.n=e.n),e.p=Ve.s,e.n=void 0,Ve.s.n=e,Ve.s=e),e}}function nn(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=null==e?void 0:e.watched,this.Z=null==e?void 0:e.unwatched,this.name=null==e?void 0:e.name}function rn(t,e){return new nn(t,e)}function sn(t){for(var e=t.s;void 0!==e;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function on(t){for(var e=t.s;void 0!==e;e=e.n){var n=e.S.n;if(void 0!==n&&(e.r=n),e.S.n=e,e.i=-1,void 0===e.n){t.s=e;break}}}function an(t){for(var e=t.s,n=void 0;void 0!==e;){var i=e.p;-1===e.i?(e.S.U(e),void 0!==i&&(i.n=e.n),void 0!==e.n&&(e.n.p=i)):n=e,e.S.n=e.r,void 0!==e.r&&(e.r=void 0),e=i}t.s=n}function ln(t,e){nn.call(this,void 0),this.x=t,this.s=void 0,this.g=tn-1,this.f=4,this.W=null==e?void 0:e.watched,this.Z=null==e?void 0:e.unwatched,this.name=null==e?void 0:e.name}function un(t,e){return new ln(t,e)}function hn(t){var e=t.m;if(t.m=void 0,"function"==typeof e){Qe++;var n=Ve;Ve=void 0;try{e()}catch(e){throw t.f&=-2,t.f|=8,dn(t),e}finally{Ve=n,Je()}}}function dn(t){for(var e=t.s;void 0!==e;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,hn(t)}function cn(t){if(Ve!==this)throw new Error("Out-of-order effect");an(this),Ve=t,this.f&=-2,8&this.f&&dn(this),Je()}function vn(t,e){this.x=t,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=null==e?void 0:e.name}function fn(t,e){var n=new vn(t,e);try{n.c()}catch(t){throw n.d(),t}var i=n.d.bind(n);return i[Symbol.dispose]=i,i}function pn(t,e){vt[t]=e.bind(null,vt[t]||function(){})}function gn(t){if(Ge){var e=Ge;Ge=void 0,e()}Ge=t&&t.S()}function mn(t){var e=this,n=t.data,i=function(t){return _e(function(){return rn(t)},[])}(n);i.value=n;var r=_e(function(){for(var t=e.__v;t=t.__;)if(t.__c){t.__c.__$f|=4;break}return e.__$u.c=function(){var t,n=e.__$u.S(),i=r.value;n(),pt(i)||3!==(null==(t=e.base)?void 0:t.nodeType)?(e.__$f|=1,e.setState({})):e.base.data=i},un(function(){var t=i.value.value;return 0===t?0:!0===t?"":t||""})},[]);return r.value}function bn(t,e,n,i){var r=e in t&&void 0===t.ownerSVGElement,s=rn(n);return{o:function(t,e){s.value=t,i=e},d:fn(function(){var n=s.value.value;i[e]!==n&&(i[e]=n,r?t[e]=n:n?t.setAttribute(e,n):t.removeAttribute(e))})}}nn.prototype.brand=We,nn.prototype.h=function(){return!0},nn.prototype.S=function(t){var e=this,n=this.t;n!==t&&void 0===t.e&&(t.x=n,this.t=t,void 0!==n?n.e=t:Ke(function(){var t;null==(t=e.W)||t.call(e)}))},nn.prototype.U=function(t){var e=this;if(void 0!==this.t){var n=t.e,i=t.x;void 0!==n&&(n.x=i,t.e=void 0),void 0!==i&&(i.e=n,t.x=void 0),t===this.t&&(this.t=i,void 0===i&&Ke(function(){var t;null==(t=e.Z)||t.call(e)}))}},nn.prototype.subscribe=function(t){var e=this;return fn(function(){var n=e.value,i=Ve;Ve=void 0;try{t(n)}finally{Ve=i}},{name:"sub"})},nn.prototype.valueOf=function(){return this.value},nn.prototype.toString=function(){return this.value+""},nn.prototype.toJSON=function(){return this.value},nn.prototype.peek=function(){var t=this;return Ke(function(){return t.value})},Object.defineProperty(nn.prototype,"value",{get:function(){var t=en(this);return void 0!==t&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(Ze>100)throw new Error("Cycle detected");!function(t){0!==Qe&&0===Ze&&0!==t.l&&(t.l=0,Ye={S:t,v:t.v,i:t.i,o:Ye})}(this),this.v=t,this.i++,tn++,Qe++;try{for(var e=this.t;void 0!==e;e=e.x)e.t.N()}finally{Je()}}}}),ln.prototype=new nn,ln.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if(32==(36&this.f))return!0;if(this.f&=-5,this.g===tn)return!0;if(this.g=tn,this.f|=1,this.i>0&&!sn(this))return this.f&=-2,!0;var t=Ve;try{on(this),Ve=this;var e=this.x();(16&this.f||this.v!==e||0===this.i)&&(this.v=e,this.f&=-17,this.i++)}catch(t){this.v=t,this.f|=16,this.i++}return Ve=t,an(this),this.f&=-2,!0},ln.prototype.S=function(t){if(void 0===this.t){this.f|=36;for(var e=this.s;void 0!==e;e=e.n)e.S.S(e)}nn.prototype.S.call(this,t)},ln.prototype.U=function(t){if(void 0!==this.t&&(nn.prototype.U.call(this,t),void 0===this.t)){this.f&=-33;for(var e=this.s;void 0!==e;e=e.n)e.S.U(e)}},ln.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;void 0!==t;t=t.x)t.t.N()}},Object.defineProperty(ln.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=en(this);if(this.h(),void 0!==t&&(t.i=this.i),16&this.f)throw this.v;return this.v}}),vn.prototype.c=function(){var t=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var e=this.x();"function"==typeof e&&(this.m=e)}finally{t()}},vn.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,hn(this),on(this),Qe++;var t=Ve;return Ve=this,cn.bind(this,t)},vn.prototype.N=function(){2&this.f||(this.f|=2,this.u=Xe,Xe=this)},vn.prototype.d=function(){this.f|=8,1&this.f||dn(this)},vn.prototype.dispose=function(){this.d()},mn.displayName="_st",Object.defineProperties(nn.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:mn},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),pn("__b",function(t,e){if("string"==typeof e.type){var n,i=e.props;for(var r in i)if("children"!==r){var s=i[r];s instanceof nn&&(n||(e.__np=n={}),n[r]=s,i[r]=s.peek())}}t(e)}),pn("__r",function(t,e){t(e),gn();var n,i=e.__c;i&&(i.__$f&=-2,void 0===(n=i.__$u)&&(i.__$u=n=function(){var t;return fn(function(){t=this}),t.c=function(){i.__$f|=1,i.setState({})},t}())),gn(n)}),pn("__e",function(t,e,n,i){gn(),t(e,n,i)}),pn("diffed",function(t,e){var n;if(gn(),"string"==typeof e.type&&(n=e.__e)){var i=e.__np,r=e.props;if(i){var s=n.U;if(s)for(var o in s){var a=s[o];void 0===a||o in i||(a.d(),s[o]=void 0)}else n.U=s={};for(var l in i){var u=s[l],h=i[l];void 0===u?(u=bn(n,l,h,r),s[l]=u):u.o(h,r)}}}t(e)}),pn("unmount",function(t,e){if("string"==typeof e.type){var n=e.__e;if(n){var i=n.U;if(i)for(var r in n.U=void 0,i){var s=i[r];s&&s.d()}}}else{var o=e.__c;if(o){var a=o.__$u;a&&(o.__$u=void 0,a.d())}}t(e)}),pn("__h",function(t,e,n,i){(i<3||9===i)&&(e.__$f|=2),t(e,n,i)}),jt.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,i=n&&void 0!==n.s;for(var r in e)return!0;if(this.__f||"boolean"==typeof this.u&&!0===this.u){if(!(i||2&this.__$f||4&this.__$f))return!0;if(1&this.__$f)return!0}else{if(!(i||4&this.__$f))return!0;if(3&this.__$f)return!0}for(var s in t)if("__source"!==s&&t[s]!==this.props[s])return!0;for(var o in this.props)if(!(o in t))return!0;return!1};var yn={primaryColor:"#7B68EE",fontFamily:"'Inter var', 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",borderRadius:"12px"};class wn{constructor(){this.isOpen=rn(!1),this.isVisible=rn(!0),this.isLoading=rn(!1),this.currentView=rn("list"),this.channels=rn([]),this.channel=rn(null),this.messages=rn([]),this.isTyping=rn(!1),this.typingSender=rn(null),this.typingSenderType=rn(null),this.agentLastReadAt=rn(null),this.initialUserReadAt=rn(null),this.userScrolledUp=rn(!1),this.unreadNewMessagesCount=rn(0),this.theme=rn(h({},yn)),this.connectionState=rn("disconnected"),this.ablyProjectId=rn(null),this.realtimeChannelId=rn(null),this.realtimeAttached=rn(!1),this.pendingRealtimeChannelId=rn(null),this.identityChangeInFlight=rn(!1),this.lastConnectedDistinctId=rn(null),this.A=new Map,this.isConnected=un(()=>"connected"===this.connectionState.value),this.polledUnreadTotal=rn(null),this.unreadCount=un(()=>this.isOpen.value||null===this.polledUnreadTotal.value?this.channels.value.reduce((t,e)=>t+(e.unread_count||0),0):this.polledUnreadTotal.value),this.connectionBanner=un(()=>{var t=this.connectionState.value;return"suspended"===t?"reconnecting":"failed"===t?"failed":"none"}),this.realtimeReady=un(()=>{var t=this.channel.value;return!!t&&("connected"===this.connectionState.value&&this.realtimeAttached.value&&this.realtimeChannelId.value===t.id)})}setMessages(t){this.messages.value=t}patchChannelSummary(t,e){var n=this.channels.value.findIndex(e=>e.id===t);if(-1!==n){var i=[...this.channels.value];i[n]=h({},i[n],e),i.sort((t,e)=>{var n=t.last_message_at||t.created_at,i=e.last_message_at||e.created_at;return new Date(i).getTime()-new Date(n).getTime()}),this.channels.value=i}}prependChannelSummary(t){this.channels.value.some(e=>e.id===t.id)||(this.channels.value=[t,...this.channels.value])}clearActiveChannel(){this.channel.value=null,this.messages.value=[],this.isTyping.value=!1,this.typingSender.value=null,this.typingSenderType.value=null,this.userScrolledUp.value=!1,this.unreadNewMessagesCount.value=0,this.realtimeChannelId.value=null,this.realtimeAttached.value=!1,this.pendingRealtimeChannelId.value=null,this.agentLastReadAt.value=null,this.initialUserReadAt.value=null}prepareChannelSwitch(){this.messages.value=[],this.isTyping.value=!1,this.typingSender.value=null,this.typingSenderType.value=null,this.userScrolledUp.value=!1,this.unreadNewMessagesCount.value=0,this.agentLastReadAt.value=null,this.initialUserReadAt.value=null}cacheMessages(t,e){if(t){var n=e.filter(t=>!t.id.startsWith("temp-"));for(this.A.delete(t),this.A.set(t,n);this.A.size>wn.MESSAGES_CACHE_LIMIT;){var i=this.A.keys().next().value;if(void 0===i)break;this.A.delete(i)}}}getCachedMessages(t){if(!t)return null;var e=this.A.get(t);return e?(this.A.delete(t),this.A.set(t,e),e):null}clearMessagesCache(){this.A.clear()}}wn.MESSAGES_CACHE_LIMIT=10;var xn={bottom:20,right:20,left:20};function _n(t,e){return void 0!==t&&Number.isFinite(t)?Math.max(0,t):e}function kn(t){return null===t?h({},xn):{bottom:_n(null==t?void 0:t.bottom,xn.bottom),right:_n(null==t?void 0:t.right,xn.right),left:_n(null==t?void 0:t.left,xn.left)}}function Sn(t,e,n){t.style.bottom=n.bottom+"px","bottom-right"===e?(t.style.right=n.right+"px",t.style.left=""):(t.style.left=n.left+"px",t.style.right="")}var Cn="vtilt-bubble-pos";function Tn(t){try{localStorage.setItem(Cn,JSON.stringify(t))}catch(t){}}function An(t,e,n){var i=t.getBoundingClientRect(),r=i.left-e,s=i.top-n,o=window.innerWidth-t.offsetWidth-r,a=-r,l=window.innerHeight-t.offsetHeight-s,u=-s;return{x:Math.min(Math.max(e,a),o),y:Math.min(Math.max(n,u),l)}}function En(t,e,n){t.style.transform="translate3d("+e+"px, "+n+"px, 0)"}function In(t,e){var n,i=null!==(n=null==e?void 0:e.handle)&&void 0!==n?n:t,r=null==e?void 0:e.onPositionChange,s=0,o=0,a=0,l=0,u=0,h=0,d=!1,c=!1,v=function(){try{var t=localStorage.getItem(Cn);if(!t)return null;var e=JSON.parse(t);if("number"==typeof e.x&&"number"==typeof e.y)return e}catch(t){}return null}();if(v){s=v.x,o=v.y;var f=t.style.transition;t.style.transition="none",En(t,s,o);var p=An(t,s,o);s=p.x,o=p.y,En(t,s,o),t.offsetHeight,t.style.transition=f}i.style.cursor="grab",i.style.touchAction="none";var g=e=>{0===e.button&&(d=!0,c=!1,a=e.clientX,l=e.clientY,u=s,h=o,i.setPointerCapture(e.pointerId),i.style.cursor="grabbing",t.style.transition="none")},m=e=>{if(d){var n=e.clientX-a,i=e.clientY-l;if(!(!c&&Math.abs(n)<5&&Math.abs(i)<5)){c=!0;var v={x:u+n,y:h+i},f=An(t,v.x,v.y);s=f.x,o=f.y,En(t,s,o),null==r||r()}}},b=()=>{d&&(d=!1,i.style.cursor="grab",t.style.transition="",c&&(Tn({x:s,y:o}),null==r||r()))},y=t=>{c&&(t.stopPropagation(),t.preventDefault(),c=!1)},w=()=>{var e=s,n=o,i=An(t,s,o);s=i.x,o=i.y,En(t,s,o),e===s&&n===o||Tn({x:s,y:o}),null==r||r()};return i.addEventListener("pointerdown",g),i.addEventListener("pointermove",m),i.addEventListener("pointerup",b),i.addEventListener("pointercancel",b),i.addEventListener("click",y,!0),window.addEventListener("resize",w),{destroy(){i.removeEventListener("pointerdown",g),i.removeEventListener("pointermove",m),i.removeEventListener("pointerup",b),i.removeEventListener("pointercancel",b),i.removeEventListener("click",y,!0),window.removeEventListener("resize",w)}}}function Mn(t){var{store:e,controller:n,bubbleRef:i}=t,r=e.unreadCount.value;return re("button",{type:"button",class:"vt-bubble",ref:i,onClick:()=>n.toggle(),"aria-label":"Open chat",children:[re(Ne,{}),re("span",{class:"vt-bubble-badge","data-visible":r>0?"true":"false",children:r>99?"99+":r})]})}function On(t){var{channel:e,onSelect:n}=t,i=e.unread_count>0,r=function(t){var e=new Date(t),n=Date.now()-e.getTime(),i=Math.floor(n/6e4),r=Math.floor(n/36e5),s=Math.floor(n/864e5);if(i<1)return"Just now";if(i<60)return i+"m ago";if(r<24)return r+"h ago";if(s<7)return s+"d ago";return e.toLocaleDateString()}(e.last_message_at||e.created_at),s=e.last_message_preview||"No messages yet",o="user"===e.last_message_sender?"You: ":"",a="closed"===e.status?" · Closed":"";return re("button",{type:"button",class:"vt-channel-item","data-channel-id":e.id,onClick:()=>n(e.id),children:[re("div",{class:"vt-channel-avatar","data-mode":e.ai_mode?"ai":"support",children:e.ai_mode?re(Le,{width:24,height:24}):re($e,{width:24,height:24})}),re("div",{class:"vt-channel-body",children:[re("div",{class:"vt-channel-row",children:[re("div",{class:"vt-channel-name","data-unread":i?"true":"false",children:e.ai_mode?"AI Assistant":"Support"}),re("div",{class:"vt-channel-time",children:r})]}),re("div",{class:"vt-channel-row",children:[re("div",{class:"vt-channel-preview","data-unread":i?"true":"false",children:[o,s,a]}),i&&re("div",{class:"vt-channel-unread",children:e.unread_count>99?"99+":e.unread_count})]})]})]})}function Pn(){return re("div",{style:"flex: 1; overflow: hidden;",children:[re(Rn,{}),re(Rn,{}),re(Rn,{}),re(Rn,{})]})}function Rn(){return re("div",{style:"padding: 14px 16px; display: flex; align-items: center; gap: 12px; border-bottom: 1px solid var(--vtilt-border-light); background: white;",children:[re("div",{class:"vt-skeleton-circle",style:"width: 48px; height: 48px; flex-shrink: 0;"}),re("div",{style:"flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8px;",children:[re("div",{class:"vt-skeleton",style:"height: 12px; width: 40%;"}),re("div",{class:"vt-skeleton",style:"height: 10px; width: 80%;"})]})]})}function Dn(){return re(Ut,{children:[re(Un,{direction:"in",widthPct:62,metaPx:92,height:40}),re(Un,{direction:"out",widthPct:42,metaPx:56,height:40}),re(Un,{direction:"in",widthPct:78,metaPx:76,height:60})]})}function Un(t){var{direction:e,widthPct:n,metaPx:i,height:r}=t;return re("div","in"===e?{style:"display: flex; gap: 10px; align-items: flex-end;",children:[re("div",{class:"vt-skeleton-circle",style:"width: 32px; height: 32px; flex-shrink: 0;"}),re("div",{style:"display: flex; flex-direction: column; align-items: flex-start; min-width: 0; max-width: 85%;",children:[re("div",{class:"vt-skeleton",style:"width: "+n+"%; min-width: 96px; height: "+r+"px; border-radius: 20px 20px 20px 4px;"}),re("div",{class:"vt-skeleton",style:"height: 10px; width: "+i+"px; margin-top: 8px; margin-left: 6px; border-radius: 4px;"})]})]}:{style:"display: flex; flex-direction: column; align-items: flex-end;",children:[re("div",{class:"vt-skeleton",style:"width: "+n+"%; min-width: 80px; max-width: 80%; height: "+r+"px; border-radius: 20px 20px 4px 20px;"}),re("div",{class:"vt-skeleton",style:"height: 10px; width: "+i+"px; margin-top: 8px; margin-right: 6px; border-radius: 4px;"})]})}function jn(t){var{store:e,controller:n}=t,i=e.channels.value,r=e.isLoading.value;return 0===i.length&&r?re(Pn,{}):0===i.length?re(Bn,{controller:n}):re(Ut,{children:[re("div",{class:"vt-list-root",children:i.map(t=>re(On,{channel:t,onSelect:t=>{n.selectChannel(t)}},t.id))}),re("div",{class:"vt-list-footer",children:re("button",{type:"button",class:"vt-new-channel-btn",onClick:()=>{n.createChannel()},children:["Send us a message",re(Be,{width:18,height:18})]})})]})}function Bn(t){var{controller:e}=t,n=e.config.greeting||"Hi! How can we help you today?";return re("div",{class:"vt-list-empty",children:[re("div",{class:"vt-list-empty-icon",children:re(ze,{})}),re("div",{class:"vt-list-empty-title",children:n}),re("div",{class:"vt-list-empty-subtitle",children:"Start a conversation with us"}),re("button",{type:"button",class:"vt-new-channel-btn",style:"width: auto; padding: 14px 28px;",onClick:()=>{e.createChannel()},children:["Send us a message",re(Be,{width:18,height:18})]})]})}function Nn(t){var e,n,i,{store:r,controller:s}=t;if("list"===r.currentView.value)return re("div",{class:"vt-header","data-view":"list",children:[re("div",{class:"vt-header-title",children:"Messages"}),re("button",{type:"button",class:"vt-iconbtn vt-header-close",onClick:()=>s.close(),"aria-label":"Close",children:re(Ue,{})})]});var o=null===(i=null!==(n=null===(e=r.channel.value)||void 0===e?void 0:e.ai_mode)&&void 0!==n?n:s.config.aiMode)||void 0===i||i;return re("div",{class:"vt-header","data-view":"conversation",children:[re("button",{type:"button",class:"vt-iconbtn vt-header-back",onClick:()=>s.goToChannelList(),"aria-label":"Back",children:re(je,{})}),re("div",{class:"vt-header-avatar","data-mode":o?"ai":"support",children:re(o?Le:$e,{})}),re("div",{class:"vt-header-info",children:[re("div",{class:"vt-header-name",children:o?"AI Assistant":"Support"}),re("div",{class:"vt-header-status",children:"Online"})]}),re("button",{type:"button",class:"vt-iconbtn vt-header-close",onClick:()=>s.close(),"aria-label":"Close",children:re(Ue,{})})]})}function Ln(){return re("div",{class:"vt-closed-banner",children:"This conversation has been closed."})}function $n(t){var{store:e}=t,n=e.connectionBanner.value,i=function(t,e){var[n,i]=ye(!1);return we(()=>{if(t){var n=setTimeout(()=>i(!0),e);return()=>clearTimeout(n)}i(!1)},[t,e]),n}("reconnecting"===n,2500),r=ke(()=>{"undefined"!=typeof window&&window.location.reload()},[]);return"failed"===n?re("div",{class:"vt-conn-banner","data-kind":"failed",role:"alert",children:[re("span",{class:"vt-conn-banner-icon","aria-hidden":"true",children:re("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[re("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z"}),re("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),re("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}),re("span",{class:"vt-conn-banner-text",children:"Connection lost"}),re("button",{type:"button",class:"vt-conn-banner-action",onClick:r,children:"Retry"})]}):i?re("div",{class:"vt-conn-banner","data-kind":"reconnecting",role:"status",children:[re("span",{class:"vt-conn-banner-dot","aria-hidden":"true"}),re("span",{class:"vt-conn-banner-text",children:"Reconnecting"})]}):null}function zn(t){var{store:e,controller:n}=t,[i,r]=ye(""),s=xe(null),o=null==e.channel.value,a=()=>{var t=i.trim();t&&(n.stopUserTyping(),n.sendMessage(t),r(""),s.current&&(s.current.style.height="",s.current.focus()))};return we(()=>{s.current&&function(t){t.style.height="auto";var e=120,n=60;t.style.height=Math.min(Math.max(t.scrollHeight,n),e)+"px"}(s.current)},[i]),re("div",{class:"vt-input-container","data-pending":o?"true":"false",children:re("div",{class:"vt-input-box",children:[re("textarea",{class:"vt-input-textarea",ref:s,rows:1,placeholder:o?"Starting conversation…":"Message...",autocomplete:"off",autocorrect:"on",autocapitalize:"sentences",disabled:o,value:i,onInput:t=>{var e=t.currentTarget.value;r(e),n.notifyUserTyping()},onBlur:()=>{n.stopUserTyping()},onKeyDown:t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),a())}}),re("button",{type:"button",class:"vt-input-send","data-active":i.trim().length>0?"true":"false",disabled:0===i.trim().length||o,onClick:a,"aria-label":"Send message",children:re(Be,{})})]})})}function qn(t,e){for(var n in t)if("__source"!==n&&!(n in e))return!0;for(var i in e)if("__source"!==i&&t[i]!==e[i])return!0;return!1}function Fn(t,e){this.props=t,this.context=e}function Hn(t,e){function n(t){var n=this.props.ref;return n!=t.ref&&n&&("function"==typeof n?n(null):n.current=null),e?!e(this.props,t)||n!=t.ref:qn(this.props,t)}function i(e){return this.shouldComponentUpdate=n,Rt(t,e)}return i.displayName="Memo("+(t.displayName||t.name)+")",i.__f=i.prototype.isReactComponent=!0,i.type=t,i}(Fn.prototype=new jt).isPureReactComponent=!0,Fn.prototype.shouldComponentUpdate=function(t,e){return qn(this.props,t)||qn(this.state,e)};var Wn=vt.__b;vt.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Wn&&Wn(t)};var Jn=vt.__e;vt.__e=function(t,e,n,i){if(t.then)for(var r,s=e;s=s.__;)if((r=s.__c)&&r.__c)return null==e.__e&&(e.__e=n.__e,e.__k=n.__k),r.__c(t,e);Jn(t,e,n,i)};var Vn=vt.unmount;function Kn(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(t){"function"==typeof t.__c&&t.__c()}),t.__c.__H=null),null!=(t=function(t,e){for(var n in e)t[n]=e[n];return t}({},t)).__c&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(t){return Kn(t,e,n)})),t}function Gn(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(t){return Gn(t,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function Xn(){this.__u=0,this.o=null,this.__b=null}function Qn(t){var e=t.__&&t.__.__c;return e&&e.__a&&e.__a(t)}function Zn(){this.i=null,this.l=null}vt.unmount=function(t){var e=t.__c;e&&(e.__z=!0),e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Vn&&Vn(t)},(Xn.prototype=new jt).__c=function(t,e){var n=e.__c,i=this;null==i.o&&(i.o=[]),i.o.push(n);var r=Qn(i.__v),s=!1,o=function(){s||i.__z||(s=!0,n.__R=null,r?r(l):l())};n.__R=o;var a=n.__P;n.__P=null;var l=function(){if(! --i.__u){if(i.state.__a){var t=i.state.__a;i.__v.__k[0]=Gn(t,t.__c.__P,t.__c.__O)}var e;for(i.setState({__a:i.__b=null});e=i.o.pop();)e.__P=a,e.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(o,o)},Xn.prototype.componentWillUnmount=function(){this.o=[]},Xn.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=Kn(this.__b,n,i.__O=i.__P)}this.__b=null}var r=e.__a&&Rt(Ut,null,t.fallback);return r&&(r.__u&=-33),[Rt(Ut,null,e.__a?null:t.children),r]};var Yn=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&("t"!==t.props.revealOrder[0]||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};(Zn.prototype=new jt).__a=function(t){var e=this,n=Qn(e.__v),i=e.l.get(t);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),Yn(e,t,i)):r()};n?n(s):s()}},Zn.prototype.render=function(t){this.i=null,this.l=new Map;var e=Ft(t.children);t.revealOrder&&"b"===t.revealOrder[0]&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},Zn.prototype.componentDidUpdate=Zn.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){Yn(t,n,e)})};var ti="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,ei=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,ni=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,ii=/[A-Z0-9]/g,ri="undefined"!=typeof document,si=function(t){return("undefined"!=typeof Symbol&&"symbol"==typeof Symbol()?/fil|che|rad/:/fil|che|ra/).test(t)};jt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(jt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var oi=vt.event;vt.event=function(t){return oi&&(t=oi(t)),t.persist=function(){},t.isPropagationStopped=function(){return this.cancelBubble},t.isDefaultPrevented=function(){return this.defaultPrevented},t.nativeEvent=t};var ai={configurable:!0,get:function(){return this.class}},li=vt.vnode;vt.vnode=function(t){"string"==typeof t.type&&function(t){var e=t.props,n=t.type,i={},r=-1==n.indexOf("-");for(var s in e){var o=e[s];if(!("value"===s&&"defaultValue"in e&&null==o||ri&&"children"===s&&"noscript"===n||"class"===s||"className"===s)){var a=s.toLowerCase();"defaultValue"===s&&"value"in e&&null==e.value?s="value":"download"===s&&!0===o?o="":"translate"===a&&"no"===o?o=!1:"o"===a[0]&&"n"===a[1]?"ondoubleclick"===a?s="ondblclick":"onchange"!==a||"input"!==n&&"textarea"!==n||si(e.type)?"onfocus"===a?s="onfocusin":"onblur"===a?s="onfocusout":ni.test(s)&&(s=a):a=s="oninput":r&&ei.test(s)?s=s.replace(ii,"-$&").toLowerCase():null===o&&(o=void 0),"oninput"===a&&i[s=a]&&(s="oninputCapture"),i[s]=o}}"select"==n&&(i.multiple&&Array.isArray(i.value)&&(i.value=Ft(e.children).forEach(function(t){t.props.selected=-1!=i.value.indexOf(t.props.value)})),null!=i.defaultValue&&(i.value=Ft(e.children).forEach(function(t){t.props.selected=i.multiple?-1!=i.defaultValue.indexOf(t.props.value):i.defaultValue==t.props.value}))),e.class&&!e.className?(i.class=e.class,Object.defineProperty(i,"className",ai)):e.className&&(i.class=i.className=e.className),t.props=i}(t),t.$$typeof=ti,li&&li(t)};var ui=vt.__r;vt.__r=function(t){ui&&ui(t),t.__c};var hi=vt.diffed;function di(t,e){var n=Date.parse(t.created_at),i=Date.parse(e.created_at);return n!==i?n-i:t.id.localeCompare(e.id)}function ci(t,e){return function(t){return t.length<2?t:[...t].sort(di)}([...t,e])}vt.diffed=function(t){hi&&hi(t);var e=t.props,n=t.__e;null!=n&&"textarea"===t.type&&"value"in e&&e.value!==n.value&&(n.value=null==e.value?"":e.value)};var vi="chat.stream",fi=/<!--vtilt:widget:([\s\S]*?)-->/g;function pi(t){for(var e,n,i=[],r=new RegExp(fi.source,"g");null!==(n=r.exec(t));)try{var s=JSON.parse(n[1]);s.type&&i.push({type:s.type,params:null!==(e=s.params)&&void 0!==e?e:{}})}catch(t){}return i}function gi(t){return mi.apply(this,arguments)}function mi(){return mi=u(function*(t){var e,n,i,{store:r,response:s,channelId:o,tempId:a,signal:l,isActive:u,onStreamStart:d,onComplete:c}=t,v=()=>{var t;return!(null==l?void 0:l.aborted)&&(null===(t=null==u?void 0:u())||void 0===t||t)},f=s.headers.get("X-Vtilt-Message-Id"),p=s.headers.get("X-Vtilt-Message-Created-At"),g=null!==(e=null!=a?a:f)&&void 0!==e?e:"temp-ai-"+Date.now();if(v()&&(null==d||d(g),v())){var m={id:g,channel_id:o,sender_type:"ai",sender_id:null,sender_name:"AI Assistant",sender_avatar_url:null,content:"",content_type:"text",metadata:{},created_at:null!=p?p:(new Date).toISOString()};r.setMessages(ci(r.messages.value,m));var b=null===(n=s.body)||void 0===n?void 0:n.getReader();if(!b)return A().error(vi,"no response body reader available"),void bi(r,g);var y=new TextDecoder,w="",x=null,_=!0,k=()=>{if(v()){var t=r.messages.value.findIndex(t=>t.id===g);if(-1!==t){var e=[...r.messages.value];e[t]=h({},e[t],{content:w.replace(/<[^>]*$/,"")}),r.setMessages(e)}}else bi(r,g)},S=()=>{null===x&&(x=requestAnimationFrame(()=>{k(),x=null}))};try{for(;;){if(!v())return void bi(r,g);var{done:C,value:T}=yield b.read();if(C)break;var E=y.decode(T,{stream:!0});w+=E,_?(_=!1,k()):S()}if(!v())return void bi(r,g);null!==x&&(cancelAnimationFrame(x),x=null),k();var I=r.messages.value.findIndex(t=>t.id===g);if(-1!==I){var M=pi(w),O=[...r.messages.value],P=h({},null!==(i=O[I].metadata)&&void 0!==i?i:{});M.length>0&&(P.T=M),O[I]=h({},O[I],{content:w,metadata:P}),r.setMessages(O)}null==c||c(g)}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)return void bi(r,g);A().error(vi,"failed to handle streaming response:",t),bi(r,g)}finally{b.releaseLock(),null!==x&&cancelAnimationFrame(x)}}}),mi.apply(this,arguments)}function bi(t,e){var n=t.messages.value.filter(t=>t.id!==e);n.length!==t.messages.value.length&&t.setMessages(n)}var yi=/<(?:p|ul|ol|li|h[1-6]|br|div|pre|blockquote)\b/i,wi=new Set(["P","B","STRONG","I","EM","U","UL","OL","LI","BR","A","H1","H2","H3","H4","H5","H6","CODE","PRE","BLOCKQUOTE","DIV","SPAN"]);function xi(t){var e=t;return e=(e=(e=(e=(e=(e=e.replace(/\*\*(.+?)\*\*/g,"<b>$1</b>")).replace(/__(.+?)__/g,"<b>$1</b>")).replace(/\*(.+?)\*/g,"<i>$1</i>")).replace(/(?<!\w)_(.+?)_(?!\w)/g,"<i>$1</i>")).replace(/`([^`]+)`/g,"<code>$1</code>")).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2">$1</a>')}function _i(t,e){for(var n=Array.from(t.children),i=0;i<n.length;){var r=n[i];if("LI"!==r.tagName)_i(r,e),i++;else{for(var s=[],o=i;o<n.length&&"LI"===n[o].tagName;)s.push(n[o]),o++;var a=e.createElement("ul");for(var l of(t.insertBefore(a,s[0]),s))a.appendChild(l);i=o}}}function ki(t,e){if(void 0===e&&(e="text"),!t)return"";var n=t.trim();if(!n)return"";if("undefined"==typeof document)return n;var i,r,s=function(t,e){return"html"!==t&&!yi.test(e)}(e,n)?function(t){if(!t||yi.test(t))return t;for(var e=t.split("\n"),n=[],i=0;i<e.length;){var r=e[i],s=r.match(/^(#{1,6})\s+(.+)$/);if(s){var o=s[1].length;n.push("<h"+o+">"+xi(s[2])+"</h"+o+">"),i++}else if(/^[-*]\s+/.test(r)){for(var a=[];i<e.length&&/^[-*]\s+/.test(e[i]);)a.push("<li>"+xi(e[i].replace(/^[-*]\s+/,""))+"</li>"),i++;n.push("<ul>"+a.join("")+"</ul>")}else if(/^\d+\.\s+/.test(r)){for(var l=[];i<e.length&&/^\d+\.\s+/.test(e[i]);)l.push("<li>"+xi(e[i].replace(/^\d+\.\s+/,""))+"</li>"),i++;n.push("<ol>"+l.join("")+"</ol>")}else if(""!==r.trim()){for(var u=[];i<e.length&&""!==e[i].trim()&&!/^#{1,6}\s/.test(e[i])&&!/^[-*]\s+/.test(e[i])&&!/^\d+\.\s+/.test(e[i]);)u.push(xi(e[i])),i++;n.push("<p>"+u.join("<br>")+"</p>")}else i++}return n.join("")}(n):n,o=document.createElement("div");return o.innerHTML=s,i=document,(r=t=>{for(var e of Array.from(t.children))if(wi.has(e.tagName)){for(var n of Array.from(e.attributes))"A"===e.tagName&&"href"===n.name||e.removeAttribute(n.name);"A"===e.tagName&&(e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer")),r(e)}else e.replaceWith(i.createTextNode(e.textContent||""))})(o),_i(o,document),o.innerHTML}var Si=Hn(function(t){var{message:e,controller:n}=t,i=function(t){var e,n=null!==(e=t.metadata)&&void 0!==e?e:{},i=n.T;i&&0!==i.length||(i=n.widgets);i&&0!==i.length||!t.content||(i=pi(t.content));return null!=i?i:[]}(e);return 0===i.length?null:re(Ut,{children:i.map((t,i)=>{if(t.submitted)return re(Ci,{widget:t},i);var r=n.widgets.get(t.type);if(!r)return null;var s=n.getWidgetContext(e.id,t.type);return re("div",{children:r.render(t.params,s)},i)})})},(t,e)=>t.message===e.message&&t.controller===e.controller);function Ci(t){var e,n,{widget:i}=t;if("collect_email"===i.type){var r=null!==(e=i.submittedEmail)&&void 0!==e?e:"",s=null!==(n=i.submittedName)&&void 0!==n?n:"";return re("div",{class:"vt-widget",children:re("p",{class:"vt-widget-thanks",children:s?"✓ Thanks, "+s+"! We'll follow up at "+r+".":r?"✓ Thanks! We'll follow up at "+r+".":"✓ Thanks!"})})}return"escalate_to_human"===i.type?re("div",{class:"vt-widget",children:re("p",{class:"vt-widget-thanks",children:"✓ A team member has been notified. They'll join shortly."})}):re("div",{class:"vt-widget",children:re("p",{class:"vt-widget-thanks",children:"✓ Done"})})}var Ti=Hn(function(t){var{message:e,controller:n,isReadByAgent:i}=t,r="user"===e.sender_type?"out":"in",s=_e(()=>function(t){if("user"===t.sender_type)return"";if("ai"===t.sender_type)return"AI Assistant";return t.sender_name||"Agent"}(e),[e.sender_type,e.sender_name]);return re("div",{class:"vt-message","data-direction":r,children:[re("div",{class:"vt-message-row",children:["in"===r&&re(Ei,{senderType:e.sender_type}),re(Ai,{message:e})]}),re(Si,{message:e,controller:n}),re("div",{class:"vt-message-meta",children:[s?re("span",{children:s}):null,s?re("span",{children:" · "}):null,re("time",{children:Mi(e.created_at)}),"out"===r?re(Ii,{message:e,controller:n}):null,"out"===r&&i?re("span",{children:" · Read"}):null]})]})},(t,e)=>t.message===e.message&&t.message.delivery_status===e.message.delivery_status&&t.controller===e.controller&&t.isReadByAgent===e.isReadByAgent);function Ai(t){var e,{message:n}=t,i=(null!==(e=n.content)&&void 0!==e?e:"").replace(fi,"").trim();if(!i)return re("div",{class:"vt-message-bubble"});if(!lt(n))return re("div",{class:"vt-message-bubble",children:i});var r=ki(i,n.content_type);return re("div",{class:"vt-message-bubble",children:re("div",{class:"vt-md"+("user"===n.sender_type?" vt-user-md":""),dangerouslySetInnerHTML:{__html:r}})})}function Ei(t){var{senderType:e}=t,n="ai"===e;return re("div",{class:"vt-message-avatar","data-mode":n?"ai":"support",children:re(n?Le:$e,{width:16,height:16})})}function Ii(t){var{message:e,controller:n}=t,i=e.delivery_status;return i?re("span","pending"===i||"sending"===i?{children:" · Sending…"}:{children:[" · ",re("button",{type:"button",class:"vt-message-retry",onClick:()=>n.retryFailedMessage(e.id),children:"Failed — tap to retry"})]}):null}function Mi(t){if(!t)return"";var e=new Date(t);return Number.isNaN(e.getTime())?"":e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Oi(t){var{senderType:e,senderName:n}=t,i="ai"===e,r=i?"AI Assistant":n||"Agent";return re("div",{class:"vt-message","data-direction":"in","data-typing":"true",children:[re("div",{class:"vt-message-row",children:[re("div",{class:"vt-message-avatar","data-mode":i?"ai":"support",children:re(i?Le:$e,{width:16,height:16})}),re("div",{class:"vt-message-bubble","data-typing":"true","aria-label":r+" is typing",children:[re("span",{class:"vt-typing-dot"}),re("span",{class:"vt-typing-dot"}),re("span",{class:"vt-typing-dot"})]})]}),re("div",{class:"vt-message-meta",children:re("span",{children:r})})]})}function Pi(t){var{count:e,visible:n,onJump:i}=t;return re("button",{type:"button",class:"vt-new-pill","data-visible":n&&e>0?"true":"false","aria-label":"Jump to latest messages",onClick:i,children:re("span",{children:e>1?"↓ "+e+" new messages":"↓ 1 new message"})})}function Ri(t){var{store:e,scrollRef:n,messages:i,typingActive:r=!1}=t,s=xe(null),o=xe(0);return we(()=>{var t=n.current;if(t){var i=()=>{t.scrollHeight-t.scrollTop-t.clientHeight<80?e.userScrolledUp.value&&(e.userScrolledUp.value=!1,e.unreadNewMessagesCount.value=0):e.userScrolledUp.value||(e.userScrolledUp.value=!0)};return t.addEventListener("scroll",i,{passive:!0}),()=>t.removeEventListener("scroll",i)}},[n.current]),we(()=>{var t,r,a,l=n.current;if(l){var u=null!==(t=i[i.length-1])&&void 0!==t?t:null;if(u){var h=u.id,d=null!==(a=null===(r=u.content)||void 0===r?void 0:r.length)&&void 0!==a?a:0,c=h!==s.current,v=!c&&"ai"===u.sender_type&&d>o.current;if(c||v)if(s.current=h,o.current=d,c){if("user"===u.sender_type)return l.scrollTop=l.scrollHeight,e.userScrolledUp.value=!1,void(e.unreadNewMessagesCount.value=0);var f=l.scrollHeight-l.scrollTop-l.clientHeight<80;!e.userScrolledUp.value||f?l.scrollTop=l.scrollHeight:"agent"!==u.sender_type&&"ai"!==u.sender_type||(e.unreadNewMessagesCount.value=e.unreadNewMessagesCount.value+1)}else(t=>{var n=t.scrollHeight-t.scrollTop-t.clientHeight<80;e.userScrolledUp.value&&!n||(t.scrollTop=t.scrollHeight)})(l)}}},[i,n.current]),we(()=>{if(r){var t=n.current;if(t){var i=t.scrollHeight-t.scrollTop-t.clientHeight<80;e.userScrolledUp.value&&!i||(t.scrollTop=t.scrollHeight)}}},[r,n.current]),{jumpToBottom:()=>{var t=n.current;t&&(t.scrollTop=t.scrollHeight,e.userScrolledUp.value=!1,e.unreadNewMessagesCount.value=0)}}}function Di(t){var{store:e,controller:n}=t,i=xe(null),r=e.messages.value,s=e.channel.value,o=e.agentLastReadAt.value,a=e.isTyping.value,l=e.typingSenderType.value,u=e.typingSender.value,{jumpToBottom:h}=Ri({store:e,scrollRef:i,messages:r,typingActive:a});!function(t){var e,n,i,{store:r,controller:s,messages:o}=t;we(()=>{if(r.isOpen.value&&"conversation"===r.currentView.value&&r.channel.value){var t=setTimeout(()=>s.markAsRead(),80);return()=>clearTimeout(t)}},[null!==(n=null===(e=o[o.length-1])||void 0===e?void 0:e.id)&&void 0!==n?n:null,r.isOpen.value,r.currentView.value,null===(i=r.channel.value)||void 0===i?void 0:i.id])}({store:e,controller:n,messages:r});var d=!s&&e.isLoading.value&&0===r.length,c=!!s&&e.isLoading.value&&0===r.length,v=a&&("ai"===l||"agent"===l);return re("div",{class:"vt-messages-wrapper",children:[re("div",{class:"vt-messages",ref:i,children:d?re(Oi,{senderType:!1===n.config.aiMode?"agent":"ai"}):c?re(Dn,{}):re(Ut,{children:[r.map(t=>{return re(Ti,{message:t,controller:n,isReadByAgent:(e=t.created_at,!!o&&new Date(e)<=new Date(o))},t.id);var e}),v&&re(Oi,{senderType:l,senderName:u})]})}),re(Pi,{count:e.unreadNewMessagesCount.value,visible:e.userScrolledUp.value,onJump:h})]})}function Ui(t){var e,{store:n,controller:i}=t,r="closed"===(null===(e=n.channel.value)||void 0===e?void 0:e.status);return re(Ut,{children:[re(Di,{store:n,controller:i}),re($n,{store:n}),r?re(Ln,{}):re(zn,{store:n,controller:i})]})}function ji(t){var{store:e,controller:n}=t,i=e.currentView.value;return re("div",{class:"vt-panel vt-opening",children:[re(Nn,{store:e,controller:n}),re("div",{class:"vt-content",children:re("list"===i?jn:Ui,{store:e,controller:n})})]})}var Bi="vtilt-chat-font";function Ni(t){!function(){if("undefined"!=typeof document&&!document.getElementById(Bi)){var t=document.createElement("link");t.rel="preconnect",t.href="https://fonts.gstatic.com",t.crossOrigin="anonymous",document.head.appendChild(t);var e=document.createElement("link");e.id=Bi,e.rel="stylesheet",e.href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap",document.head.appendChild(e)}}();var e=document.createElement("div");e.id="vtilt-chat-host",e.style.cssText="all: initial; position: fixed; inset: auto; z-index: 999999; pointer-events: none;",document.body.appendChild(e);var n=e.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent='\n/* Load Inter so the widget looks like vTilt on every host page. The @import\n sits at the very top of the stylesheet (required by the spec) and only\n fetches the variable-axis subset we need. If the host\'s CSP blocks Google\n Fonts the font-family fallback chain below keeps the widget legible. */\n@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap");\n\n:host {\n --vtilt-primary: #7B68EE;\n --vtilt-primary-shadow: rgba(123, 104, 238, 0.4);\n --vtilt-font: "Inter var", "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n --vtilt-radius: 16px;\n --vtilt-text: #000000;\n --vtilt-text-muted: #666666;\n --vtilt-text-subtle: #888888;\n --vtilt-bg: #ffffff;\n --vtilt-bg-list: #FAFAFA;\n --vtilt-border: #E5E5E5;\n --vtilt-border-light: #EEEEEE;\n --vtilt-skeleton: #E8E8EA;\n --vtilt-online: #16A34A;\n\n all: initial;\n font-family: var(--vtilt-font);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n color: var(--vtilt-text);\n}\n\n*, *::before, *::after {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n}\n\nbutton {\n font-family: inherit;\n cursor: pointer;\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n}\n\n/* =========================================================================\n * Container + bubble + panel\n * ========================================================================= */\n\n/* The host element gets \'all: initial\' inline (set in ChatRoot.tsx) so the\n host page can\'t position or style it. Inline styles win over \':host\' rules\n in the cascade, so the host\'s effective font-family / color end up at the\n UA default — and shadow children inherit from there. We re-establish the\n widget typography on .vt-container (which lives *inside* the shadow tree)\n so every descendant inherits Inter + the themed text color, regardless of\n what the host page or the host element\'s inline reset look like. */\n.vt-container {\n position: fixed;\n bottom: var(--vt-bubble-offset-bottom, 20px);\n /* Pin the container to the bubble\'s intrinsic size so it keeps the\n * same bounding box even after the bubble itself goes display:none on\n * open. Without this the container collapses to 0x0 and the absolutely\n * positioned panel anchors at that zero-size point — which means the\n * opened panel no longer overlaps the bubble\'s last visible footprint\n * for any non-default anchor (e.g. a bubble dragged to the bottom-left\n * with data-position="bottom-right" would see the panel jump 60px away\n * from where the bubble had been). With a fixed container size, the\n * panel\'s [data-panel-anchor] corner always coincides with the matching\n * corner of the bubble, regardless of drag offset. */\n width: 60px;\n height: 60px;\n z-index: 999999;\n font-family: var(--vtilt-font);\n font-size: 14px;\n line-height: 1.4;\n color: var(--vtilt-text);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.vt-container[data-position="bottom-right"] {\n right: var(--vt-bubble-offset-right, 20px);\n}\n.vt-container[data-position="bottom-left"] {\n left: var(--vt-bubble-offset-left, 20px);\n}\n.vt-container[data-hidden="true"] { display: none; }\n\n.vt-bubble {\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background: var(--vtilt-primary);\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 4px 16px var(--vtilt-primary-shadow);\n transition: transform 0.15s ease, box-shadow 0.15s ease;\n position: relative;\n border: none;\n}\n.vt-bubble:hover { transform: scale(1.05); box-shadow: 0 6px 20px var(--vtilt-primary-shadow); }\n.vt-bubble:active { transform: scale(0.95); }\n.vt-container[data-open="true"] .vt-bubble { display: none; }\n.vt-container[data-draggable="true"] .vt-bubble:hover,\n.vt-container[data-draggable="true"] .vt-bubble:active { transform: none; }\n\n.vt-bubble-badge {\n display: none;\n position: absolute;\n top: -4px;\n right: -4px;\n background: #E53935;\n color: white;\n font-size: 11px;\n font-weight: 700;\n min-width: 20px;\n height: 20px;\n border-radius: 10px;\n align-items: center;\n justify-content: center;\n padding: 0 6px;\n border: 2px solid white;\n}\n.vt-bubble-badge[data-visible="true"] { display: flex; }\n\n/* Panel position is driven by [data-panel-anchor] on the container.\n * The chat widget recomputes the anchor from the bubble\'s actual viewport\n * position (see usePanelAnchor in ui/ChatRoot.tsx) so the panel always\n * extends into whichever side has more room — even after the bubble has\n * been dragged across the viewport. The default anchor (no attribute) is\n * "bottom-right" so the very first paint, before JS has computed the\n * anchor, matches the most common default position.\n *\n * Per-anchor max-width / max-height are exposed as the CSS variables\n * --vt-panel-max-w and --vt-panel-max-h. JS sets them to the available\n * room from the chosen anchor (capped by the panel\'s intrinsic 380x600\n * design size), so on small or oddly-shaped viewports the panel never\n * overruns the opposite edge. The min(...) wrapper falls back to the\n * original "viewport minus 40px" formula when the variables aren\'t set. */\n.vt-panel {\n display: none;\n flex-direction: column;\n position: absolute;\n bottom: 0;\n right: 0;\n width: 380px;\n height: 600px;\n /* Effective size = min(intrinsic, room-from-anchor, viewport-minus-margin).\n * The viewport term is a backstop: while the chat is open we deliberately\n * freeze the per-anchor variable, so a viewport resize during open could\n * otherwise leave a stale value that overruns the opposite edge. */\n max-width: min(380px, var(--vt-panel-max-w, calc(100vw - 40px)), calc(100vw - 40px));\n max-height: min(600px, var(--vt-panel-max-h, calc(100vh - 40px)), calc(100vh - 40px));\n max-height: min(600px, var(--vt-panel-max-h, calc(100dvh - 40px)), calc(100dvh - 40px));\n background: var(--vtilt-bg);\n border-radius: var(--vtilt-radius);\n box-shadow: 0 5px 40px rgba(0, 0, 0, 0.16);\n overflow: hidden;\n}\n.vt-container[data-panel-anchor="bottom-left"] .vt-panel { right: auto; left: 0; }\n.vt-container[data-panel-anchor="top-right"] .vt-panel { bottom: auto; top: 0; }\n.vt-container[data-panel-anchor="top-left"] .vt-panel { bottom: auto; top: 0; right: auto; left: 0; }\n.vt-container[data-open="true"] .vt-panel { display: flex; }\n.vt-container[data-open="true"] .vt-panel.vt-opening {\n animation: vt-open 0.5s cubic-bezier(0.16, 1, 0.3, 1) forwards;\n /* The animation scales from 0.4 to 1; transform-origin decides which\n * corner of the panel that scale grows from. JS sets --vt-panel-origin\n * to the same corner usePanelAnchor picked for [data-panel-anchor], so\n * the panel always appears to "pop" out of the bubble. The fallback\n * matches the default bottom-right anchor used before JS computes a\n * direction (or in environments where the variable isn\'t set). */\n transform-origin: var(--vt-panel-origin, bottom right);\n}\n\n@keyframes vt-open {\n from { opacity: 0; transform: scale(0.4); }\n to { opacity: 1; transform: scale(1); }\n}\n\n/* =========================================================================\n * Header\n * ========================================================================= */\n\n.vt-header {\n background: var(--vtilt-bg);\n border-bottom: 1px solid var(--vtilt-border);\n padding: 18px 16px;\n padding-top: max(18px, env(safe-area-inset-top, 18px));\n display: flex;\n align-items: center;\n min-height: 60px;\n flex-shrink: 0;\n gap: 12px;\n}\n.vt-header[data-view="list"] {\n justify-content: space-between;\n}\n.vt-header[data-view="conversation"] {\n padding: 12px 16px;\n padding-top: max(12px, env(safe-area-inset-top, 12px));\n}\n\n.vt-header-title { font-weight: 600; font-size: 17px; color: var(--vtilt-text); }\n.vt-header-info { flex: 1; min-width: 0; }\n.vt-header-name { font-weight: 600; font-size: 16px; color: var(--vtilt-text); }\n.vt-header-status {\n font-size: 13px;\n color: var(--vtilt-online);\n display: flex;\n align-items: center;\n gap: 5px;\n margin-top: 1px;\n}\n.vt-header-status::before {\n content: "";\n width: 7px;\n height: 7px;\n background: var(--vtilt-online);\n border-radius: 50%;\n}\n\n.vt-iconbtn {\n background: transparent;\n border: none;\n color: var(--vtilt-text-muted);\n padding: 6px;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n}\n.vt-iconbtn:hover { color: var(--vtilt-text); background: #F0F0F0; }\n.vt-header-back { margin-left: -6px; }\n.vt-header-close { margin-right: -6px; }\n\n.vt-header-avatar {\n width: 44px;\n height: 44px;\n border-radius: 50%;\n background: var(--vtilt-primary);\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n color: white;\n}\n.vt-header-avatar[data-mode="support"] { background: #DEDEDE; color: #666; }\n\n/* =========================================================================\n * Content area (channel list, conversation)\n * ========================================================================= */\n\n.vt-content {\n flex: 1;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n min-height: 0;\n background: var(--vtilt-bg);\n}\n\n/* Channel list ----------------------------------------------------------- */\n\n.vt-list-root {\n flex: 1;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n}\n\n.vt-list-empty {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 48px 24px;\n text-align: center;\n}\n.vt-list-empty-icon {\n width: 72px;\n height: 72px;\n margin-bottom: 24px;\n background: var(--vtilt-primary);\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n.vt-list-empty-title {\n font-size: 18px;\n font-weight: 600;\n color: var(--vtilt-text);\n margin-bottom: 12px;\n line-height: 1.4;\n max-width: 280px;\n}\n.vt-list-empty-subtitle {\n font-size: 14px;\n color: var(--vtilt-text-muted);\n margin-bottom: 28px;\n}\n\n.vt-channel-item {\n padding: 14px 16px;\n cursor: pointer;\n display: flex;\n align-items: center;\n gap: 12px;\n background: var(--vtilt-bg);\n border: none;\n width: 100%;\n text-align: left;\n border-bottom: 1px solid var(--vtilt-border-light);\n transition: background 0.1s ease;\n font: inherit;\n color: inherit;\n}\n.vt-channel-item:hover { background: #F5F5F5; }\n.vt-channel-item:active { background: #EBEBEB; }\n\n.vt-channel-avatar {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: var(--vtilt-primary);\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n color: white;\n}\n.vt-channel-avatar[data-mode="support"] { background: #DEDEDE; color: #666; }\n\n.vt-channel-body { flex: 1; min-width: 0; }\n.vt-channel-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n margin-bottom: 4px;\n}\n.vt-channel-name {\n font-weight: 500;\n font-size: 15px;\n color: var(--vtilt-text);\n line-height: 1.2;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.vt-channel-name[data-unread="true"] { font-weight: 600; }\n.vt-channel-time {\n font-size: 13px;\n color: var(--vtilt-text-subtle);\n white-space: nowrap;\n flex-shrink: 0;\n}\n.vt-channel-preview {\n font-size: 14px;\n color: var(--vtilt-text-subtle);\n font-weight: 400;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n flex: 1;\n min-width: 0;\n line-height: 1.4;\n}\n.vt-channel-preview[data-unread="true"] { color: #333; }\n.vt-channel-unread {\n min-width: 20px;\n height: 20px;\n padding: 0 6px;\n background: var(--vtilt-primary);\n border-radius: 10px;\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 12px;\n font-weight: 600;\n color: #FFFFFF;\n line-height: 1;\n}\n\n.vt-list-footer {\n padding: 16px;\n padding-bottom: max(16px, env(safe-area-inset-bottom, 16px));\n border-top: 1px solid var(--vtilt-border);\n}\n\n.vt-new-channel-btn {\n width: 100%;\n background: var(--vtilt-primary);\n color: white;\n border: none;\n border-radius: 100px;\n padding: 14px 24px;\n font-weight: 500;\n font-size: 15px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n box-shadow: 0 2px 8px var(--vtilt-primary-shadow);\n transition: opacity 0.1s ease;\n}\n.vt-new-channel-btn:hover { opacity: 0.9; }\n.vt-new-channel-btn:active { opacity: 0.8; }\n\n/* Conversation ----------------------------------------------------------- */\n\n.vt-messages-wrapper {\n position: relative;\n flex: 1;\n display: flex;\n flex-direction: column;\n min-height: 0;\n}\n\n.vt-messages {\n flex: 1;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n padding: 20px 16px 24px 16px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n min-height: 0;\n background: var(--vtilt-bg-list);\n}\n\n.vt-message {\n display: flex;\n flex-direction: column;\n animation: vt-message-in 0.22s ease-out both;\n}\n.vt-message[data-direction="in"] { align-items: flex-start; }\n.vt-message[data-direction="out"] { align-items: flex-end; }\n\n.vt-message-row {\n display: flex;\n gap: 10px;\n align-items: flex-end;\n max-width: 85%;\n}\n.vt-message[data-direction="out"] .vt-message-row {\n flex-direction: row-reverse;\n}\n\n.vt-message-avatar {\n width: 32px;\n height: 32px;\n border-radius: 50%;\n background: var(--vtilt-primary);\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n color: white;\n}\n.vt-message-avatar[data-mode="support"] { background: #DEDEDE; color: #666; }\n\n.vt-message-bubble {\n padding: 10px 14px;\n background: var(--vtilt-bg);\n border-radius: 20px 20px 20px 4px;\n font-size: 14px;\n line-height: 1.4;\n color: var(--vtilt-text);\n word-wrap: break-word;\n overflow-wrap: anywhere;\n min-width: 0;\n}\n.vt-message[data-direction="out"] .vt-message-bubble {\n background: var(--vtilt-primary);\n color: white;\n border-radius: 20px 20px 4px 20px;\n}\n\n.vt-message-meta {\n font-size: 12px;\n color: var(--vtilt-text-subtle);\n margin-top: 6px;\n}\n.vt-message[data-direction="in"] .vt-message-meta { margin-left: 46px; }\n.vt-message[data-direction="out"] .vt-message-meta { margin-right: 4px; }\n\n.vt-message-retry {\n font: inherit;\n font-size: inherit;\n color: var(--vtilt-error, #dc2626);\n background: none;\n border: none;\n padding: 0;\n cursor: pointer;\n text-decoration: underline;\n}\n\n@keyframes vt-message-in {\n from { opacity: 0; transform: translateY(4px); }\n to { opacity: 1; transform: translateY(0); }\n}\n\n/* Markdown content rules (parity with chat-message-content.css) */\n.vt-md {\n max-width: 100%;\n overflow-wrap: anywhere;\n word-break: break-word;\n font-size: inherit;\n line-height: 1.45;\n}\n.vt-md p { margin: 0 0 0.5em 0; }\n.vt-md p:last-child { margin-bottom: 0; }\n.vt-md :is(b, strong) { font-weight: 600; }\n.vt-md :is(i, em) { font-style: italic; }\n.vt-md u { text-decoration: underline; }\n.vt-md :is(h1, h2, h3, h4, h5, h6) {\n font-size: 1em;\n font-weight: 600;\n margin: 0.65em 0 0.35em 0;\n line-height: 1.3;\n}\n.vt-md :is(h1, h2, h3):first-child { margin-top: 0.15em; }\n.vt-md :is(ul, ol) {\n list-style: none;\n margin: 0.5em 0;\n padding: 0 0 0 0.35em;\n}\n.vt-md li {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n align-items: flex-start;\n gap: 0.35em;\n margin: 0.2em 0;\n padding: 0;\n line-height: 1.45;\n}\n.vt-md ul > li::before {\n content: "•";\n display: inline-block;\n flex: 0 0 auto;\n line-height: 1.45;\n}\n.vt-md ul ul > li::before { content: "◦"; }\n.vt-md ol { counter-reset: vt-ol; }\n.vt-md ol > li { counter-increment: vt-ol; }\n.vt-md ol > li::before {\n content: counter(vt-ol) ".";\n display: inline-block;\n flex: 0 0 auto;\n min-width: 1.1em;\n line-height: 1.45;\n}\n.vt-md ol ol { counter-reset: vt-ol; }\n.vt-md li > :is(ul, ol) {\n flex: 1 0 100%;\n width: 100%;\n margin: 0.25em 0 0 0;\n padding-left: 0.75em;\n}\n.vt-md code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n font-size: 0.9em;\n background: rgba(0, 0, 0, 0.06);\n padding: 0.1em 0.35em;\n border-radius: 4px;\n}\n.vt-md pre {\n margin: 0.5em 0;\n padding: 0.5em 0.65em;\n border-radius: 6px;\n background: rgba(0, 0, 0, 0.06);\n overflow-x: auto;\n white-space: pre-wrap;\n}\n.vt-md pre code { background: none; padding: 0; }\n.vt-md blockquote {\n margin: 0.5em 0;\n padding-left: 0.75em;\n border-left: 3px solid rgba(0, 0, 0, 0.15);\n}\n.vt-md a { color: inherit; text-decoration: underline; }\n\n/* Brand-colored "out" bubble inverts code/pre/quote backdrop. */\n.vt-user-md code { background: rgba(255, 255, 255, 0.2); }\n.vt-user-md pre { background: rgba(255, 255, 255, 0.15); }\n.vt-user-md pre code { background: none; }\n.vt-user-md blockquote { border-left-color: rgba(255, 255, 255, 0.35); }\n\n/* Typing bubble + new-messages pill -------------------------------------\n *\n * The typing indicator is no longer a separate strip above the composer\n * - it is an inline .vt-message rendered as the last child of the\n * message list, reusing the avatar + bubble shape so the dots morph\n * into the real message when it arrives. The only typing-specific\n * style is the [data-typing] modifier that switches the bubble layout\n * to inline-flex so the three dots sit horizontally instead of\n * stacking. The dot animation rules are reused by TypingBubble. */\n\n.vt-message-bubble[data-typing="true"] {\n display: inline-flex;\n align-items: center;\n gap: 5px;\n /* Critical: do NOT override the base .vt-message-bubble padding here.\n * The row uses align-items: flex-end, so a bubble shorter than a\n * single-line text bubble would bottom-align with the avatar and\n * visually sit lower than where the real message will appear. We\n * inherit 10px 14px from the base, then enforce a min content\n * height of one text line (14px font-size * 1.4 line-height) so the\n * total bubble height matches a single-line text bubble exactly.\n * When the dots morph into text the bubble stays put — no jolt. */\n min-height: 1.4em;\n}\n.vt-typing-dot {\n width: 6px;\n height: 6px;\n background: #B5B5B5;\n border-radius: 50%;\n animation: vt-typing-bounce 1.2s infinite;\n}\n.vt-typing-dot:nth-child(2) { animation-delay: 0.2s; }\n.vt-typing-dot:nth-child(3) { animation-delay: 0.4s; }\n@keyframes vt-typing-bounce {\n 0%, 60%, 100% { opacity: 0.35; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n\n.vt-new-pill {\n position: absolute;\n left: 50%;\n transform: translateX(-50%);\n bottom: 12px;\n background: var(--vtilt-primary);\n color: white;\n padding: 6px 14px;\n border-radius: 999px;\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n border: none;\n box-shadow: 0 2px 8px rgba(0,0,0,0.15);\n display: none;\n align-items: center;\n gap: 6px;\n z-index: 5;\n transition: opacity 0.15s ease;\n}\n.vt-new-pill[data-visible="true"] { display: flex; }\n.vt-new-pill:hover { opacity: 0.92; }\n\n/* Closed banner + connection banner ------------------------------------- */\n\n.vt-closed-banner {\n padding: 12px 16px;\n padding-bottom: max(12px, env(safe-area-inset-bottom, 12px));\n border-top: 1px solid var(--vtilt-border);\n text-align: center;\n background: var(--vtilt-bg-list);\n flex-shrink: 0;\n font-size: 14px;\n color: var(--vtilt-text-subtle);\n}\n\n/* Connection banner.\n *\n * Two visual modes:\n * - data-kind="reconnecting": slim pill. Pulsing dot + "Reconnecting"\n * label. Slate background — informational, not alarming.\n * - data-kind="failed": actionable card. Warning icon + "Connection\n * lost" + Retry button. Red because the user must act.\n */\n.vt-conn-banner {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 6px 12px;\n border-top: 1px solid var(--vtilt-border);\n font-size: 12px;\n font-weight: 500;\n flex-shrink: 0;\n}\n.vt-conn-banner[data-kind="reconnecting"] {\n background: #F8FAFC;\n color: #475569;\n justify-content: center;\n}\n.vt-conn-banner[data-kind="failed"] {\n background: #FEF2F2;\n color: #991B1B;\n}\n.vt-conn-banner-icon {\n display: inline-flex;\n flex-shrink: 0;\n color: #DC2626;\n}\n.vt-conn-banner-text {\n flex: 1;\n}\n.vt-conn-banner[data-kind="reconnecting"] .vt-conn-banner-text {\n flex: 0 0 auto;\n}\n.vt-conn-banner-dot {\n display: inline-block;\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: #F59E0B;\n flex-shrink: 0;\n animation: vt-conn-pulse 1.4s ease-in-out infinite;\n}\n@keyframes vt-conn-pulse {\n 0%, 100% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.4; transform: scale(0.85); }\n}\n.vt-conn-banner-action {\n appearance: none;\n border: 1px solid #DC2626;\n background: transparent;\n color: #DC2626;\n font: inherit;\n font-weight: 600;\n font-size: 11px;\n padding: 3px 10px;\n border-radius: 999px;\n cursor: pointer;\n flex-shrink: 0;\n transition: background 0.12s ease, color 0.12s ease;\n}\n.vt-conn-banner-action:hover,\n.vt-conn-banner-action:focus-visible {\n background: #DC2626;\n color: #FFFFFF;\n outline: none;\n}\n@media (prefers-reduced-motion: reduce) {\n .vt-conn-banner-dot {\n animation: none;\n }\n}\n\n/* Input ----------------------------------------------------------------- */\n\n.vt-input-container {\n padding: 8px 12px;\n padding-bottom: max(8px, env(safe-area-inset-bottom, 8px));\n border-top: 1px solid var(--vtilt-border);\n flex-shrink: 0;\n background: var(--vtilt-bg);\n}\n.vt-input-box {\n position: relative;\n border: 1px solid #DDD;\n border-radius: 12px;\n background: var(--vtilt-bg);\n transition: border-color 0.15s ease, box-shadow 0.15s ease;\n}\n.vt-input-box:focus-within {\n border-color: var(--vtilt-primary);\n box-shadow: 0 0 0 2px rgba(123, 104, 238, 0.12);\n}\n.vt-input-textarea {\n width: 100%;\n box-sizing: border-box;\n border: none;\n border-radius: 0;\n padding: 12px 48px 12px 12px;\n font-size: 16px;\n line-height: 1.4;\n outline: none;\n background: transparent;\n color: var(--vtilt-text);\n resize: none;\n overflow-y: auto;\n overflow-x: hidden;\n min-height: 60px;\n max-height: 120px;\n font-family: inherit;\n}\n.vt-input-textarea::placeholder { color: #999; }\n.vt-input-textarea:disabled { color: #BBB; cursor: not-allowed; }\n\n.vt-input-send {\n position: absolute;\n right: 4px;\n bottom: 4px;\n background: #E5E5E5;\n color: #999;\n border: none;\n border-radius: 50%;\n padding: 0;\n width: 32px;\n height: 32px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background-color 0.15s ease, color 0.15s ease, opacity 0.15s ease;\n opacity: 0.6;\n}\n.vt-input-send[data-active="true"] {\n background: var(--vtilt-primary);\n color: white;\n cursor: pointer;\n opacity: 1;\n}\n.vt-input-send[data-active="true"]:hover { opacity: 0.9; }\n.vt-input-send[data-active="true"]:active { opacity: 0.8; transform: scale(0.95); }\n.vt-input-send:disabled { cursor: not-allowed; }\n\n.vt-input-container[data-pending="true"] .vt-input-box {\n background: var(--vtilt-bg-list);\n border-color: var(--vtilt-border-light);\n}\n\n/* Skeletons ------------------------------------------------------------- */\n\n@keyframes vt-skeleton-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.55; }\n}\n.vt-skeleton {\n background: var(--vtilt-skeleton);\n border-radius: 6px;\n animation: vt-skeleton-pulse 2.2s cubic-bezier(0.4, 0, 0.6, 1) infinite;\n}\n.vt-skeleton-circle {\n background: var(--vtilt-skeleton);\n border-radius: 50%;\n animation: vt-skeleton-pulse 2.2s cubic-bezier(0.4, 0, 0.6, 1) infinite;\n}\n\n/* Built-in widgets ------------------------------------------------------ */\n\n.vt-widget { margin-top: 10px; }\n.vt-widget p { margin: 0 0 10px 0; font-size: 14px; color: #333; }\n.vt-widget-input {\n font-family: inherit;\n font-size: 14px;\n padding: 8px 10px;\n border: 1px solid #DDD;\n border-radius: 8px;\n width: 100%;\n margin-bottom: 8px;\n}\n.vt-widget-input:focus { outline: none; border-color: var(--vtilt-primary); }\n.vt-widget-btn {\n padding: 10px 16px;\n background: var(--vtilt-primary);\n color: white;\n border: none;\n border-radius: 12px;\n font-size: 14px;\n font-weight: 600;\n cursor: pointer;\n}\n.vt-widget-btn[data-style="outline"] {\n background: transparent;\n color: var(--vtilt-primary);\n border: 2px solid var(--vtilt-primary);\n display: inline-flex;\n align-items: center;\n gap: 8px;\n}\n.vt-widget-btn:disabled { opacity: 0.6; cursor: not-allowed; }\n.vt-widget-thanks { font-size: 13px; color: var(--vtilt-online); margin: 0; }\n\n/* Mobile fullscreen ----------------------------------------------------\n *\n * On viewports <=480px the open panel covers the whole device, regardless\n * of where the bubble was dragged. The rules live in a media query (not\n * a JS-driven data attribute) so they remain correct on viewport resize\n * — rotation, browser-window resize, devtools toggling — without needing\n * a re-render to update an attribute.\n *\n * "transform: none !important" is required because bubble-drag.ts sets\n * an inline "transform: translate3d(...)" on the container. Per the CSS\n * cascade, author !important declarations win over inline normal styles,\n * so the open panel snaps back to (0, 0) and fills the viewport even\n * after the user has dragged the bubble away from its anchor corner.\n */\n\n@media (max-width: 480px) {\n .vt-bubble { width: 56px; height: 56px; }\n .vt-container { width: 56px; height: 56px; }\n\n .vt-container[data-open="true"] {\n top: 0; left: 0; right: 0; bottom: 0;\n /* Stretch the container from a 56x56 box back to the viewport so the\n * fullscreen panel inside has room to fill the screen. */\n width: auto; height: auto;\n transform: none !important;\n }\n .vt-container[data-open="true"] .vt-panel {\n position: absolute;\n top: 0; left: 0; right: 0; bottom: 0;\n width: 100%;\n max-width: none;\n height: 100%;\n max-height: none;\n border-radius: 0;\n box-shadow: none;\n }\n}\n\n@media (prefers-reduced-motion: reduce) {\n * { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }\n}\n',n.appendChild(i);var r=document.createElement("div");return r.style.cssText="pointer-events: auto;",n.appendChild(r),function(t,e){var n=()=>{var n=e.theme.value;t.style.setProperty("--vtilt-primary",n.primaryColor),t.style.setProperty("--vtilt-primary-shadow",n.primaryColor+"66"),t.style.setProperty("--vtilt-font",n.fontFamily),t.style.setProperty("--vtilt-radius",n.borderRadius)};n(),e.theme.subscribe(n)}(e,t.store),ne(re(Li,{store:t.store,controller:t.controller,position:t.position,bubbleDraggable:t.bubbleDraggable}),r),{host:e,destroy(){ne(null,r),e.remove()}}}function Li(t){var{store:e,controller:n,position:i,bubbleDraggable:r}=t,s=xe(null),o=xe(null),a=xe(null),l=function(t,e){return ke(()=>{var n=e.current;if(n&&"undefined"!=typeof window&&!t.isOpen.value){var i=n.getBoundingClientRect();if(0!==i.width&&0!==i.height){var r=window.innerWidth,s=window.innerHeight,o=(i.left+i.right)/2>r/2?"right":"left",a=(i.top+i.bottom)/2>s/2?"bottom":"top",l=a+"-"+o;n.setAttribute("data-panel-anchor",l),n.style.setProperty("--vt-panel-origin",a+" "+o);var u="right"===o?i.right:r-i.left,h="bottom"===a?i.bottom:s-i.top;n.style.setProperty("--vt-panel-max-w",Math.max(0,u-20)+"px"),n.style.setProperty("--vt-panel-max-h",Math.max(0,h-20)+"px")}}},[t,e])}(e,s);return function(t,e){var n=be(se++,4);!de.__s&&Ie(n.__H,e)&&(n.__=t,n.u=e,oe.__h.push(n))}(()=>{if(r&&s.current&&o.current)return a.current=In(s.current,{handle:o.current,onPositionChange:l}),()=>{var t;null===(t=a.current)||void 0===t||t.destroy(),a.current=null}},[r,l]),we(()=>{l();var t=()=>l();window.addEventListener("resize",t);var n=e.isOpen.subscribe(t=>{t||l()});return()=>{window.removeEventListener("resize",t),n()}},[e,l]),function(t){we(()=>{var e=t.isOpen.value,n=t.isOpen.subscribe(t=>{var n,i;if("undefined"!=typeof document){var r=function(t,e,n){return n?e&&!t?{nextWasOpen:!0,shouldLock:!0,shouldUnlock:!1}:!e&&t?{nextWasOpen:!1,shouldLock:!1,shouldUnlock:!0}:{nextWasOpen:e,shouldLock:!1,shouldUnlock:!1}:{nextWasOpen:e,shouldLock:!1,shouldUnlock:!1}}(e,t,"undefined"!=typeof window&&window.innerWidth<=480);e=r.nextWasOpen;var s=document.documentElement,o=document.body;if(r.shouldLock){var a=null!==(n=null===window||void 0===window?void 0:window.scrollY)&&void 0!==n?n:0;s.style.setProperty("overflow","hidden","important"),o.style.setProperty("overflow","hidden","important"),o.style.setProperty("position","fixed","important"),o.style.setProperty("width","100%","important"),o.style.top="-"+a+"px",o.dataset.vtScrollY=String(a)}else if(r.shouldUnlock){var l=Number(null!==(i=o.dataset.vtScrollY)&&void 0!==i?i:0);s.style.removeProperty("overflow"),o.style.removeProperty("overflow"),o.style.removeProperty("position"),o.style.removeProperty("width"),o.style.top="",delete o.dataset.vtScrollY,null===window||void 0===window||window.scrollTo(0,l)}}else e=t});return n},[t])}(e),re("div",{ref:s,class:"vt-container","data-position":i,"data-draggable":r?"true":"false","data-hidden":e.isVisible.value?"false":"true","data-open":e.isOpen.value?"true":"false",children:[re(Mn,{store:e,controller:n,bubbleRef:o}),re(ji,{store:e,controller:n})]})}var $i=Object.defineProperty,zi=Object.defineProperties,qi=Object.getOwnPropertyDescriptors,Fi=Object.getOwnPropertySymbols,Hi=Object.prototype.hasOwnProperty,Wi=Object.prototype.propertyIsEnumerable,Ji=(t,e,n)=>e in t?$i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vi=(t,e)=>{for(var n in e||(e={}))Hi.call(e,n)&&Ji(t,n,e[n]);if(Fi)for(var n of Fi(e))Wi.call(e,n)&&Ji(t,n,e[n]);return t},Ki=(t,e)=>zi(t,qi(e)),Gi=function(t,e){this[0]=t,this[1]=e},Xi=class{},Qi="undefined"!=typeof global?global:"undefined"!=typeof window?window:self;function Zi(t,e){return(""+t).padStart(e?3:2,"0")}function Yi(t){return Xi.Config.logTimestamps?function(e){var n=new Date;t(Zi(n.getHours())+":"+Zi(n.getMinutes())+":"+Zi(n.getSeconds())+"."+Zi(n.getMilliseconds(),1)+" "+e)}:function(e){t(e)}}var tr=class t{constructor(){this.deprecated=(t,e)=>{this.deprecationWarning(t+" is deprecated and will be removed in a future version. "+e)},this.shouldLog=t=>t<=this.logLevel,this.setLog=(t,e)=>{void 0!==t&&(this.logLevel=t),void 0!==e&&(this.logHandler=this.logErrorHandler=e)},this.logLevel=t.defaultLogLevel,this.logHandler=t.defaultLogHandler,this.logErrorHandler=t.defaultLogErrorHandler}static initLogHandlers(){var e,n,i,[r,s]=("function"==typeof(null==(e=null==Qi?void 0:Qi.console)?void 0:e.log)?(n=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.log.apply(console,e)},i=console.warn?function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];console.warn.apply(console,e)}:n):n=i=function(){},[n,i].map(Yi));this.defaultLogHandler=r,this.defaultLogErrorHandler=s,this.defaultLogger=new t}static logActionNoStrip(t,e,n,i){t.logAction(e,n,i)}logAction(t,e,n){this.shouldLog(t)&&(1===t?this.logErrorHandler:this.logHandler)("Ably: "+e+": "+n,t)}renamedClientOption(t,e){this.deprecationWarning("The `"+t+"` client option has been renamed to `"+e+"`. Please update your code to use `"+e+"` instead. `"+t+"` will be removed in a future version.")}renamedMethod(t,e,n){this.deprecationWarning("`"+t+"`’s `"+e+"` method has been renamed to `"+n+"`. Please update your code to use `"+n+"` instead. `"+e+"` will be removed in a future version.")}deprecationWarning(t){this.shouldLog(1)&&this.logErrorHandler("Ably: Deprecation warning - "+t,1)}};tr.defaultLogLevel=1,tr.LOG_NONE=0,tr.LOG_ERROR=1,tr.LOG_MAJOR=2,tr.LOG_MINOR=3,tr.LOG_MICRO=4,tr.logAction=(t,e,n,i)=>{tr.logActionNoStrip(t,e,n,i)};var er=tr,nr={};function ir(t){var e="["+t.constructor.name;return t.message&&(e+=": "+t.message),t.statusCode&&(e+="; statusCode="+t.statusCode),t.code&&(e+="; code="+t.code),t.cause&&(e+="; cause="+Or(t.cause)),!t.href||t.message&&t.message.indexOf("help.ably.io")>-1||(e+="; see "+t.href+" "),e+="]"}((t,e)=>{for(var n in e)$i(t,n,{get:e[n],enumerable:!0})})(nr,{Format:()=>Cr,allSame:()=>Sr,allToLowerCase:()=>$r,allToUpperCase:()=>zr,arrChooseN:()=>jr,arrDeleteValue:()=>yr,arrEquals:()=>Gr,arrIntersect:()=>mr,arrIntersectOb:()=>br,arrPopRandomElement:()=>Tr,arrWithoutValue:()=>wr,cheapRandStr:()=>Dr,containsValue:()=>pr,copy:()=>ar,createMissingPluginError:()=>Xr,dataSizeBytes:()=>Rr,decodeBody:()=>Nr,encodeBody:()=>Lr,ensureArray:()=>lr,forInOwnNonNullProperties:()=>kr,getBackoffCoefficient:()=>qr,getGlobalObject:()=>Wr,getJitterCoefficient:()=>Fr,getRetryTime:()=>Hr,inherits:()=>fr,inspectBody:()=>Pr,inspectError:()=>Or,intersect:()=>gr,isEmpty:()=>hr,isErrorInfoOrPartialErrorInfo:()=>Mr,isNil:()=>dr,isObject:()=>ur,keysArray:()=>xr,listenerToAsyncIterator:()=>ts,matchDerivedChannel:()=>Vr,mixin:()=>or,parseQueryString:()=>Ir,prototypicalClone:()=>vr,randomString:()=>Ur,shallowClone:()=>cr,shallowEquals:()=>Jr,stringifyValues:()=>Er,throwMissingPluginError:()=>Qr,toBase64:()=>Kr,toQueryString:()=>Ar,valuesArray:()=>_r,whenPromiseSettles:()=>Br,withTimeoutAsync:()=>Zr});var rr=class t extends Error{constructor(e,n,i,r){super(e),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,t.prototype),this.code=n,this.statusCode=i,this.cause=r}toString(){return ir(this)}static fromValues(e){var{message:n,code:i,statusCode:r}=e;if("string"!=typeof n||"number"!=typeof i||"number"!=typeof r)throw new Error("ErrorInfo.fromValues(): invalid values: "+Xi.Config.inspect(e));var s=Object.assign(new t(n,i,r),e);return s.code&&!s.href&&(s.href="https://help.ably.io/error/"+s.code),s}},sr=class t extends Error{constructor(e,n,i,r){super(e),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,t.prototype),this.code=n,this.statusCode=i,this.cause=r}toString(){return ir(this)}static fromValues(e){var{message:n,code:i,statusCode:r}=e;if("string"!=typeof n||!dr(i)&&"number"!=typeof i||!dr(r)&&"number"!=typeof r)throw new Error("PartialErrorInfo.fromValues(): invalid values: "+Xi.Config.inspect(e));var s=Object.assign(new t(n,i,r),e);return s.code&&!s.href&&(s.href="https://help.ably.io/error/"+s.code),s}};function or(t){for(var e=0;e<(arguments.length<=1?0:arguments.length-1);e++){var n=e+1<1||arguments.length<=e+1?void 0:arguments[e+1];if(!n)break;for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}function ar(t){return or({},t)}function lr(t){return dr(t)?[]:Array.isArray(t)?t:[t]}function ur(t){return"[object Object]"==Object.prototype.toString.call(t)}function hr(t){for(var e in t)return!1;return!0}function dr(t){return null==t}function cr(t){var e=new Object;for(var n in t)e[n]=t[n];return e}function vr(t,e){class n{}n.prototype=t;var i=new n;return e&&or(i,e),i}var fr=function(t,e){Xi.Config.inherits?Xi.Config.inherits(t,e):(t.super_=e,t.prototype=vr(e.prototype,{constructor:t}))};function pr(t,e){for(var n in t)if(t[n]==e)return!0;return!1}function gr(t,e){return Array.isArray(e)?mr(t,e):br(t,e)}function mr(t,e){for(var n=[],i=0;i<t.length;i++){var r=t[i];-1!=e.indexOf(r)&&n.push(r)}return n}function br(t,e){for(var n=[],i=0;i<t.length;i++){var r=t[i];r in e&&n.push(r)}return n}function yr(t,e){var n=t.indexOf(e),i=-1!=n;return i&&t.splice(n,1),i}function wr(t,e){var n=t.slice();return yr(n,e),n}function xr(t,e){var n=[];for(var i in t)e&&!Object.prototype.hasOwnProperty.call(t,i)||n.push(i);return n}function _r(t,e){var n=[];for(var i in t)e&&!Object.prototype.hasOwnProperty.call(t,i)||n.push(t[i]);return n}function kr(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&t[n]&&e(n)}function Sr(t,e){if(0===t.length)return!0;var n=t[0][e];return t.every(function(t){return t[e]===n})}var Cr=(t=>(t.msgpack="msgpack",t.json="json",t))(Cr||{});function Tr(t){return t.splice((e=t,Math.floor(Math.random()*e.length)),1)[0];var e}function Ar(t){var e=[];if(t)for(var n in t)e.push(encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e.length?"?"+e.join("&"):""}function Er(t){return Object.fromEntries(Object.entries(t).map(t=>{var[e,n]=t;return[e,String(n)]}))}function Ir(t){for(var e,n=/([^?&=]+)=?([^&]*)/g,i={};e=n.exec(t);)i[decodeURIComponent(e[1])]=decodeURIComponent(e[2]);return i}function Mr(t){return"object"==typeof t&&null!==t&&(t instanceof rr||t instanceof sr)}function Or(t){var e,n;return t instanceof Error||"ErrorInfo"===(null==(e=null==t?void 0:t.constructor)?void 0:e.name)||"PartialErrorInfo"===(null==(n=null==t?void 0:t.constructor)?void 0:n.name)?t.toString():Xi.Config.inspect(t)}function Pr(t){return Xi.BufferUtils.isBuffer(t)?t.toString():"string"==typeof t?t:Xi.Config.inspect(t)}function Rr(t){if(Xi.BufferUtils.isBuffer(t))return Xi.BufferUtils.byteLength(t);if("string"==typeof t)return Xi.Config.stringByteSize(t);if("number"==typeof t)return 8;if("boolean"==typeof t)return 1;throw new Error("Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: "+typeof t)}function Dr(){return String(Math.random()).substr(2)}var Ur=function(){var t=u(function*(t){var e=yield Xi.Config.getRandomArrayBuffer(t);return Xi.BufferUtils.base64Encode(e)});return function(e){return t.apply(this,arguments)}}();function jr(t,e){for(var n=Math.min(e,t.length),i=t.slice(),r=[],s=0;s<n;s++)r.push(Tr(i));return r}function Br(t,e){t.then(t=>{null==e||e(null,t)}).catch(t=>{null==e||e(t)})}function Nr(t,e,n){return"msgpack"==n?(e||Qr("MsgPack"),e.decode(t)):JSON.parse(String(t))}function Lr(t,e,n){return"msgpack"==n?(e||Qr("MsgPack"),e.encode(t,!0)):JSON.stringify(t)}function $r(t){return t.map(function(t){return t&&t.toLowerCase()})}function zr(t){return t.map(function(t){return t&&t.toUpperCase()})}function qr(t){return Math.min((t+2)/3,2)}function Fr(){return 1-.2*Math.random()}function Hr(t,e){return t*qr(e)*Fr()}function Wr(){return"undefined"!=typeof global?global:"undefined"!=typeof window?window:self}function Jr(t,e){return Object.keys(t).every(n=>t[n]===e[n])&&Object.keys(e).every(n=>e[n]===t[n])}function Vr(t){var e=t.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!e||!e.length||e.length<5)throw new rr("regex match failed",400,40010);if(e[2])throw new rr("cannot use a derived option with a "+e[2]+" channel",400,40010);return{qualifierParam:e[3]||"",channelName:e[4]}}function Kr(t){var e=Xi.BufferUtils,n=e.utf8Encode(t);return e.base64Encode(n)}function Gr(t,e){return t.length===e.length&&t.every(function(t,n){return t===e[n]})}function Xr(t){return new rr(t+" plugin not provided",40019,400)}function Qr(t){throw Xr(t)}function Zr(t,e,n){return Yr.apply(this,arguments)}function Yr(){return Yr=u(function*(t,e,n){void 0===e&&(e=5e3),void 0===n&&(n="Timeout expired");var i=new rr(n,5e4,500);return Promise.race([t,new Promise((t,n)=>setTimeout(()=>n(i),e))])}),Yr.apply(this,arguments)}function ts(t){return n=(t,i,r,s)=>{try{var o=e[t](i),a=(i=o.value)instanceof Gi,l=o.done;Promise.resolve(a?i[0]:i).then(e=>a?n("return"===t?t:"next",i[1]?{done:e.done,value:e.value}:e,r,s):r({value:e,done:l})).catch(t=>n("throw",t,r,s))}catch(t){s(t)}},i=t=>r[t]=e=>new Promise((i,r)=>n(t,e,i,r)),r={},e=(e=function*(){var e=[],n=null,i=t(t=>{if(n){var i=n;n=null,i(t)}else e.push(t)});try{for(;;)if(e.length>0)yield e.shift();else{if(n)throw new rr("Concurrent next() calls are not supported",4e4,400);var r=yield new Gi(new Promise(t=>{n=t}));yield r}}finally{i()}}).apply(this,null),r[Symbol.asyncIterator]=()=>r,i("next"),i("throw"),i("return"),r;var e,n,i,r}var es="2.17.0",ns={ENDPOINT:"main",ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["main.a.fallback.ably-realtime.com","main.b.fallback.ably-realtime.com","main.c.fallback.ably-realtime.com","main.d.fallback.ably-realtime.com","main.e.fallback.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:es,protocolVersion:5,agent:"ably-js/"+es,getPort:function(t,e){return e||t.tls?t.tlsPort:t.port},getHttpScheme:function(t){return t.tls?"https://":"http://"},getPrimaryDomainFromEndpoint:rs,getEndpointFallbackHosts:ss,getFallbackHosts:as,getHosts:function(t){return[t.primaryDomain].concat(as(t))},checkHost:ls,objectifyOptions:function(t,e,n,i,r){if(void 0===t){var s=e?n+" must be initialized with either a client options object, an Ably API key, or an Ably Token":n+" must be initialized with a client options object";throw er.logAction(i,er.LOG_ERROR,n+"()",s),new Error(s)}var o;if("string"==typeof t)if(-1==t.indexOf(":")){if(!e){var a=n+" cannot be initialized with just an Ably Token; you must provide a client options object with a `plugins` property. (Set this Ably Token as the object’s `token` property.)";throw er.logAction(i,er.LOG_ERROR,n+"()",a),new Error(a)}o={token:t}}else{if(!e){var l=n+" cannot be initialized with just an Ably API key; you must provide a client options object with a `plugins` property. (Set this Ably API key as the object’s `key` property.)";throw er.logAction(i,er.LOG_ERROR,n+"()",l),new Error(l)}o={key:t}}else o=t;r&&(o=Ki(Vi({},o),{plugins:Vi(Vi({},r),o.plugins)}));return o},normaliseOptions:function(t,e,n){var i=null!=n?n:er.defaultLogger;t.environment&&i.deprecated("The `environment` client option","Use the `endpoint` client option instead.");t.restHost&&i.deprecated("The `restHost` client option","Use the `endpoint` client option instead.");t.realtimeHost&&i.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead.");hs(t),"function"==typeof t.recover&&!0===t.closeOnUnload&&(er.logAction(i,er.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),t.recover=void 0);"closeOnUnload"in t||(t.closeOnUnload=!t.recover);"queueMessages"in t||(t.queueMessages=!0);var r=t.endpoint||ns.ENDPOINT;t.fallbackHosts||t.restHost||t.realtimeHost||t.port||t.tlsPort||(t.fallbackHosts=ss(t.environment||r));var s=t.environment&&t.environment+".realtime.ably.net",o=t.restHost||t.realtimeHost||s||rs(r);(t.fallbackHosts||[]).concat(o).forEach(ls),t.port=t.port||ns.PORT,t.tlsPort=t.tlsPort||ns.TLS_PORT,"tls"in t||(t.tls=!0);var a=function(t){var e={};for(var n in ns.TIMEOUTS)e[n]=t[n]||ns.TIMEOUTS[n];return e}(t);t.useBinaryProtocol=!!e&&("useBinaryProtocol"in t?Xi.Config.supportsBinary&&t.useBinaryProtocol:Xi.Config.preferBinary);var l={};t.clientId&&(l["X-Ably-ClientId"]=Xi.BufferUtils.base64Encode(Xi.BufferUtils.utf8Encode(t.clientId)));"idempotentRestPublishing"in t||(t.idempotentRestPublishing=!0);var u=null,h=t.connectivityCheckUrl;if(t.connectivityCheckUrl){var[d,c]=t.connectivityCheckUrl.split("?");u=c?Ir(c):{},-1===d.indexOf("://")&&(d="https://"+d),h=d}var v=t.wsConnectivityCheckUrl;v&&-1===v.indexOf("://")&&(v="wss://"+v);return Ki(Vi({},t),{primaryDomain:o,maxMessageSize:t.maxMessageSize||ns.maxMessageSize,timeouts:a,connectivityCheckParams:u,connectivityCheckUrl:h,wsConnectivityCheckUrl:v,headers:l})},defaultGetHeaders:function(t,e){var{format:n,protocolVersion:i=vs.protocolVersion}=void 0===e?{}:e;return{accept:cs[null!=n?n:t.useBinaryProtocol?"msgpack":"json"],"X-Ably-Version":i.toString(),"Ably-Agent":us(t)}},defaultPostHeaders:function(t,e){var{format:n,protocolVersion:i=vs.protocolVersion}=void 0===e?{}:e,r=cs[null!=n?n:t.useBinaryProtocol?"msgpack":"json"];return{accept:r,"content-type":r,"X-Ably-Version":i.toString(),"Ably-Agent":us(t)}}};function is(t){return t.includes(".")||t.includes("::")||"localhost"===t}function rs(t){return is(t)?t:t.startsWith("nonprod:")?t.replace("nonprod:","")+".realtime.ably-nonprod.net":t+".realtime.ably.net"}function ss(t){return is(t)?[]:t.startsWith("nonprod:")?os(t.replace("nonprod:",""),"ably-realtime-nonprod.com"):os(t,"ably-realtime.com")}function os(t,e){return["a","b","c","d","e"].map(n=>t+"."+n+".fallback."+e)}function as(t){var e=t.fallbackHosts,n=void 0!==t.httpMaxRetryCount?t.httpMaxRetryCount:ns.httpMaxRetryCount;return e?jr(e,n):[]}function ls(t){if("string"!=typeof t)throw new rr("host must be a string; was a "+typeof t,4e4,400);if(!t.length)throw new rr("host must not be zero-length",4e4,400)}function us(t){var e=ns.agent;if(t.agents)for(var n in t.agents)e+=" "+n+"/"+t.agents[n];return e}function hs(t){if(t.endpoint&&(t.environment||t.restHost||t.realtimeHost))throw new rr("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(t.environment&&(t.restHost||t.realtimeHost))throw new rr("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function ds(t,e,n){var i=n||{};if(i.cipher){t||Qr("Crypto");var r=t.getCipher(i.cipher,e);i.cipher=r.cipherParams,i.channelCipher=r.cipher}else"cipher"in i&&(i.cipher=void 0,i.channelCipher=null);return i}var cs={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},vs={protocolVersion:ns.protocolVersion};var fs=ns;var ps=class t{constructor(t,e){this.logger=t,this.members=e||[]}call(t,e){for(var n of this.members)if(n)try{n(t,e)}catch(t){er.logAction(this.logger,er.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+t+"; stack = "+t.stack)}}push(){this.members.push(...arguments)}createPromise(){return new Promise((t,e)=>{this.push((n,i)=>{n?e(n):t(i)})})}resolveAll(t){this.call(null,t)}rejectAll(t){this.call(t)}static create(e,n){var i=new t(e,n);return Object.assign((t,e)=>i.call(t,e),{push:t=>i.push(t),createPromise:()=>i.createPromise(),resolveAll:t=>i.resolveAll(t),rejectAll:t=>i.rejectAll(t)})}},gs=(t=>(t.Get="get",t.Delete="delete",t.Post="post",t.Put="put",t.Patch="patch",t))(gs||{}),ms=gs,bs=(t=>(t[t.Success=200]="Success",t[t.NoContent=204]="NoContent",t[t.BadRequest=400]="BadRequest",t[t.Unauthorized=401]="Unauthorized",t[t.Forbidden=403]="Forbidden",t[t.RequestTimeout=408]="RequestTimeout",t[t.InternalServerError=500]="InternalServerError",t))(bs||{});var ys=bs,ws=Math.pow(2,17);function xs(t){return Mr(t)?(t.code||(403===t.statusCode?t.code=40300:(t.code=40170,t.statusCode=401)),t):new rr(Or(t),t.code||40170,t.statusCode||401)}function _s(t){if(!t)return"";"string"==typeof t&&(t=JSON.parse(t));var e=Object.create(null),n=xr(t,!0);if(!n)return"";n.sort();for(var i=0;i<n.length;i++)e[n[i]]=t[n[i]].sort();return JSON.stringify(e)}function ks(t,e){if(t.authCallback);else if(t.authUrl);else if(t.key);else if(!t.tokenDetails){var n="authOptions must include valid authentication parameters";throw er.logAction(e,er.LOG_ERROR,"Auth()",n),new Error(n)}}var Ss=0;var Cs=class{constructor(t,e){if(this.authOptions={},this.client=t,this.tokenParams=e.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,function(t){return t.useTokenAuth||!function(t){return"useTokenAuth"in t&&!t.useTokenAuth}(t)&&(t.authCallback||t.authUrl||t.token||t.tokenDetails)}(e))(function(t){return!t.key&&!t.authCallback&&!t.authUrl})(e)&&er.logAction(this.logger,er.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this.I(e.defaultTokenParams,e),ks(this.authOptions,this.logger);else{if(!e.key){var n="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw er.logAction(this.logger,er.LOG_ERROR,"Auth()",n),new rr(n,40160,401)}this.M(e)}}get logger(){return this.client.logger}authorize(t,e){var n=this;return u(function*(){if(e&&e.key&&n.authOptions.key!==e.key)throw new rr("Unable to update auth options with incompatible key",40102,401);try{var i=yield n.O(null!=t?t:null,null!=e?e:null);return n.client.connection?new Promise((t,e)=>{n.client.connection.connectionManager.onAuthUpdated(i,(n,i)=>n?e(n):t(i))}):i}catch(t){throw n.client.connection&&t.statusCode===ys.Forbidden&&n.client.connection.connectionManager.actOnErrorFromAuthorize(t),t}})()}O(t,e){var n=this;return u(function*(){n.tokenDetails=null,n.I(t,e),ks(n.authOptions,n.logger);try{return n.P(!0)}finally{delete n.tokenParams.timestamp,delete n.authOptions.queryTime}})()}requestToken(t,e){var n=this;return u(function*(){var i,r=e||n.authOptions,s=t||ar(n.tokenParams),o=n.client;if(r.authCallback)i=r.authCallback;else if(r.authUrl)i=(t,e)=>{var i,s=or({accept:"application/json, text/plain"},r.authHeaders),o=r.authMethod&&"post"===r.authMethod.toLowerCase(),a=r.authUrl.indexOf("?");a>-1&&(i=Ir(r.authUrl.slice(a)),r.authUrl=r.authUrl.slice(0,a),o||(r.authParams=or(i,r.authParams)));var l=or({},r.authParams||{},t),u=t=>{var n,i,r=null!=(n=t.body)?n:null,s=null;if(t.error);else{var o=null!=(i=t.headers["content-type"])?i:null;s=Array.isArray(o)?o.join(", "):o}if(t.error)e(t.error,null);else if(t.unpacked)e(null,r);else if(Xi.BufferUtils.isBuffer(r)&&(r=r.toString()),s){var a=s.indexOf("application/json")>-1,l=s.indexOf("text/plain")>-1||s.indexOf("application/jwt")>-1;if(a||l){if(a){if(r.length>ws)return void e(new rr("authUrl response exceeded max permitted length",40170,401),null);try{r=JSON.parse(r)}catch(t){return void e(new rr("Unexpected error processing authURL response; err = "+t.message,40170,401),null)}}e(null,r,s)}else e(new rr("authUrl responded with unacceptable content-type "+s+", should be either text/plain, application/jwt or application/json",40170,401),null)}else e(new rr("authUrl response is missing a content-type header",40170,401),null)};if(o){var h=s||{};h["content-type"]="application/x-www-form-urlencoded";var d=Ar(l).slice(1);Br(n.client.http.doUri(ms.Post,r.authUrl,h,d,i),(t,e)=>u(t||e))}else Br(n.client.http.doUri(ms.Get,r.authUrl,s||{},null,l),(t,e)=>u(t||e))};else{if(!r.key){throw er.logAction(n.logger,er.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),new rr("Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)",40171,403)}i=(t,e)=>{Br(n.createTokenRequest(t,r),(t,n)=>e(t,null!=n?n:null))}}"capability"in s&&(s.capability=_s(s.capability));return new Promise((t,e)=>{var a=!1,l=n.client.options.timeouts.realtimeRequestTimeout,u=setTimeout(()=>{a=!0;var t="Token request callback timed out after "+l/1e3+" seconds";er.logAction(n.logger,er.LOG_ERROR,"Auth.requestToken()",t),e(new rr(t,40170,401))},l);i(s,(i,s,l)=>{if(!a){if(clearTimeout(u),i)return er.logAction(n.logger,er.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+Or(i)),void e(xs(i));if("string"!=typeof s){if("object"!=typeof s||null===s){var h="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof s;return er.logAction(n.logger,er.LOG_ERROR,"Auth.requestToken()",h),void e(new rr(h,40170,401))}var d=JSON.stringify(s).length;if(d>ws&&!r.suppressMaxLengthCheck)e(new rr("Token request/details object exceeded max permitted stringified size (was "+d+" bytes)",40170,401));else if("issued"in s)t(s);else{if(!("keyName"in s)){var c="Expected token request callback to call back with a token string, token request object, or token details object";return er.logAction(n.logger,er.LOG_ERROR,"Auth.requestToken()",c),void e(new rr(c,40170,401))}var v,f,p,g;f=(i,r,s)=>{if(i)return er.logAction(n.logger,er.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+Or(i)),void e(xs(i));s||(r=JSON.parse(r)),t(r)},p="/keys/"+(v=s).keyName+"/requestToken",g=fs.defaultPostHeaders(n.client.options,{format:"json"}),r.requestHeaders&&or(g,r.requestHeaders),Br(n.client.http.do(ms.Post,function(t){return o.baseUri(t)+p},g,JSON.stringify(v),null),(t,e)=>t?f(t):f(e.error,e.body,e.unpacked))}}else 0===s.length?e(new rr("Token string is empty",40170,401)):s.length>ws?e(new rr("Token string exceeded max permitted length (was "+s.length+" bytes)",40170,401)):"undefined"===s||"null"===s?e(new rr("Token string was literal null/undefined",40170,401)):"{"!==s[0]||l&&l.indexOf("application/jwt")>-1?t({token:s}):e(new rr("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401))}})})})()}createTokenRequest(t,e){var n=this;return u(function*(){e=e||n.authOptions,t=t||ar(n.tokenParams);var i=e.key;if(!i)throw new rr("No key specified",40101,403);var r=i.split(":"),s=r[0],o=r[1];if(!o)throw new rr("Invalid key specified",40101,403);if(""===t.clientId)throw new rr("clientId can’t be an empty string",40012,400);"capability"in t&&(t.capability=_s(t.capability));var a=or({keyName:s},t),l=t.clientId||"",u=t.ttl||"",h=t.capability||"";a.timestamp||(a.timestamp=yield n.R(e&&e.queryTime));var d=a.nonce||(a.nonce=("000000"+Math.floor(1e16*Math.random())).slice(-16)),c=a.timestamp,v=a.keyName+"\n"+u+"\n"+h+"\n"+l+"\n"+c+"\n"+d+"\n";return a.mac=a.mac||((t,e)=>{var n=Xi.BufferUtils,i=n.utf8Encode(t),r=n.utf8Encode(e),s=n.hmacSha256(i,r);return n.base64Encode(s)})(v,o),a})()}getAuthParams(){var t=this;return u(function*(){if("basic"==t.method)return{key:t.key};var e=yield t.P(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:e.token}})()}getAuthHeaders(){var t=this;return u(function*(){if("basic"==t.method)return{authorization:"Basic "+t.basicKey};var e=yield t.P(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+Kr(e.token)}})()}M(t){this.method="basic",this.key=t.key,this.basicKey=Kr(t.key),this.authOptions=t||{},"clientId"in t&&this.D(t.clientId)}I(t,e){this.method="token",t&&(this.tokenParams=t),e&&(e.token&&(e.tokenDetails="string"==typeof e.token?{token:e.token}:e.token),e.tokenDetails&&(this.tokenDetails=e.tokenDetails),"clientId"in e&&this.D(e.clientId),this.authOptions=e)}P(t){var e=this;return u(function*(){var n=e.tokenDetails;if(n){if(e.j(n.clientId))throw new rr("Mismatch between clientId in token ("+n.clientId+") and current clientId ("+e.clientId+")",40102,403);if(!e.client.isTimeOffsetSet()||!n.expires||n.expires>=e.client.getTimestampUsingOffset())return n;e.tokenDetails=null}var i=(e.waitingForTokenRequest||(e.waitingForTokenRequest=ps.create(e.logger))).createPromise();if(null!==e.currentTokenRequestId&&!t)return i;var r,s=e.currentTokenRequestId=Ss++,o=null;try{r=yield e.requestToken(e.tokenParams,e.authOptions)}catch(t){o=t}if(e.currentTokenRequestId>s)return i;e.currentTokenRequestId=null;var a=e.waitingForTokenRequest;return e.waitingForTokenRequest=null,o?(null==a||a.rejectAll(o),i):(null==a||a.resolveAll(e.tokenDetails=r),i)})()}D(t){if("string"!=typeof t&&null!==t)throw new rr("clientId must be either a string or null",40012,400);if("*"===t)throw new rr('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);var e=this.B(t);if(e)throw e}B(t){if(this.j(t)){var e="Unexpected clientId mismatch: client has "+this.clientId+", requested "+t,n=new rr(e,40102,401);return er.logAction(this.logger,er.LOG_ERROR,"Auth._uncheckedSetClientId()",e),n}return this.clientId=this.tokenParams.clientId=t,null}j(t){return!(!this.clientId||"*"===this.clientId||!t||"*"===t||this.clientId===t)}static isTokenErr(t){return t.code&&t.code>=40140&&t.code<40150}revokeTokens(t,e){return this.client.rest.revokeTokens(t,e)}R(t){var e=this;return u(function*(){return e.client.getTimestamp(t||!!e.authOptions.queryTime)})()}};function Ts(t){var e=[];if(t)for(var n in t)e.push(n+"="+t[n]);return e.join("&")}function As(t,e){return t+(e?"?":"")+Ts(e)}var Es=class{constructor(t){this.client=t,this.platformHttp=new Xi.Http(t),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var t,e;return null!=(e=null==(t=this.client)?void 0:t.logger)?e:er.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}L(t){var e=t.connection,n=e&&e.connectionManager.host;return n?[n].concat(fs.getFallbackHosts(t.options)):fs.getHosts(t.options)}do(t,e,n,i,r){var s=this;return u(function*(){try{var o=s.client;if(!o)return{error:new rr("http.do called without client",5e4,500)};var a="function"==typeof e?e:function(t){return o.baseUri(t)+e},l=o.$;if(l){if(l.validUntil>Date.now()){var h=yield s.doUri(t,a(l.host),n,i,r);return h.error&&s.platformHttp.shouldFallback(h.error)?(o.$=null,s.do(t,e,n,i,r)):h}o.$=null}var d=s.L(o);if(1===d.length)return s.doUri(t,a(d[0]),n,i,r);var c=null,v=function(){var e=u(function*(e,l){var u=e.shift();c=null!=c?c:new Date;var h=yield s.doUri(t,a(u),n,i,r);return h.error&&s.platformHttp.shouldFallback(h.error)&&e.length?Date.now()-c.getTime()>o.options.timeouts.httpMaxRetryDuration?{error:new rr("Timeout for trying fallback hosts retries. Total elapsed time exceeded the "+o.options.timeouts.httpMaxRetryDuration+"ms limit",50003,500)}:v(e,!0):(l&&(o.$={host:u,validUntil:Date.now()+o.options.timeouts.fallbackRetryTimeout}),h)});return function(t,n){return e.apply(this,arguments)}}();return v(d)}catch(t){return{error:new rr("Unexpected error in Http.do: "+Or(t),500,5e4)}}})()}doUri(t,e,n,i,r){var s=this;return u(function*(){try{!function(t,e,n,i,r){r.shouldLog(er.LOG_MICRO)&&er.logActionNoStrip(r,er.LOG_MICRO,"Http."+t+"()","Sending; "+As(e,i)+"; Body"+(Xi.BufferUtils.isBuffer(n)?" (Base64): "+Xi.BufferUtils.base64Encode(n):": "+n))}(t,e,i,r,s.logger);var o=yield s.platformHttp.doUri(t,e,n,i,r);return s.logger.shouldLog(er.LOG_MICRO)&&function(t,e,n,i,r){t.error?er.logActionNoStrip(r,er.LOG_MICRO,"Http."+e+"()","Received Error; "+As(n,i)+"; Error: "+Or(t.error)):er.logActionNoStrip(r,er.LOG_MICRO,"Http."+e+"()","Received; "+As(n,i)+"; Headers: "+Ts(t.headers)+"; StatusCode: "+t.statusCode+"; Body"+(Xi.BufferUtils.isBuffer(t.body)?" (Base64): "+Xi.BufferUtils.base64Encode(t.body):": "+t.body))}(o,t,e,r,s.logger),o}catch(t){return{error:new rr("Unexpected error in Http.doUri: "+Or(t),500,5e4)}}})()}};function Is(t,e,n){for(var i,r,s,o=0;o<t.length;o++)if(i=t[o],n&&(i=i[n]),Array.isArray(i)){for(;-1!==(r=i.indexOf(e));)i.splice(r,1);n&&0===i.length&&delete t[o][n]}else if(ur(i))for(s in i)Object.prototype.hasOwnProperty.call(i,s)&&Array.isArray(i[s])&&Is([i],e,s)}var Ms=class{constructor(t){this.logger=t,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];if(1===e.length){var i=e[0];if("function"!=typeof i)throw new Error("EventListener.on(): Invalid arguments: "+Xi.Config.inspect(e));this.any.push(i)}if(2===e.length){var[r,s]=e;if("function"!=typeof s)throw new Error("EventListener.on(): Invalid arguments: "+Xi.Config.inspect(e));if(dr(r))this.any.push(s);else if(Array.isArray(r))r.forEach(t=>{this.on(t,s)});else{if("string"!=typeof r)throw new Error("EventListener.on(): Invalid arguments: "+Xi.Config.inspect(e));(this.events[r]||(this.events[r]=[])).push(s)}}}off(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];if(0==e.length||dr(e[0])&&dr(e[1]))return this.any=[],this.events=Object.create(null),this.anyOnce=[],void(this.eventsOnce=Object.create(null));var[i,r]=e,s=null,o=null;if(1!==e.length&&r){if("function"!=typeof r)throw new Error("EventEmitter.off(): invalid arguments:"+Xi.Config.inspect(e));[o,s]=[i,r]}else"function"==typeof i?s=i:o=i;if(s&&dr(o))Is([this.any,this.events,this.anyOnce,this.eventsOnce],s);else if(Array.isArray(o))o.forEach(t=>{this.off(t,s)});else{if("string"!=typeof o)throw new Error("EventEmitter.off(): invalid arguments:"+Xi.Config.inspect(e));s?Is([this.events,this.eventsOnce],s,o):(delete this.events[o],delete this.eventsOnce[o])}}listeners(t){if(t){var e=this.events[t]||[];return this.eventsOnce[t]&&Array.prototype.push.apply(e,this.eventsOnce[t]),e.length?e:null}return this.any.length?this.any:null}emit(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];var r={event:t},s=[];this.anyOnce.length&&(Array.prototype.push.apply(s,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(s,this.any);var o=this.eventsOnce[t];o&&(Array.prototype.push.apply(s,o),delete this.eventsOnce[t]);var a=this.events[t];a&&Array.prototype.push.apply(s,a),s.forEach(t=>{!function(t,e,n,i){try{n.apply(e,i)}catch(e){er.logAction(t,er.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+e+"; stack = "+(e&&e.stack))}}(this.logger,r,t,n)})}once(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];var i=e.length;if(0===i||1===i&&"function"!=typeof e[0]){var r=e[0];return new Promise(t=>{this.once(r,t)})}var[s,o]=e;if(1===e.length&&"function"==typeof s)this.anyOnce.push(s);else if(dr(s)){if("function"!=typeof o)throw new Error("EventEmitter.once(): Invalid arguments:"+Xi.Config.inspect(e));this.anyOnce.push(o)}else if(Array.isArray(s)){var a=this,l=function(){var t=Array.prototype.slice.call(arguments);if(s.forEach(function(t){a.off(t,l)}),"function"!=typeof o)throw new Error("EventEmitter.once(): Invalid arguments:"+Xi.Config.inspect(e));o.apply(this,t)};s.forEach(function(t){a.on(t,l)})}else{if("string"!=typeof s)throw new Error("EventEmitter.once(): Invalid arguments:"+Xi.Config.inspect(e));var u=this.eventsOnce[s]||(this.eventsOnce[s]=[]);if(o){if("function"!=typeof o)throw new Error("EventEmitter.once(): Invalid arguments:"+Xi.Config.inspect(e));u.push(o)}}}whenState(t,e){var n=this;return u(function*(){if("string"!=typeof t||"string"!=typeof e)throw new Error("whenState requires a valid state String argument");return t===e?null:n.once(t)})()}},Os={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18,OBJECT:19,OBJECT_SYNC:20,ANNOTATION:21},Ps=[];Object.keys(Os).forEach(function(t){Ps[Os[t]]=t});var Rs={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,HAS_OBJECTS:128,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19,ANNOTATION_PUBLISH:1<<21,ANNOTATION_SUBSCRIBE:1<<22,OBJECT_SUBSCRIBE:1<<24,OBJECT_PUBLISH:1<<25},Ds=Object.keys(Rs);Rs.MODE_ALL=Rs.PRESENCE|Rs.PUBLISH|Rs.SUBSCRIBE|Rs.PRESENCE_SUBSCRIBE|Rs.ANNOTATION_PUBLISH|Rs.ANNOTATION_SUBSCRIBE|Rs.OBJECT_SUBSCRIBE|Rs.OBJECT_PUBLISH;var Us=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function js(){return(js=u(function*(t,e){var{data:n,encoding:i}=yield Bs(t.data,t.encoding,e);return t.data=n,t.encoding=i,t})).apply(this,arguments)}function Bs(t,e,n){return Ns.apply(this,arguments)}function Ns(){return(Ns=u(function*(t,e,n){var i=n.channelCipher,r=t,s=e?e+"/":"";return Xi.BufferUtils.isBuffer(r)||(r=Xi.BufferUtils.utf8Encode(String(r)),s+="utf-8/"),{data:yield i.encrypt(r),encoding:s=s+"cipher+"+i.algorithm}})).apply(this,arguments)}function Ls(){return Ls=u(function*(t,e){var{data:n,encoding:i}=$s(t.data,t.encoding);return t.data=n,t.encoding=i,null!=e&&e.cipher?function(t,e){return js.apply(this,arguments)}(t,e):t}),Ls.apply(this,arguments)}function $s(t,e){if("string"==typeof t||Xi.BufferUtils.isBuffer(t)||null==t)return{data:t,encoding:e};if(ur(t)||Array.isArray(t))return{data:JSON.stringify(t),encoding:e?e+"/json":"json"};throw new rr("Data type is unsupported",40013,400)}function zs(){return(zs=u(function*(t,e){var{data:n,encoding:i,error:r}=yield qs(t.data,t.encoding,e);if(t.data=n,t.encoding=i,r)throw r})).apply(this,arguments)}function qs(t,e,n){return Fs.apply(this,arguments)}function Fs(){return Fs=u(function*(t,e,n){var i,r=function(t){return t&&t.channelOptions?t:{channelOptions:t,plugins:{},baseEncodedPreviousPayload:void 0}}(n),s=t,o=t,a=e;if(e){var l,u=e.split("/"),h=u.length,d="";try{for(;(l=h)>0;){var c=u[--h].match(/([-\w]+)(\+([\w-]+))?/);if(!c)break;switch(d=c[1]){case"base64":o=Xi.BufferUtils.base64Decode(String(o)),l==u.length&&(s=o);continue;case"utf-8":o=Xi.BufferUtils.utf8Decode(o);continue;case"json":o=JSON.parse(o);continue;case"cipher":if(null!=r.channelOptions&&r.channelOptions.cipher&&r.channelOptions.channelCipher){var v=c[3],f=r.channelOptions.channelCipher;if(v!=f.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");o=yield f.decrypt(o);continue}throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!r.plugins||!r.plugins.vcdiff)throw new rr("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if("undefined"==typeof Uint8Array)throw new rr("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{var p=r.baseEncodedPreviousPayload;"string"==typeof p&&(p=Xi.BufferUtils.utf8Encode(p));var g=Xi.BufferUtils.toBuffer(p);o=Xi.BufferUtils.toBuffer(o),s=o=Xi.BufferUtils.arrayBufferViewToBuffer(r.plugins.vcdiff.decode(o,g))}catch(t){throw new rr("Vcdiff delta decode failed with "+t,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(t){var m=t;i=new rr("Error processing the "+d+" encoding, decoder returned ‘"+m.message+"’",m.code||40013,400)}finally{a=l<=0?null:u.slice(0,l).join("/")}}return i?{error:i,data:o,encoding:a}:(r.baseEncodedPreviousPayload=s,{data:o,encoding:a})}),Fs.apply(this,arguments)}function Hs(){var t=arguments.length>0?"json":"msgpack",{data:e,encoding:n}=Ws(this.data,this.encoding,t);return Object.assign({},this,{encoding:n,data:e})}function Ws(t,e,n){return t&&Xi.BufferUtils.isBuffer(t)?"msgpack"===n?{data:Xi.BufferUtils.toBuffer(t),encoding:e}:{data:Xi.BufferUtils.base64Encode(t),encoding:e?e+"/base64":"base64"}:{data:t,encoding:e}}var Js={encryptData:Bs,encodeData:$s,encodeDataForWire:Ws,decodeData:qs};function Vs(t){var e,{id:n,connectionId:i,timestamp:r}=t;switch(t.action){case Os.MESSAGE:e=t.messages;break;case Os.PRESENCE:case Os.SYNC:e=t.presence;break;case Os.ANNOTATION:e=t.annotations;break;case Os.OBJECT:case Os.OBJECT_SYNC:e=t.state;break;default:throw new rr("Unexpected action "+t.action,4e4,400)}for(var s=0;s<e.length;s++){var o=e[s];o.connectionId||(o.connectionId=i),o.timestamp||(o.timestamp=r),n&&!o.id&&(o.id=n+":"+s)}}function Ks(t,e){var n="["+e;for(var i in t)"data"===i?"string"==typeof t.data?n+="; data="+t.data:Xi.BufferUtils.isBuffer(t.data)?n+="; data (buffer)="+Xi.BufferUtils.base64Encode(t.data):void 0!==t.data&&(n+="; data (json)="+JSON.stringify(t.data)):!i||"extras"!==i&&"operation"!==i?"version"===i?n+="; version="+JSON.stringify(t[i]):"annotations"===i?n+="; annotations="+JSON.stringify(t[i]):void 0!==t[i]&&(n+="; "+i+"="+t[i]):n+="; "+i+"="+JSON.stringify(t[i]);return n+="]"}var Gs=class{},Xs=class{constructor(t){var e,n,i,r,s,o,a,l,u,h;this.Platform=Xi,this.ErrorInfo=rr,this.Logger=er,this.Defaults=fs,this.Utils=nr,this.EventEmitter=Ms,this.MessageEncoding=Js,this.q=null!=(e=t.plugins)?e:null,this.logger=new er,this.logger.setLog(t.logLevel,t.logHandler),this.F=null!=(i=null==(n=t.plugins)?void 0:n.MsgPack)?i:null;var d=this.options=fs.normaliseOptions(t,this.F,this.logger);if(d.key){var c=d.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!c){var v="invalid key parameter";throw er.logAction(this.logger,er.LOG_ERROR,"BaseClient()",v),new rr(v,40400,404)}d.keyName=c[1],d.keySecret=c[2]}if("clientId"in d){if("string"!=typeof d.clientId&&null!==d.clientId)throw new rr("clientId must be either a string or null",40012,400);if("*"===d.clientId)throw new rr('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}this.$=null,this.serverTimeOffset=null,this.http=new Es(this),this.auth=new Cs(this,d),this.H=(null==(r=t.plugins)?void 0:r.Rest)?new t.plugins.Rest(this):null,this.J=null!=(o=null==(s=t.plugins)?void 0:s.Crypto)?o:null,this.__FilteredSubscriptions=null!=(l=null==(a=t.plugins)?void 0:a.MessageInteractions)?l:null,this.V=null!=(h=null==(u=t.plugins)?void 0:u.Annotations)?h:null}get rest(){return this.H||Qr("Rest"),this.H}get K(){return this.__FilteredSubscriptions||Qr("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var t;return(null==(t=this.options.plugins)?void 0:t.Push)&&this.push.LocalDevice||Qr("Push"),this.G||(this.G=this.push.LocalDevice.load(this)),this.G}baseUri(t){return fs.getHttpScheme(this.options)+t+":"+fs.getPort(this.options,!1)}stats(t){var e=this;return u(function*(){return e.rest.stats(t)})()}time(t){var e=this;return u(function*(){return e.rest.time(t)})()}request(t,e,n,i,r,s){var o=this;return u(function*(){return o.rest.request(t,e,n,i,r,s)})()}batchPublish(t){return this.rest.batchPublish(t)}batchPresence(t){return this.rest.batchPresence(t)}setLog(t){this.logger.setLog(t.level,t.handler)}getTimestamp(t){var e=this;return u(function*(){return!e.isTimeOffsetSet()&&t?e.time():e.getTimestampUsingOffset()})()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return null!==this.serverTimeOffset}};Xs.Platform=Xi;var Qs=Xs,Zs=["message.create","message.update","message.delete","meta","message.summary","message.append"];function Ys(t){var e=0;return t.name&&(e+=t.name.length),t.clientId&&(e+=t.clientId.length),t.extras&&(e+=JSON.stringify(t.extras).length),t.data&&(e+=Rr(t.data)),e}function to(){return(to=u(function*(t,e){return Promise.all(t.map(t=>t.encode(e)))})).apply(this,arguments)}var eo=class t extends Gs{expandFields(){if(this.version||(this.version={}),!this.version.serial&&this.serial&&(this.version.serial=this.serial),!this.version.timestamp&&this.timestamp&&(this.version.timestamp=this.timestamp),this.annotations?this.annotations.summary||(this.annotations.summary={}):this.annotations={summary:{}},this.annotations&&this.annotations.summary)for(var[t,e]of Object.entries(this.annotations.summary))if(t.endsWith(":distinct.v1")||t.endsWith(":unique.v1")||t.endsWith(":multiple.v1"))for(var[,n]of Object.entries(e))n.clipped||(n.clipped=!1);else t.endsWith(":flag.v1")&&(e.clipped||(e.clipped=!1))}encode(t){var e=this;return u(function*(){return function(t,e){return Ls.apply(this,arguments)}(Object.assign(new no,e,{action:Zs.indexOf(e.action||"message.create")}),t)})()}static fromValues(e){return Object.assign(new t,e)}static fromValuesArray(e){return e.map(e=>t.fromValues(e))}toString(){return Ks(this,"Message")}},no=class t extends Gs{toJSON(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return Hs.call(this,...e)}static fromValues(e){return Object.assign(new t,e)}static fromValuesArray(e){return e.map(e=>t.fromValues(e))}decodeWithErr(t,e){var n=this;return u(function*(){var i,r,s=Object.assign(new eo,Ki(Vi({},n),{action:(i=n.action,Zs[i||0]||"unknown")}));try{yield function(t,e){return zs.apply(this,arguments)}(s,t)}catch(t){er.logAction(e,er.LOG_ERROR,"WireMessage.decode()",Or(t)),r=t}return s.expandFields(),{decoded:s,err:r}})()}decode(t,e){var n=this;return u(function*(){var{decoded:i}=yield n.decodeWithErr(t,e);return i})()}toString(){return Ks(this,"WireMessage")}},io=eo,ro=class{constructor(t,e,n,i,r){this.previous=t,this.current=e,"attached"===e&&(this.resumed=n,this.hasBacklog=i),r&&(this.reason=r)}},so=function(){};function oo(t){var e=t||{},{agent:n}=e;return((t,e)=>{var n={};for(var i in t)Hi.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(null!=t&&Fi)for(var i of Fi(t))e.indexOf(i)<0&&Wi.call(t,i)&&(n[i]=t[i]);return n})(e,["agent"])}var ao=class t extends Ms{constructor(t,e,n){var i,r,s;super(t.logger),this.X=null,this.Y=0,this.retryCount=0,this.history=function(){var t=u(function*(t){var e=this.client.rest.channelMixin;if(t&&t.untilAttach){if("attached"!==this.state)throw new rr("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new rr("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete t.untilAttach,t.from_serial=this.properties.attachSerial}return e.history(this,t)});return function(e){return t.apply(this,arguments)}}(),this.whenState=t=>Ms.prototype.whenState.call(this,t,this.state),this.name=e,this.channelOptions=ds(null!=(i=t.J)?i:null,this.logger,n),this.client=t,this.tt=t.et?new t.et.RealtimePresence(this):null,t.V&&(this.X=new t.V.RealtimeAnnotations(this)),this.connectionManager=t.connection.connectionManager,this.state="initialized",this.subscriptions=new Ms(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(n),this.errorReason=null,this.nt=!1,this.it={channelOptions:this.channelOptions,plugins:t.options.plugins||{},baseEncodedPreviousPayload:void 0},this.rt={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this.st=new Ms(this.logger),(null==(r=t.options.plugins)?void 0:r.Push)&&(this.ot=new t.options.plugins.Push.PushChannel(this)),(null==(s=t.options.plugins)?void 0:s.LiveObjects)&&(this.lt=new t.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this.tt||Qr("RealtimePresence"),this.tt}get annotations(){return this.X||Qr("Annotations"),this.X}get push(){return this.ot||Qr("Push"),this.ot}get object(){return this.lt||Qr("LiveObjects"),this.lt}invalidStateError(){return new rr("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(t){return"function"==typeof(t=Array.prototype.slice.call(t))[0]&&t.unshift(null),t}setOptions(t){var e=this;return u(function*(){var n,i=e.channelOptions,r=function(t){if(t&&"params"in t&&!ur(t.params))return new rr("options.params must be an object",4e4,400);if(t&&"modes"in t){if(!Array.isArray(t.modes))return new rr("options.modes must be an array",4e4,400);for(var e=0;e<t.modes.length;e++){var n=t.modes[e];if(!n||"string"!=typeof n||!Us.includes(String.prototype.toUpperCase.call(n)))return new rr("Invalid channel mode: "+n,4e4,400)}}}(t);if(r)throw r;if(e.channelOptions=ds(null!=(n=e.client.J)?n:null,e.logger,t),e.it&&(e.it.channelOptions=e.channelOptions),e.ut(t,i))return e.attachImpl(),new Promise((t,n)=>{e.st.once(["attached","update","detached","failed"],function(e){switch(this.event){case"update":case"attached":t();break;default:n(e.reason)}})})})()}ut(t,e){if("attached"!==this.state&&"attaching"!==this.state)return!1;if(null==t?void 0:t.params){var n=oo(t.params),i=oo(e.params);if(Object.keys(n).length!==Object.keys(i).length)return!0;if(!Jr(i,n))return!0}return!(!(null==t?void 0:t.modes)||e.modes&&Gr(t.modes,e.modes))}publish(){var t=arguments,e=this;return u(function*(){var n,i,r=t.length<=0?void 0:t[0],s=t.length<=1?void 0:t[1];if("string"==typeof r||null==r)n=[io.fromValues({name:r,data:s})],i=t.length<=2?void 0:t[2];else if(ur(r))n=[io.fromValues(r)],i=t.length<=1?void 0:t[1];else{if(!Array.isArray(r))throw new rr("The single-argument form of publish() expects a message object or an array of message objects",40013,400);n=io.fromValuesArray(r),i=t.length<=1?void 0:t[1]}var o=e.client.options.maxMessageSize,a=yield function(t,e){return to.apply(this,arguments)}(n,e.channelOptions),l=function(t){for(var e,n=0,i=0;i<t.length;i++)n+=(e=t[i]).size||(e.size=Ys(e));return n}(a);if(l>o)throw new rr("Maximum size of messages that can be published at once exceeded (was "+l+" bytes; limit is "+o+" bytes)",40009,400);e.throwIfUnpublishableState();var u=co({action:Os.MESSAGE,channel:e.name,messages:a,params:i?Er(i):void 0});return(yield e.sendMessage(u))||{serials:[]}})()}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if("failed"===this.state||"suspended"===this.state)throw this.invalidStateError()}onEvent(t){for(var e=this.subscriptions,n=0;n<t.length;n++){var i=t[n];e.emit(i.name,i)}}attach(){var t=this;return u(function*(){return"attached"===t.state?null:new Promise((e,n)=>{t.ht(!1,null,(t,i)=>t?n(t):e(i))})})()}ht(t,e,n){n||(n=t=>{t&&er.logAction(this.logger,er.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+t.toString())});var i=this.connectionManager;i.activeState()?(("attaching"!==this.state||t)&&this.requestState("attaching",e),this.once(function(t){switch(this.event){case"attached":null==n||n(null,t);break;case"detached":case"suspended":case"failed":null==n||n(t.reason||i.getError()||new rr("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":null==n||n(new rr("Attach request superseded by a subsequent detach request",9e4,409))}})):n(i.getError())}attachImpl(){var t=co({action:Os.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&t.encodeModesToFlags(zr(this.channelOptions.modes)),this.nt&&t.setFlag("ATTACH_RESUME"),this.rt.decodeFailureRecoveryInProgress&&(t.channelSerial=this.rt.protocolMessageChannelSerial),this.sendMessage(t).catch(so)}detach(){var t=this;return u(function*(){var e=t.connectionManager;switch(t.state){case"suspended":return void t.notifyState("detached");case"detached":return;case"failed":throw new rr("Unable to detach; channel state = failed",90001,400);default:if("connected"!==e.state.state)return void t.notifyState("detached");t.requestState("detaching");case"detaching":return new Promise((n,i)=>{t.once(function(t){switch(this.event){case"detached":n();break;case"attached":case"suspended":case"failed":i(t.reason||e.getError()||new rr("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":i(new rr("Detach request superseded by a subsequent attach request",9e4,409))}})})}})()}detachImpl(){var t=co({action:Os.DETACH,channel:this.name});this.sendMessage(t).catch(so)}subscribe(){var e=arguments,n=this;return u(function*(){for(var i=e.length,r=new Array(i),s=0;s<i;s++)r[s]=e[s];var[o,a]=t.processListenerArgs(r);if("failed"===n.state)throw rr.fromValues(n.invalidStateError());return o&&"object"==typeof o&&!Array.isArray(o)?n.client.K.subscribeFilter(n,o,a):n.subscriptions.on(o,a),!1!==n.channelOptions.attachOnSubscribe?n.attach():null})()}unsubscribe(){for(var e,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];var[s,o]=t.processListenerArgs(i);"object"==typeof s&&!o||(null==(e=this.filteredSubscriptions)?void 0:e.has(o))?this.client.K.getAndDeleteFilteredSubscriptions(this,s,o).forEach(t=>this.subscriptions.off(t)):this.subscriptions.off(s,o)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new sr("Unable to sync to channel; not attached",4e4)}var t=this.connectionManager;if(!t.activeState())throw t.getError();var e=co({action:Os.SYNC,channel:this.name});this.syncChannelSerial&&(e.channelSerial=this.syncChannelSerial),t.send(e)}sendMessage(t){var e=this;return u(function*(){return new Promise((n,i)=>{e.connectionManager.send(t,e.client.options.queueMessages,(t,e)=>{t?i(t):n(e)})})})()}sendPresence(t){var e=this;return u(function*(){var n=co({action:Os.PRESENCE,channel:e.name,presence:t});yield e.sendMessage(n)})()}sendState(t){var e=this;return u(function*(){var n=co({action:Os.OBJECT,channel:e.name,state:t});yield e.sendMessage(n)})()}processMessage(t){var e=this;return u(function*(){t.action!==Os.ATTACHED&&t.action!==Os.MESSAGE&&t.action!==Os.PRESENCE&&t.action!==Os.OBJECT&&t.action!==Os.ANNOTATION||e.setChannelSerial(t.channelSerial);var n,i=!1;switch(t.action){case Os.ATTACHED:e.properties.attachSerial=t.channelSerial,e.Y=t.getMode(),e.params=t.params||{};var r=t.decodeModesFromFlags();e.modes=r&&$r(r)||void 0;var s=t.hasFlag("RESUMED"),o=t.hasFlag("HAS_PRESENCE"),a=t.hasFlag("HAS_BACKLOG"),l=t.hasFlag("HAS_OBJECTS");if("attached"===e.state){s||(e.tt&&e.tt.onAttached(o),e.lt&&e.lt.onAttached(l));var u=new ro(e.state,e.state,s,a,t.error);e.st.emit("update",u),s&&!e.channelOptions.updateOnAttached||e.emit("update",u)}else"detaching"===e.state?e.checkPendingState():e.notifyState("attached",t.error,s,o,a,l);break;case Os.DETACHED:var h=t.error?rr.fromValues(t.error):new rr("Channel detached",90001,404);"detaching"===e.state?e.notifyState("detached",h):"attaching"===e.state?e.notifyState("suspended",h):"attached"!==e.state&&"suspended"!==e.state||e.requestState("attaching",h);break;case Os.SYNC:if(i=!0,n=e.syncChannelSerial=t.channelSerial,!t.presence)break;case Os.PRESENCE:if(!t.presence)break;Vs(t);var d=e.channelOptions;if(e.tt){var c=yield Promise.all(t.presence.map(t=>t.decode(d,e.logger)));e.tt.setPresence(c,i,n)}break;case Os.OBJECT:case Os.OBJECT_SYNC:if(!e.lt||!t.state)return;Vs(t);var v=e.client.connection.connectionManager.getActiveTransportFormat(),f=t.state.map(t=>t.decode(e.client,v));t.action===Os.OBJECT?e.lt.handleObjectMessages(f):e.lt.handleObjectSyncMessages(f,t.channelSerial);break;case Os.MESSAGE:if("attached"!==e.state)return;Vs(t);var p=t.messages,g=p[0],m=p[p.length-1];if(g.extras&&g.extras.delta&&g.extras.delta.from!==e.rt.messageId){var b='Delta message decode failure - previous message not available for message "'+t.id+'" on this channel "'+e.name+'".';er.logAction(e.logger,er.LOG_ERROR,"RealtimeChannel.processMessage()",b),e.dt(new rr(b,40018,400));break}for(var y=[],w=0;w<p.length;w++){var{decoded:x,err:_}=yield p[w].decodeWithErr(e.it,e.logger);if(y[w]=x,_)switch(_.code){case 40018:return void e.dt(_);case 40019:case 40021:return void e.notifyState("failed",_)}}e.rt.messageId=m.id,e.rt.protocolMessageChannelSerial=t.channelSerial,e.onEvent(y);break;case Os.ANNOTATION:Vs(t);var k=e.channelOptions;if(e.X){var S=yield Promise.all((t.annotations||[]).map(t=>t.decode(k,e.logger)));e.X.ct(S)}break;case Os.ERROR:var C=t.error;C&&80016==C.code?e.checkPendingState():e.notifyState("failed",rr.fromValues(C))}})()}dt(t){this.rt.decodeFailureRecoveryInProgress||(this.rt.decodeFailureRecoveryInProgress=!0,this.ht(!0,t,()=>{this.rt.decodeFailureRecoveryInProgress=!1}))}onAttached(){}notifyState(t,e,n,i,r,s){if(this.clearStateTimer(),["detached","suspended","failed"].includes(t)&&(this.properties.channelSerial=null),t!==this.state){this.tt&&this.tt.actOnChannelState(t,i,e),this.lt&&this.lt.actOnChannelState(t,s),"suspended"===t&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),e&&(this.errorReason=e);var o=new ro(this.state,t,n,r,e),a='Channel state for channel "'+this.name+'"',l=t+(e?"; reason: "+e:"");"failed"===t&&er.logAction(this.logger,er.LOG_ERROR,a,l),"attaching"!==t&&"suspended"!==t&&(this.retryCount=0),"attached"===t&&this.onAttached(),"attached"===t?this.nt=!0:"detaching"!==t&&"failed"!==t||(this.nt=!1),this.state=t,this.st.emit(t,o),this.emit(t,o)}}requestState(t,e){this.notifyState(t,e),this.checkPendingState()}checkPendingState(){if(this.connectionManager.state.sendEvents)switch(this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync()}}timeoutPendingState(){switch(this.state){case"attaching":var t=new rr("Channel attach timed out",90007,408);this.notifyState("suspended",t);break;case"detaching":var e=new rr("Channel detach timed out",90007,408);this.notifyState("attached",e);break;default:this.checkPendingState()}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){var t=this.stateTimer;t&&(clearTimeout(t),this.stateTimer=null)}startRetryTimer(){if(!this.retryTimer){this.retryCount++;var t=Hr(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{"suspended"===this.state&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,this.requestState("attaching"))},t)}}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){var t=this.state;return"initialized"===t||"detached"===t||"failed"===t?null:new rr("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+t,90001,400)}setChannelSerial(t){t&&(this.properties.channelSerial=t)}status(){var t=this;return u(function*(){return t.client.rest.channelMixin.status(t)})()}getMessage(t){var e=this;return u(function*(){return e.client.rest.channelMixin.getMessage(e,t)})()}updateMessage(t,e,n){var i=this;return u(function*(){return i.sendUpdate(t,"message.update",e,n)})()}deleteMessage(t,e,n){var i=this;return u(function*(){return i.sendUpdate(t,"message.delete",e,n)})()}appendMessage(t,e,n){var i=this;return u(function*(){return i.sendUpdate(t,"message.append",e,n)})()}sendUpdate(t,e,n,i){var r=this;return u(function*(){var s,o;if(!t.serial)throw new rr('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);r.throwIfUnpublishableState();var a=io.fromValues(Ki(Vi({},t),{action:e,version:n})),l=yield a.encode(r.channelOptions),u=co({action:Os.MESSAGE,channel:r.name,messages:[l],params:i?Er(i):void 0}),h=yield r.sendMessage(u);return{versionSerial:null!=(o=null==(s=null==h?void 0:h.serials)?void 0:s[0])?o:null}})()}getMessageVersions(t,e){var n=this;return u(function*(){return n.client.rest.channelMixin.getMessageVersions(n,t,e)})()}ensureAttached(){var t=this;return u(function*(){switch(t.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":yield t.attach();break;default:throw rr.fromValues(t.invalidStateError())}})()}},lo=Lr;function uo(t){var e=[];if(t)for(var n=0;n<t.length;n++)e.push(t[n].toString());return"[ "+e.join(", ")+" ]"}function ho(t,e,n,i,r,s){return function(t,e,n,i){var r,s,o,a,l;t.error&&(r=rr.fromValues(t.error));t.messages&&(s=no.fromValuesArray(t.messages));e&&t.presence&&(o=e.WirePresenceMessage.fromValuesArray(t.presence));n&&t.annotations&&(a=n.WireAnnotation.fromValuesArray(t.annotations));i&&t.state&&(l=i.WireObjectMessage.fromValuesArray(t.state,nr,Js));return Object.assign(new fo,Ki(Vi({},t),{presence:o,messages:s,annotations:a,state:l,error:r}))}(Nr(t,e,s),n,i,r)}function co(t){return Object.assign(new fo,t)}function vo(t,e,n,i){var r="[ProtocolMessage";void 0!==t.action&&(r+="; action="+Ps[t.action]||t.action);for(var s,o=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"],a=0;a<o.length;a++)void 0!==t[s=o[a]]&&(r+="; "+s+"="+t[s]);if(t.messages&&(r+="; messages="+uo(no.fromValuesArray(t.messages))),t.presence&&e&&(r+="; presence="+uo(e.WirePresenceMessage.fromValuesArray(t.presence))),t.annotations&&n&&(r+="; annotations="+uo(n.WireAnnotation.fromValuesArray(t.annotations))),t.state&&i&&(r+="; state="+uo(i.WireObjectMessage.fromValuesArray(t.state,nr,Js))),t.error&&(r+="; error="+rr.fromValues(t.error).toString()),t.auth&&t.auth.accessToken&&(r+="; token="+t.auth.accessToken),t.flags&&(r+="; flags="+Ds.filter(t.hasFlag).join(",")),t.params){var l="";kr(t.params,function(e){l.length>0&&(l+="; "),l+=e+"="+t.params[e]}),l.length>0&&(r+="; params=["+l+"]")}return r+="]"}var fo=class{constructor(){this.hasFlag=t=>(this.flags&Rs[t])>0}setFlag(t){return this.flags=this.flags|Rs[t]}getMode(){return(this.flags||0)&Rs.MODE_ALL}encodeModesToFlags(t){t.forEach(t=>this.setFlag(t))}decodeModesFromFlags(){var t=[];return Us.forEach(e=>{this.hasFlag(e)&&t.push(e)}),t.length>0?t:void 0}},po=class extends Ms{constructor(t){super(t),this.messages=[]}count(){return this.messages.length}push(t){this.messages.push(t)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(t){this.messages.push.apply(this.messages,t)}prepend(t){this.messages.unshift.apply(this.messages,t)}completeMessages(t,e,n){e=e||null;var i=this.messages;if(0===i.length)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");var r=[];if("all"===t)r=i.splice(0);else{var s=i[0];if(s){var o=s.message.msgSerial,a=t.serial+t.count;a>o&&(r=i.splice(0,a-o))}}for(var l=0;l<r.length;l++){var u=r[l],h=null==n?void 0:n[l];u.callback(e,h)}0==i.length&&this.emit("idle")}completeAllMessages(t){this.completeMessages("all",t)}resetSendAttempted(){for(var t of this.messages)t.sendAttempted=!1}clear(){this.messages=[],this.emit("idle")}},go=class{constructor(t,e){this.message=t,this.callback=e,this.merged=!1;var n=t.action;this.sendAttempted=!1,this.ackRequired="number"==typeof n&&[Os.MESSAGE,Os.PRESENCE,Os.ANNOTATION,Os.OBJECT].includes(n)}},mo=class extends Ms{constructor(t){super(t.logger),this.transport=t,this.messageQueue=new po(this.logger),t.on("ack",(t,e,n)=>{this.onAck(t,e,n)}),t.on("nack",(t,e,n)=>{this.onNack(t,e,n)})}onAck(t,e,n){this.messageQueue.completeMessages({serial:t,count:e},null,n)}onNack(t,e,n){er.logAction(this.logger,er.LOG_ERROR,"Protocol.onNack()","serial = "+t+"; count = "+e+"; err = "+Or(n)),n||(n=new rr("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:t,count:e},n)}onceIdle(t){var e=this.messageQueue;0!==e.count()?e.once("idle",t):t()}send(t){t.ackRequired&&this.messageQueue.push(t),this.logger.shouldLog(er.LOG_MICRO)&&er.logActionNoStrip(this.logger,er.LOG_MICRO,"Protocol.send()","sending msg; "+vo(t.message,this.transport.connectionManager.realtime.et,this.transport.connectionManager.realtime.V,this.transport.connectionManager.realtime.vt)),t.sendAttempted=!0,this.transport.send(t.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){var t=this.transport;this.onceIdle(function(){t.disconnect()})}},bo=class{constructor(t,e,n,i){this.previous=t,this.current=e,n&&(this.retryIn=n),i&&(this.reason=i)}},yo={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001};var wo,xo,_o={disconnected:()=>rr.fromValues({statusCode:400,code:yo.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>rr.fromValues({statusCode:400,code:yo.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>rr.fromValues({statusCode:400,code:yo.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>rr.fromValues({statusCode:400,code:yo.CLOSING,message:"Connection closing"}),closed:()=>rr.fromValues({statusCode:400,code:yo.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>rr.fromValues({statusCode:500,code:yo.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>rr.fromValues({statusCode:500,code:yo.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})},ko=co({action:Os.CLOSE}),So=co({action:Os.DISCONNECT}),Co=class extends Ms{constructor(t,e,n,i){super(t.logger),i&&(n.format=void 0,n.heartbeats=!0),this.connectionManager=t,this.auth=e,this.params=n,this.timeouts=n.options.timeouts,this.format=n.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish("closed",_o.closed())}disconnect(t){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",t||_o.disconnected())}fail(t){this.isConnected&&this.requestDisconnect(),this.finish("failed",t||_o.failed())}finish(t,e){var n;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout(null!=(n=this.idleTimer)?n:void 0),this.idleTimer=null,this.emit(t,e),this.dispose())}onProtocolMessage(t){switch(this.logger.shouldLog(er.LOG_MICRO)&&er.logActionNoStrip(this.logger,er.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+vo(t,this.connectionManager.realtime.et,this.connectionManager.realtime.V,this.connectionManager.realtime.vt)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),t.action){case Os.HEARTBEAT:er.logActionNoStrip(this.logger,er.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",t.id);break;case Os.CONNECTED:this.onConnect(t),this.emit("connected",t.error,t.connectionId,t.connectionDetails,t);break;case Os.CLOSED:this.onClose(t);break;case Os.DISCONNECTED:this.onDisconnect(t);break;case Os.ACK:this.emit("ack",t.msgSerial,t.count,t.res);break;case Os.NACK:this.emit("nack",t.msgSerial,t.count,t.error);break;case Os.SYNC:this.connectionManager.onChannelMessage(t,this);break;case Os.ACTIVATE:break;case Os.AUTH:Br(this.auth.authorize(),t=>{t&&er.logAction(this.logger,er.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+Or(t))});break;case Os.ERROR:if(void 0===t.channel){this.onFatalError(t);break}this.connectionManager.onChannelMessage(t,this);break;default:this.connectionManager.onChannelMessage(t,this)}}onConnect(t){if(this.isConnected=!0,!t.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");var e=t.connectionDetails.maxIdleInterval;e&&(this.maxIdleInterval=e+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(t){var e=t&&t.error;this.finish("disconnected",e)}onFatalError(t){var e=t&&t.error;this.finish("failed",e)}onClose(t){var e=t&&t.error;this.finish("closed",e)}requestClose(){this.send(ko)}requestDisconnect(){this.send(So)}ping(t){var e={action:Os.HEARTBEAT};t&&(e.id=t),this.send(co(e))}dispose(){this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=Date.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(t){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},t))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;var t=Date.now()-this.lastActivity,e=this.maxIdleInterval-t;if(e<=0){var n="No activity seen from realtime in "+t+"ms; assuming connection has dropped";er.logAction(this.logger,er.LOG_ERROR,"Transport.onIdleTimerExpire()",n),this.disconnect(new rr(n,80003,408))}else this.setIdleTimer(e+100)}static tryConnect(t,e,n,i,r){var s,o=new t(e,n,i),a=function(t){clearTimeout(s),r({event:this.event,error:t})},l=e.options.timeouts.realtimeRequestTimeout;return s=setTimeout(()=>{o.off(["preconnect","disconnected","failed"]),o.dispose(),a.call({event:"disconnected"},new rr("Timeout waiting for transport to indicate itself viable",5e4,500))},l),o.on(["failed","disconnected"],a),o.on("preconnect",function(){clearTimeout(s),o.off(["failed","disconnected"],a),r(null,o)}),o.connect(),o}static isAvailable(){throw new rr("isAvailable not implemented for transport",5e4,500)}};(xo=wo||(wo={})).WebSocket="web_socket",xo.Comet="comet",xo.XhrPolling="xhr_polling";var To="undefined"!=typeof global?global:"undefined"!=typeof window?window:self,Ao=()=>{var t;return void 0!==Xi.WebStorage&&(null==(t=Xi.WebStorage)?void 0:t.localSupported)},Eo=()=>{var t;return void 0!==Xi.WebStorage&&(null==(t=Xi.WebStorage)?void 0:t.sessionSupported)},Io=function(){},Mo="ably-transport-preference";function Oo(t){try{return JSON.parse(t)}catch(t){return null}}var Po=class{constructor(t,e,n,i){this.options=t,this.host=e,this.mode=n,this.connectionKey=i,this.format=t.useBinaryProtocol?"msgpack":"json"}getConnectParams(t){var e=t?ar(t):{},n=this.options;switch(this.mode){case"resume":e.resume=this.connectionKey;break;case"recover":var i=Oo(n.recover);i&&(e.recover=i.connectionKey)}return void 0!==n.clientId&&(e.clientId=n.clientId),!1===n.echoMessages&&(e.echo="false"),void 0!==this.format&&(e.format=this.format),void 0!==this.stream&&(e.stream=this.stream),void 0!==this.heartbeats&&(e.heartbeats=this.heartbeats),e.v=fs.protocolVersion,e.agent=us(this.options),void 0!==n.transportParams&&or(e,n.transportParams),e}toString(){var t="[mode="+this.mode;return this.host&&(t+=",host="+this.host),this.connectionKey&&(t+=",connectionKey="+this.connectionKey),this.format&&(t+=",format="+this.format),t+="]"}},Ro=class t extends Ms{constructor(t,e){super(t.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=t,this.initTransports(),this.options=e;var n=e.timeouts,i=n.webSocketConnectTimeout+n.realtimeRequestTimeout;if(this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:i,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:n.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:n.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:n.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new po(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=n.connectionStateTtl,this.maxIdleInterval=null,this.transports=gr(e.transports||fs.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(wo.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(wo.XhrPolling)?this.baseTransport=wo.XhrPolling:this.transports.includes(wo.Comet)&&(this.baseTransport=wo.Comet),this.domains=fs.getHosts(e),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.lastActivity=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,!this.transports.length){var r="no requested transports available";throw er.logAction(this.logger,er.LOG_ERROR,"realtime.ConnectionManager()",r),new Error(r)}var s=Xi.Config.addEventListener;s&&(Eo()&&"function"==typeof e.recover&&s("beforeunload",this.persistConnection.bind(this)),!0===e.closeOnUnload&&s("beforeunload",()=>{this.requestState({state:"closing"})}),s("online",()=>{var t;this.state==this.states.disconnected||this.state==this.states.suspended?this.requestState({state:"connecting"}):this.state==this.states.connecting&&(null==(t=this.pendingTransport)||t.off(),this.disconnectAllTransports(),this.startConnect())}),s("offline",()=>{this.state==this.states.connected&&this.disconnectAllTransports()}))}static supportedTransports(t){var e={supportedTransports:{}};return this.initTransports(t,e),e.supportedTransports}static initTransports(t,e){var n=Vi(Vi({},Xi.Transports.bundledImplementations),t);[wo.WebSocket,...Xi.Transports.order].forEach(t=>{var i=n[t];i&&i.isAvailable()&&(e.supportedTransports[t]=i)})}initTransports(){t.initTransports(this.realtime.ft,this)}createTransportParams(t,e){return new Po(this.options,t,e,this.connectionKey)}getTransportParams(t){(t=>{if(this.connectionKey)t("resume");else if("string"!=typeof this.options.recover){var e=this.options.recover,n=this.getSessionRecoverData();this.sessionRecoveryName(),n&&"function"==typeof e?e(n,e=>{e?(this.options.recover=n.recoveryKey,t("recover")):t("clean")}):t("clean")}else t("recover")})(e=>{var n=this.createTransportParams(null,e);if("recover"===e){var i=Oo(this.options.recover);i&&(this.msgSerial=i.msgSerial)}t(n)})}tryATransport(t,e,n){this.proposedTransport=Co.tryConnect(this.supportedTransports[e],this,this.realtime.auth,t,(i,r)=>{var s,o=this.state;if(o==this.states.closing||o==this.states.closed||o==this.states.failed)return r&&r.close(),void n(!0);i?!Cs.isTokenErr(i.error)||this.errorReason&&Cs.isTokenErr(this.errorReason)?"failed"===i.event?(this.notifyState({state:"failed",error:i.error}),n(!0)):"disconnected"===i.event&&(!(s=i.error).statusCode||!s.code||s.statusCode>=500||Object.values(yo).includes(s.code)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:i.error}),n(!0))):(this.errorReason=i.error,Br(this.realtime.auth.O(null,null),i=>{i?this.actOnErrorFromAuthorize(i):this.tryATransport(t,e,n)})):(this.setTransportPending(r,t),n(null,r))})}setTransportPending(t,e){var n=e.mode;this.pendingTransport=t,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),t.once("connected",(e,i,r)=>{this.activateTransport(e,t,i,r),"recover"===n&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});var i=this;t.on(["disconnected","closed","failed"],function(e){i.deactivateTransport(t,this.event,e)}),this.emit("transport.pending",t)}activateTransport(t,e,n,i){t&&er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+t),this.persistTransportPreference(e);var r=this.state,s=this.states.connected.state;if(r.state==this.states.closing.state||r.state==this.states.closed.state||r.state==this.states.failed.state)return e.disconnect(),!1;if(delete this.pendingTransport,!e.isConnected)return!1;var o=this.activeProtocol;this.activeProtocol=new mo(e),this.host=e.params.host;var a=i.connectionKey;if(a&&this.connectionKey!=a&&this.setConnection(n,i,!!t),this.onConnectionDetailsUpdate(i,e),Xi.Config.nextTick(()=>{e.on("connected",(t,n,i)=>{this.onConnectionDetailsUpdate(i,e),this.emit("update",new bo(s,s,null,t))})}),r.state===this.states.connected.state?t&&(this.errorReason=this.realtime.connection.errorReason=t,this.emit("update",new bo(s,s,null,t))):(this.notifyState({state:"connected",error:t}),this.errorReason=this.realtime.connection.errorReason=t||null),this.emit("transport.active",e),o)if(o.messageQueue.count()>0&&er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+o.transport.shortName+", new one is "+e.shortName+") finishing with "+o.messageQueue.count()+" messages still pending"),o.transport===e){var l="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+e.shortName+"; stack = "+(new Error).stack;er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.activateTransport()",l)}else o.finish();return!0}deactivateTransport(t,e,n){var i=this.activeProtocol,r=i&&i.getTransport()===t,s=t===this.pendingTransport,o=this.noTransportsScheduledForActivation();if(n&&n.message,r&&(this.queuePendingMessages(i.getPendingMessages()),i.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",t),r&&o||r&&"failed"===e||"closed"===e||null===i&&s){if("disconnected"===e&&n&&n.statusCode>500&&this.domains.length>1)return this.unpersistTransportPreference(),this.forceFallbackHost=!0,void this.notifyState({state:e,error:n,retryImmediately:!0});var a="failed"===e&&Cs.isTokenErr(n)?"disconnected":e;this.notifyState({state:a,error:n})}else;}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(t,e,n){var i=this.connectionId;(i&&i!==t||!i&&n)&&(this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId,this.realtime.connection.id=this.connectionId=t,this.realtime.connection.key=this.connectionKey=e.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){this.lastActivity&&this.connectionId&&(Date.now()-this.lastActivity>this.connectionStateTtl+this.maxIdleInterval&&(this.clearConnection(),this.states.connecting.failState="suspended"))}persistConnection(){if(Eo()){var t=this.createRecoveryKey();t&&this.setSessionRecoverData({recoveryKey:t,disconnectedAt:Date.now(),location:To.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var t;return null==(t=this.activeProtocol)?void 0:t.getTransport().format}getError(){if(this.errorReason){var t=sr.fromValues(this.errorReason);return t.cause=this.errorReason,t}return this.getStateError()}getStateError(){var t,e;return null==(e=(t=_o)[this.state.state])?void 0:e.call(t)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(t){var e=t.current+(t.reason?"; reason: "+t.reason:"");"failed"===t.current&&er.logAction(this.logger,er.LOG_ERROR,"Connection state",e);var n=this.state=this.states[t.current];t.reason&&(this.errorReason=t.reason,this.realtime.connection.errorReason=t.reason),(n.terminal||"suspended"===n.state)&&this.clearConnection(),this.emit("connectionstate",t)}startTransitionTimer(t){this.transitionTimer&&clearTimeout(this.transitionTimer),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,this.notifyState({state:t.failState}))},t.retryDelay)}cancelTransitionTimer(){this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(t){"disconnected"!==t&&"suspended"!==t&&"connecting"!==t&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(t){this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.requestState({state:"connecting"})},t)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{this.checkWsConnectivity().then(()=>{this.wsCheckResult=!0}).catch(()=>{this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&Br(this.realtime.http.checkConnectivity(),(t,e)=>{!t&&e||(this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new rr("Unable to connect (network unreachable)",80003,404)}))})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(t){this.webSocketGiveUpTimer=setTimeout(()=>{var e,n;this.wsCheckResult||this.baseTransport&&(this.abandonedWebSocket=!0,null==(e=this.proposedTransport)||e.dispose(),null==(n=this.pendingTransport)||n.dispose(),this.connectBase(t,++this.connectCounter))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(t){var e,n,i=t.state,r="disconnected"===i&&(this.state===this.states.connected||t.retryImmediately||this.state===this.states.connecting&&t.error&&Cs.isTokenErr(t.error)&&!(this.errorReason&&Cs.isTokenErr(this.errorReason)));if(i!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(t.state),"suspended"!==i&&"connected"!==i||(this.disconnectedRetryCount=0),!this.state.terminal)){var s=this.states[t.state],o=s.retryDelay;"disconnected"===s.state&&(this.disconnectedRetryCount++,o=Hr(s.retryDelay,this.disconnectedRetryCount));var a=new bo(this.state.state,s.state,o,t.error||(null==(n=(e=_o)[s.state])?void 0:n.call(e)));if(r){var l=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},u=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;u&&u<1e3?setTimeout(l,1e3-u):Xi.Config.nextTick(l)}else"disconnected"!==i&&"suspended"!==i||this.startRetryTimer(o);("disconnected"===i&&!r||"suspended"===i||s.terminal)&&Xi.Config.nextTick(()=>{this.disconnectAllTransports()}),"connected"!=i||this.activeProtocol||er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(a),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(i,a.reason),this.failQueuedMessages(a.reason))}}requestState(t){var e,n,i=t.state;if(i!=this.state.state&&(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(i),!("connecting"==i&&"connected"==this.state.state||"closing"==i&&"closed"==this.state.state))){var r=this.states[i],s=new bo(this.state.state,r.state,null,t.error||(null==(n=(e=_o)[r.state])?void 0:n.call(e)));this.enactStateChange(s),"connecting"==i&&Xi.Config.nextTick(()=>{this.startConnect()}),"closing"==i&&this.closeImpl()}}startConnect(){if(this.state===this.states.connecting){var t=this.realtime.auth,e=++this.connectCounter,n=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(t=>{if("recover"===t.mode&&t.options.recover){var n=Oo(t.options.recover);n&&this.realtime.channels.recoverChannels(n.channelSerials)}e===this.connectCounter&&this.connectImpl(t,e)})};if(this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),"basic"===t.method)n();else{var i=t=>{e===this.connectCounter&&(t?this.actOnErrorFromAuthorize(t):n())};this.errorReason&&Cs.isTokenErr(this.errorReason)?Br(t.O(null,null),i):Br(t.P(!1),i)}}}connectImpl(t,e){if(this.state.state===this.states.connecting.state){var n=this.getTransportPreference();n&&n===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(this.disconnectAllTransports(),this.connectWs(t,++this.connectCounter))}).catch(Io),n&&n===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(t,e):this.connectWs(t,e)}}connectWs(t,e){this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(t),this.tryTransportWithFallbacks("web_socket",t,!0,e,()=>!1!==this.wsCheckResult&&!this.abandonedWebSocket)}connectBase(t,e){this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,t,!1,e,()=>!0):this.notifyState({state:"disconnected",error:new rr("No transports left to try",8e4,404)})}tryTransportWithFallbacks(t,e,n,i,r){var s=t=>{this.notifyState({state:this.states.connecting.failState,error:t})},o=this.domains.slice(),a=(t,e)=>{i===this.connectCounter&&(r()?e||t||u():e&&e.dispose())},l=o.shift();if(l){e.host=l;var u=()=>{o.length?this.realtime.http.checkConnectivity?Br(this.realtime.http.checkConnectivity(),(n,l)=>{i===this.connectCounter&&r()&&(n?s(n):l?(e.host=Tr(o),this.tryATransport(e,t,a)):s(new rr("Unable to connect (network unreachable)",80003,404)))}):s(new sr("Internal error: Http.checkConnectivity not set",null,500)):s(new rr("Unable to connect (and no more fallback hosts to try)",80003,404))};if(this.forceFallbackHost&&o.length)return this.forceFallbackHost=!1,void u();this.tryATransport(e,t,a)}else s(new rr("Unable to connect (no available host)",80003,404))}closeImpl(){this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&this.pendingTransport.close(),this.activeProtocol&&this.activeProtocol.getTransport().close(),this.notifyState({state:"closed"})}onAuthUpdated(t,e){var n;switch(this.state.state){case"connected":var i=null==(n=this.activeProtocol)?void 0:n.getTransport();i&&i.onAuthUpdated&&i.onAuthUpdated(t);var r=co({action:Os.AUTH,auth:{accessToken:t.token}});this.send(r);var s=()=>{this.off(o),e(null,t)},o=t=>{"failed"===t.current&&(this.off(s),this.off(o),e(t.reason||this.getStateError()))};this.once("connectiondetails",s),this.on("connectionstate",o);break;case"connecting":this.disconnectAllTransports();default:var a=n=>{switch(n.current){case"connected":this.off(a),e(null,t);break;case"failed":case"closed":case"suspended":this.off(a),e(n.reason||this.getStateError())}};this.on("connectionstate",a),"connecting"===this.state.state?this.startConnect():this.requestState({state:"connecting"})}}disconnectAllTransports(){this.connectCounter++,this.pendingTransport&&this.pendingTransport.disconnect(),delete this.pendingTransport,this.proposedTransport&&this.proposedTransport.disconnect(),delete this.pendingTransport,this.activeProtocol&&this.activeProtocol.getTransport().disconnect()}send(t,e,n){n=n||Io;var i=this.state;if(i.sendEvents)this.sendImpl(new go(t,n));else if(e&&i.queueEvents)this.logger.shouldLog(er.LOG_MICRO),this.queue(t,n);else{var r="rejecting event, queueEvent was "+e+", state was "+i.state;n(this.errorReason||new rr(r,9e4,400))}}sendImpl(t){var e=t.message;t.ackRequired&&!t.sendAttempted&&(e.msgSerial=this.msgSerial++);try{this.activeProtocol.send(t)}catch(t){er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+t.stack)}}queue(t,e){this.queuedMessages.push(new go(t,e))}sendQueuedMessages(){for(var t;t=this.queuedMessages.shift();)this.sendImpl(t)}queuePendingMessages(t){t&&t.length&&this.queuedMessages.prepend(t)}failQueuedMessages(t){var e=this.queuedMessages.count();e>0&&(er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+e+" queued messages, err = "+Or(t)),this.queuedMessages.completeAllMessages(t))}onChannelMessage(t,e){this.pendingChannelMessagesState.queue.push({message:t,transport:e}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;var t=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(t.message).catch(t=>{er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",t)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}processChannelMessage(t){var e=this;return u(function*(){yield e.realtime.channels.processChannelMessage(t)})()}ping(){var t=this;return u(function*(){var e;if("connected"!==t.state.state)throw new rr("Unable to ping service; not connected",4e4,400);var n=null==(e=t.activeProtocol)?void 0:e.getTransport();if(!n)throw t.getStateError();var i=Date.now(),r=Dr();return Zr(new Promise(t=>{var e=s=>{s===r&&(n.off("heartbeat",e),t(Date.now()-i))};n.on("heartbeat",e),n.ping(r)}),t.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")})()}abort(t){this.activeProtocol.getTransport().fail(t)}getTransportPreference(){var t,e;return this.transportPreference||Ao()&&(null==(e=null==(t=Xi.WebStorage)?void 0:t.get)?void 0:e.call(t,Mo))}persistTransportPreference(t){var e,n;this.transportPreference=t.shortName,Ao()&&(null==(n=null==(e=Xi.WebStorage)?void 0:e.set)||n.call(e,Mo,t.shortName))}unpersistTransportPreference(){var t,e;this.transportPreference=null,Ao()&&(null==(e=null==(t=Xi.WebStorage)?void 0:t.remove)||e.call(t,Mo))}actOnErrorFromAuthorize(t){if(40171===t.code)this.notifyState({state:"failed",error:t});else if(40102===t.code)this.notifyState({state:"failed",error:t});else if(t.statusCode===ys.Forbidden){var e="Client configured authentication provider returned 403; failing the connection";er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",e),this.notifyState({state:"failed",error:new rr(e,80019,403,t)})}else{this.notifyState({state:this.state.failState,error:new rr("Client configured authentication provider request failed",80019,401,t)})}}onConnectionDetailsUpdate(t,e){if(t){this.connectionDetails=t,t.maxMessageSize&&(this.options.maxMessageSize=t.maxMessageSize);var n=t.clientId;if(n){var i=this.realtime.auth.B(n);if(i)return er.logAction(this.logger,er.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",i.message),void e.fail(i)}var r=t.connectionStateTtl;r&&(this.connectionStateTtl=r),this.maxIdleInterval=t.maxIdleInterval,this.emit("connectiondetails",t)}}checkWsConnectivity(){var t=this.options.wsConnectivityCheckUrl||fs.wsConnectivityCheckUrl,e=new Xi.Config.WebSocket(t);return new Promise((t,n)=>{var i=!1;e.onopen=()=>{i||(i=!0,t(),e.close())},e.onclose=e.onerror=()=>{i||(i=!0,n())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var t,e;return Eo()&&(null==(e=null==(t=Xi.WebStorage)?void 0:t.getSession)?void 0:e.call(t,this.sessionRecoveryName()))}setSessionRecoverData(t){var e,n;return Eo()&&(null==(n=null==(e=Xi.WebStorage)?void 0:e.setSession)?void 0:n.call(e,this.sessionRecoveryName(),t))}clearSessionRecoverData(){var t,e;return Eo()&&(null==(e=null==(t=Xi.WebStorage)?void 0:t.removeSession)?void 0:e.call(t,this.sessionRecoveryName()))}},Do=class extends Ms{constructor(t,e){super(t.logger),this.whenState=t=>Ms.prototype.whenState.call(this,t,this.state),this.ably=t,this.connectionManager=new Ro(t,e),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",t=>{var e=this.state=t.current;Xi.Config.nextTick(()=>{this.emit(e,t)})}),this.connectionManager.on("update",t=>{Xi.Config.nextTick(()=>{this.emit("update",t)})})}connect(){this.connectionManager.requestState({state:"connecting"})}ping(){var t=this;return u(function*(){return t.connectionManager.ping()})()}close(){this.connectionManager.requestState({state:"closing"})}get recoveryKey(){return this.logger.deprecationWarning("The `Connection.recoveryKey` attribute has been replaced by the `Connection.createRecoveryKey()` method. Replace your usage of `recoveryKey` with the return value of `createRecoveryKey()`. `recoveryKey` will be removed in a future version."),this.createRecoveryKey()}createRecoveryKey(){return this.connectionManager.createRecoveryKey()}},Uo=class t extends Qs{constructor(e){var n,i,r,s;if(super(fs.objectifyOptions(e,!1,"BaseRealtime",er.defaultLogger)),"string"==typeof EdgeRuntime)throw new rr('Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === \'string\')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.',4e4,400);this.ft=t.transportImplementationsFromPlugins(this.options.plugins),this.et=null!=(i=null==(n=this.options.plugins)?void 0:n.RealtimePresence)?i:null,this.vt=null!=(s=null==(r=this.options.plugins)?void 0:r.LiveObjects)?s:null,this.connection=new Do(this,this.options),this.gt=new Bo(this),!1!==this.options.autoConnect&&this.connect()}static transportImplementationsFromPlugins(t){var e={};return(null==t?void 0:t.WebSocketTransport)&&(e[wo.WebSocket]=t.WebSocketTransport),(null==t?void 0:t.XHRPolling)&&(e[wo.XhrPolling]=t.XHRPolling),e}get channels(){return this.gt}get clientId(){return this.auth.clientId}connect(){this.connection.connect()}close(){this.connection.close()}};Uo.EventEmitter=Ms;var jo=Uo,Bo=class extends Ms{constructor(t){super(t.logger),this.realtime=t,this.all=Object.create(null),t.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){var t={};for(var e of xr(this.all,!0)){var n=this.all[e];n.properties.channelSerial&&(t[e]=n.properties.channelSerial)}return t}recoverChannels(t){for(var e of xr(t,!0)){this.get(e).properties.channelSerial=t[e]}}processChannelMessage(t){var e=this;return u(function*(){var n=t.channel;if(void 0!==n){var i=e.all[n];i?yield i.processMessage(t):er.logAction(e.logger,er.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+n)}else er.logAction(e.logger,er.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+t.action)})()}onTransportActive(){for(var t in this.all){var e=this.all[t];"attaching"===e.state||"detaching"===e.state?e.checkPendingState():"suspended"===e.state?e.ht(!1,null):"attached"===e.state&&e.requestState("attaching")}}propogateConnectionInterruption(t,e){var n=["attaching","attached","detaching","suspended"],i={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"}[t];for(var r in this.all){var s=this.all[r];n.includes(s.state)&&s.notifyState(i,e)}}get(t,e){t=String(t);var n=this.all[t];if(n){if(e){if(n.ut(e,n.channelOptions))throw new rr("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);n.setOptions(e)}}else n=this.all[t]=new ao(this.realtime,t,e);return n}getDerived(t,e,n){if(e.filter){var i=Kr(e.filter),r=Vr(t);t="[filter="+i+r.qualifierParam+"]"+r.channelName}return this.get(t,n)}release(t){t=String(t);var e=this.all[t];if(e){var n=e.getReleaseErr();if(n)throw n;delete this.all[t]}}},No=jo,Lo=Uint8Array,$o=Uint32Array,zo=Math.pow,qo=new $o(8),Fo=[],Ho=new $o(64);function Wo(t){return(t-(0|t))*zo(2,32)|0}for(var Jo,Vo,Ko=2,Go=0;Go<64;){for(Jo=!0,Vo=2;Vo<=Ko/2;Vo++)Ko%Vo===0&&(Jo=!1);Jo&&(Go<8&&(qo[Go]=Wo(zo(Ko,.5))),Fo[Go]=Wo(zo(Ko,1/3)),Go++),Ko++}var Xo=!!new Lo(new $o([1]).buffer)[0];function Qo(t){return Xo?t>>>24|(t>>>16&255)<<8|(65280&t)<<8|t<<24:t}function Zo(t,e){return t>>>e|t<<32-e}function Yo(t){var e,n=qo.slice(),i=t.length,r=8*i,s=512-(r+64)%512-1+r+65,o=new Lo(s/8),a=new $o(o.buffer);o.set(t,0),o[i]=128,a[a.length-1]=Qo(r);for(var l=0;l<s/32;l+=16){var u=n.slice();for(e=0;e<64;e++){var h;if(e<16)h=Qo(a[l+e]);else{var d=Ho[e-15],c=Ho[e-2];h=Ho[e-7]+Ho[e-16]+(Zo(d,7)^Zo(d,18)^d>>>3)+(Zo(c,17)^Zo(c,19)^c>>>10)}Ho[e]=h|=0;for(var v=(Zo(u[4],6)^Zo(u[4],11)^Zo(u[4],25))+(u[4]&u[5]^~u[4]&u[6])+u[7]+h+Fo[e],f=(Zo(u[0],2)^Zo(u[0],13)^Zo(u[0],22))+(u[0]&u[1]^u[2]&(u[0]^u[1])),p=7;p>0;p--)u[p]=u[p-1];u[0]=v+f|0,u[4]=u[4]+v|0}for(e=0;e<8;e++)n[e]=n[e]+u[e]|0}return new Lo(new $o(n.map(function(t){return Qo(t)})).buffer)}var ta,ea=new class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(t){for(var e,n,i,r,s="",o=this.base64CharSet,a=t.byteLength,l=a%3,u=a-l,h=0;h<u;h+=3)e=(258048&(r=t[h]<<16|t[h+1]<<8|t[h+2]))>>12,n=(4032&r)>>6,i=63&r,s+=o[(16515072&r)>>18]+o[e]+o[n]+o[i];return 1==l?(e=(3&(r=t[u]))<<4,s+=o[(252&r)>>2]+o[e]+"=="):2==l&&(e=(1008&(r=t[u]<<8|t[u+1]))>>4,n=(15&r)<<2,s+=o[(64512&r)>>10]+o[e]+o[n]+"="),s}base64ToArrayBuffer(t){for(var e=null==atob?void 0:atob(t),n=e.length,i=new Uint8Array(n),r=0;r<n;r++){var s=e.charCodeAt(r);i[r]=s}return this.toArrayBuffer(i)}isBuffer(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}toBuffer(t){if(!ArrayBuffer)throw new Error("Can't convert to Buffer: browser does not support the necessary types");if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(this.toArrayBuffer(t));throw new Error("BufferUtils.toBuffer expected an ArrayBuffer or a view onto one")}toArrayBuffer(t){if(!ArrayBuffer)throw new Error("Can't convert to ArrayBuffer: browser does not support the necessary types");if(t instanceof ArrayBuffer)return t;if(ArrayBuffer.isView(t))return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);throw new Error("BufferUtils.toArrayBuffer expected an ArrayBuffer or a view onto one")}base64Encode(t){return this.uint8ViewToBase64(this.toBuffer(t))}base64UrlEncode(t){return this.base64Encode(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}base64Decode(t){if(ArrayBuffer&&Xi.Config.atob)return this.base64ToArrayBuffer(t);throw new Error("Expected ArrayBuffer to exist and Platform.Config.atob to be configured")}hexEncode(t){return this.toBuffer(t).reduce((t,e)=>t+e.toString(16).padStart(2,"0"),"")}hexDecode(t){if(t.length%2!=0)throw new Error("Can't create a byte array from a hex string of odd length");for(var e=new Uint8Array(t.length/2),n=0;n<e.length;n++)e[n]=parseInt(t.slice(2*n,2*(n+1)),16);return this.toArrayBuffer(e)}utf8Encode(t){if(Xi.Config.TextEncoder){var e=(new Xi.Config.TextEncoder).encode(t);return this.toArrayBuffer(e)}throw new Error("Expected TextEncoder to be configured")}utf8Decode(t){if(!this.isBuffer(t))throw new Error("Expected input of utf8decode to be an arraybuffer or typed array");if(TextDecoder)return(new TextDecoder).decode(t);throw new Error("Expected TextDecoder to be configured")}areBuffersEqual(t,e){if(!t||!e)return!1;var n=this.toArrayBuffer(t),i=this.toArrayBuffer(e);if(n.byteLength!=i.byteLength)return!1;for(var r=new Uint8Array(n),s=new Uint8Array(i),o=0;o<r.length;o++)if(r[o]!=s[o])return!1;return!0}byteLength(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:-1}arrayBufferViewToBuffer(t){return this.toArrayBuffer(t)}concat(t){var e=t.reduce((t,e)=>t+e.byteLength,0),n=new Uint8Array(e),i=0;for(var r of t){var s=this.toBuffer(r);n.set(s,i),i+=s.byteLength}return n.buffer}sha256(t){var e=Yo(this.toBuffer(t));return this.toArrayBuffer(e)}hmacSha256(t,e){var n=function(t,e){if(t.length>64&&(t=Yo(t)),t.length<64){var n=new Uint8Array(64);n.set(t,0),t=n}for(var i=new Uint8Array(64),r=new Uint8Array(64),s=0;s<64;s++)i[s]=54^t[s],r[s]=92^t[s];var o=new Uint8Array(e.length+64);o.set(i,0),o.set(e,64);var a=new Uint8Array(96);return a.set(r,0),a.set(Yo(o),64),Yo(a)}(this.toBuffer(e),this.toBuffer(t));return this.toArrayBuffer(n)}},na=(t=>(t[t.REQ_SEND=0]="REQ_SEND",t[t.REQ_RECV=1]="REQ_RECV",t[t.REQ_RECV_POLL=2]="REQ_RECV_POLL",t[t.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",t))(na||{}),ia=na;function ra(){return new rr("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var sa=(ta=class{constructor(t){var e;this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1,this.client=null!=t?t:null;var n=(null==t?void 0:t.options.connectivityCheckUrl)||fs.connectivityCheckUrl,i=null!=(e=null==t?void 0:t.options.connectivityCheckParams)?e:null,r=!(null==t?void 0:t.options.connectivityCheckUrl),s=Vi(Vi({},sa.bundledRequestImplementations),null==t?void 0:t.q),o=s.XHRRequest,a=s.FetchRequest,l=!(!o&&!a);if(!l)throw ra();Xi.Config.xhrSupported&&o?(this.supportsAuthHeaders=!0,this.Request=function(){var e=u(function*(e,n,i,r,s){return new Promise(a=>{var l,u=o.createRequest(n,i,r,s,ia.REQ_SEND,null!=(l=t&&t.options.timeouts)?l:null,this.logger,e);u.once("complete",(t,e,n,i,r)=>a({error:t,body:e,headers:n,unpacked:i,statusCode:r})),u.exec()})});return function(t,n,i,r,s){return e.apply(this,arguments)}}(),(null==t?void 0:t.options.disableConnectivityCheck)?this.checkConnectivity=u(function*(){return!0}):this.checkConnectivity=u(function*(){var t,e,s=yield this.doUri(ms.Get,n,null,null,i);return r?!s.error&&"yes"==(null==(t=s.body)?void 0:t.replace(/\n/,"")):!s.error&&((e=s.statusCode)>=200&&e<400)})):Xi.Config.fetchSupported&&a?(this.supportsAuthHeaders=!0,this.Request=function(){var e=u(function*(e,n,i,r,s){return a(e,null!=t?t:null,n,i,r,s)});return function(t,n,i,r,s){return e.apply(this,arguments)}}(),(null==t?void 0:t.options.disableConnectivityCheck)?this.checkConnectivity=u(function*(){return!0}):this.checkConnectivity=u(function*(){var t,e=yield this.doUri(ms.Get,n,null,null,null);return!e.error&&"yes"==(null==(t=e.body)?void 0:t.replace(/\n/,""))})):this.Request=u(function*(){return{error:l?new sr("no supported HTTP transports available",null,400):ra()}})}get logger(){var t,e;return null!=(e=null==(t=this.client)?void 0:t.logger)?e:er.defaultLogger}doUri(t,e,n,i,r){var s=this;return u(function*(){return s.Request?s.Request(t,e,n,r,i):{error:new sr("Request invoked before assigned to",null,500)}})()}shouldFallback(t){var e=t.statusCode;return 408===e&&!t.code||400===e&&!t.code||e>=500&&e<=504}},ta.methods=[ms.Get,ms.Delete,ms.Post,ms.Put,ms.Patch],ta.methodsWithoutBody=[ms.Get,ms.Delete],ta.methodsWithBody=[ms.Post,ms.Put,ms.Patch],ta),oa=sa,aa="ablyjs-storage-test",la="undefined"!=typeof global?global:"undefined"!=typeof window?window:self,ua=new class{constructor(){try{la.sessionStorage.setItem(aa,aa),la.sessionStorage.removeItem(aa),this.sessionSupported=!0}catch(t){this.sessionSupported=!1}try{la.localStorage.setItem(aa,aa),la.localStorage.removeItem(aa),this.localSupported=!0}catch(t){this.localSupported=!1}}get(t){return this.bt(t,!1)}getSession(t){return this.bt(t,!0)}remove(t){return this.yt(t,!1)}removeSession(t){return this.yt(t,!0)}set(t,e,n){return this.wt(t,e,n,!1)}setSession(t,e,n){return this.wt(t,e,n,!0)}wt(t,e,n,i){var r={value:e};return n&&(r.expires=Date.now()+n),this.storageInterface(i).setItem(t,JSON.stringify(r))}bt(t,e){if(e&&!this.sessionSupported)throw new Error("Session Storage not supported");if(!e&&!this.localSupported)throw new Error("Local Storage not supported");var n=this.storageInterface(e).getItem(t);if(!n)return null;var i=JSON.parse(n);return i.expires&&i.expires<Date.now()?(this.storageInterface(e).removeItem(t),null):i.value}yt(t,e){return this.storageInterface(e).removeItem(t)}storageInterface(t){return t?la.sessionStorage:la.localStorage}},ha=Wr(),da="string"==typeof EdgeRuntime;"undefined"!=typeof Window||"undefined"!=typeof WorkerGlobalScope||da||console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var ca,va,fa={agent:"browser",logTimestamps:!0,userAgent:ha.navigator&&ha.navigator.userAgent.toString(),currentUrl:ha.location&&ha.location.href,binaryType:"arraybuffer",WebSocket:ha.WebSocket,fetchSupported:!!ha.fetch,xhrSupported:ha.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:(va=ha.location,!ha.WebSocket||!va||!va.origin||va.origin.indexOf("http")>-1),useProtocolHeartbeats:!0,supportsBinary:!!ha.TextDecoder,preferBinary:!1,ArrayBuffer:ha.ArrayBuffer,atob:ha.atob,nextTick:"function"==typeof ha.queueMicrotask?t=>ha.queueMicrotask(t):t=>Promise.resolve().then(t),addEventListener:ha.addEventListener,inspect:JSON.stringify,stringByteSize:function(t){return ha.TextDecoder&&(new ha.TextEncoder).encode(t).length||t.length},TextEncoder:ha.TextEncoder,TextDecoder:ha.TextDecoder,getRandomArrayBuffer:(ca=u(function*(t){var e=new Uint8Array(t);return ha.crypto.getRandomValues(e),e.buffer}),function(t){return ca.apply(this,arguments)}),isWebworker:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,push:{platform:"browser",formFactor:"desktop",storage:ua}},pa=fa;wo.XhrPolling;var ga=wo.WebSocket;var ma=class extends Co{constructor(t,e,n){super(t,e,n),this.shortName=ga,n.heartbeats=Xi.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!Xi.Config.WebSocket}createWebSocket(t,e){return this.uri=t+Ar(e),new Xi.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){Co.prototype.connect.call(this);var t=this,e=this.params,n=e.options,i=(n.tls?"wss://":"ws://")+this.wsHost+":"+fs.getPort(n)+"/";Br(this.auth.getAuthParams(),function(n,r){if(!t.isDisposed){for(var s in r)" "+s+": "+r[s]+";";if(n)t.disconnect(n);else{var o=e.getConnectParams(r);try{var a=t.wsConnection=t.createWebSocket(i,o);a.binaryType=Xi.Config.binaryType,a.onopen=function(){t.onWsOpen()},a.onclose=function(e){t.onWsClose(e)},a.onmessage=function(e){t.onWsData(e.data)},a.onerror=function(e){t.onWsError(e)},a.on&&a.on("ping",function(){t.onActivity()})}catch(e){er.logAction(t.logger,er.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(e.stack||e.message)),t.disconnect(e)}}}})}send(t){var e=this.wsConnection;if(e)try{e.send(lo(t,this.connectionManager.realtime.F,this.params.format))}catch(t){var n="Exception from ws connection when trying to send: "+Or(t);er.logAction(this.logger,er.LOG_ERROR,"WebSocketTransport.send()",n),this.finish("disconnected",new rr(n,5e4,500))}else er.logAction(this.logger,er.LOG_ERROR,"WebSocketTransport.send()","No socket connection")}onWsData(t){try{this.onProtocolMessage(ho(t,this.connectionManager.realtime.F,this.connectionManager.realtime.et,this.connectionManager.realtime.V,this.connectionManager.realtime.vt,this.format))}catch(t){er.logAction(this.logger,er.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+t.stack)}}onWsOpen(){this.emit("preconnect")}onWsClose(t){var e,n;if("object"==typeof t?(n=t.code,e=t.wasClean||1e3===n):e=1e3==(n=t),delete this.wsConnection,e){var i=new rr("Websocket closed",80003,400);this.finish("disconnected",i)}else{var r=new rr("Unclean disconnection of WebSocket ; code = "+n,80003,400);this.finish("disconnected",r)}this.emit("disposed")}onWsError(t){Xi.Config.nextTick(()=>{this.disconnect(Error(t.message))})}dispose(){this.isDisposed=!0;var t=this.wsConnection;t&&(t.onmessage=function(){},delete this.wsConnection,Xi.Config.nextTick(()=>{if(!t)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");t.close()}))}},ba={order:["xhr_polling"],bundledImplementations:{}},ya={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[wo.XhrPolling,wo.WebSocket]};function wa(t,e,n,i,r,s){return xa.apply(this,arguments)}function xa(){return(xa=u(function*(t,e,n,i,r,s){var o,a=new Headers(i||{}),l=t?t.toUpperCase():dr(s)?"GET":"POST",h=new AbortController,d=new Promise(t=>{o=setTimeout(()=>{h.abort(),t({error:new sr("Request timed out",null,408)})},e?e.options.timeouts.httpRequestTimeout:fs.TIMEOUTS.httpRequestTimeout)}),c={method:l,headers:a,body:s,signal:h.signal};Xi.Config.isWebworker||(c.credentials=a.has("authorization")?"include":"same-origin");var v=u(function*(){try{var t=new URLSearchParams(r||{});t.set("rnd",Dr());var e=n+"?"+t,i=yield Wr().fetch(e,c);if(clearTimeout(o),204==i.status)return{error:null,statusCode:i.status};var s,a=i.headers.get("Content-Type");s=a&&a.indexOf("application/x-msgpack")>-1?yield i.arrayBuffer():a&&a.indexOf("application/json")>-1?yield i.json():yield i.text();var l=!!a&&-1===a.indexOf("application/x-msgpack"),u=function(t){var e={};return t.forEach((t,n)=>{e[n]=t}),e}(i.headers);if(i.ok)return{error:null,body:s,headers:u,unpacked:l,statusCode:i.status};var h=function(t,e){if(function(t,e){return!!e.get("x-ably-errorcode")}(0,e))return t.error&&rr.fromValues(t.error)}(s,i.headers)||new sr("Error response received from server: "+i.status+" body was: "+Xi.Config.inspect(s),null,i.status);return{error:h,body:s,headers:u,unpacked:l,statusCode:i.status}}catch(h){return clearTimeout(o),{error:h}}})();return Promise.race([d,v])})).apply(this,arguments)}var _a;function ka(t,e){var n,i,r=null!==(n=t.metadata)&&void 0!==n?n:{},s=null!==(i=e.metadata)&&void 0!==i?i:{};return!s.widgets&&r.T?h({},e,{metadata:h({},s,{T:r.T})}):e}function Sa(t,e,n,i){var r,s,o,a=(s=t.messages.value,o=e.id,s.some(t=>t.id===o));if(t.setMessages(function(t,e){var n=t.findIndex(t=>t.id===e.id);if(-1!==n){var i=t[n],r=ka(i,e);if(function(t,e){return t.id===e.id&&t.channel_id===e.channel_id&&t.sender_type===e.sender_type&&t.sender_id===e.sender_id&&t.sender_name===e.sender_name&&t.sender_avatar_url===e.sender_avatar_url&&t.content===e.content&&t.content_type===e.content_type&&t.created_at===e.created_at&&t.metadata===e.metadata}(i,r))return t;var s=[...t];return s[n]=r,s}if("ai"===e.sender_type){var o=t.findIndex(t=>t.id.startsWith("temp-ai-"));if(-1!==o){var a=ka(t[o],e),l=[...t];return l[o]=a,l}}return ci(t,e)}(t.messages.value,e)),"user"!==e.sender_type||e.sender_id!==n){if(!a){if("ai"===e.sender_type||"agent"===e.sender_type){var l=t.isOpen.value,u=(null===(r=t.channel.value)||void 0===r?void 0:r.id)===e.channel_id;if(l&&u)i.onAgentMessageWhileOpen();else{var d=t.channels.value.findIndex(t=>t.id===e.channel_id);if(-1!==d){var c=[...t.channels.value];c[d]=h({},c[d],{unread_count:(c[d].unread_count||0)+1}),t.channels.value=c}}i.onTrack(e)}t.isTyping.value=!1,t.typingSender.value=null,t.typingSenderType.value=null,i.onMessageDispatched(e)}}else i.onMessageDispatched(e)}Xi.BufferUtils=ea,Xi.Http=oa,Xi.Config=pa,Xi.Transports=ba,Xi.WebStorage=ua,oa.bundledRequestImplementations={},er.initLogHandlers(),Xi.Defaults=(_a=ya,Object.assign(ns,_a)),Xi.Config.agent&&(Xi.Defaults.agent+=" "+Xi.Config.agent);var Ca="chat.ably";function Ta(t,e,n){return Aa.apply(this,arguments)}function Aa(){return(Aa=u(function*(t,e,n){return it(t,nt,{method:"POST",body:JSON.stringify(h({distinct_id:e},n&&{channel_id:n}))})})).apply(this,arguments)}function Ea(){return(Ea=u(function*(t,e){var n=yield Ta(t,e);return(null==n?void 0:n.tokenRequest)?n.clientId&&null!=n.project_id?{tokenRequest:n.tokenRequest,clientId:n.clientId,projectId:n.project_id}:(A().warn(Ca,"token:request:incomplete — missing clientId or project_id"),null):(A().warn(Ca,"token:request:failed (initial)"),null)})).apply(this,arguments)}var Ia="chat.ably";function Ma(t,e){var n=(()=>{if(!e||"object"!=typeof e)return String(e);var t=e,n="string"==typeof t.message?t.message:String(e),i="number"==typeof t.code?t.code:null,r="number"==typeof t.statusCode?t.statusCode:null;return i||r?n+" (code="+(null!=i?i:"-")+", status="+(null!=r?r:"-")+")":n})(),i=n.toLowerCase();return i.includes("timeout for trying fallback hosts")||i.includes("connection failed")||i.includes("network")||i.includes("failed to fetch")?t+" — "+n+" (browser cannot reach Ably hosts (*.ably.io / *.ably-realtime.com) — check ad-blocker, firewall, VPN, or offline state)":t+" — "+n}var Oa=t=>new No(t);class Pa{constructor(t,e,n,i){void 0===i&&(i=Oa),this.instance=t,this.store=e,this.hooks=n,this.xt=null,this._t=null,this.kt=null,this.St=null,this.Ct=null,this.Tt=i}get clientId(){var t,e;return null!==(e=null===(t=this.xt)||void 0===t?void 0:t.auth.clientId)&&void 0!==e?e:null}get isLive(){return null!=this.xt}get currentChannelId(){return this.store.realtimeChannelId.value}ensureConnected(){var t=this;return u(function*(){if(!t.xt){t.store.connectionState.value="connecting",A().debug(Ia,"connect:start");var e=t.hooks.getDistinctId(),n=yield function(t,e){return Ea.apply(this,arguments)}(t.instance,e);if(n){t.store.ablyProjectId.value=n.projectId;var i,r=n.clientId,s=t.Tt({plugins:{WebSocketTransport:ma,FetchRequest:wa},authCallback:(i={instance:t.instance,getDistinctId:()=>t.hooks.getDistinctId(),getChannelScope:()=>{var e,n,i,r;return null!==(r=null!==(n=null!==(e=t.store.pendingRealtimeChannelId.value)&&void 0!==e?e:t.store.realtimeChannelId.value)&&void 0!==n?n:null===(i=t.store.channel.value)||void 0===i?void 0:i.id)&&void 0!==r?r:null},getLiveClientId:()=>{var e,n;return null!==(n=null===(e=t.xt)||void 0===e?void 0:e.auth.clientId)&&void 0!==n?n:null},onIdentityChange:()=>t.hooks.onIdentityChange()},function(){var t=u(function*(t,e){try{var n=i.getChannelScope(),r=yield Ta(i.instance,i.getDistinctId(),null!=n?n:void 0);if(!(null==r?void 0:r.tokenRequest))return void e("Failed to refresh token",null);var s=r.tokenRequest.clientId,o=i.getLiveClientId();if(o&&s&&s!==o)return A().warn(Ca,"token:request:clientid-mismatch — recreating connection"),e("clientId changed; recreating connection",null),void i.onIdentityChange();e(null,r.tokenRequest)}catch(t){e(String(t),null)}});return function(e,n){return t.apply(this,arguments)}}()),authMethod:"POST"});t.xt=s,s.connection.on("connected",()=>{t.store.connectionState.value="connected",t.At(),A().debug(Ia,"connect:connected")}),s.connection.on("disconnected",()=>{t.store.connectionState.value="disconnected",A().debug(Ia,"connect:disconnected")}),s.connection.on("suspended",()=>{t.store.connectionState.value="suspended",A().debug(Ia,"connect:suspended")}),s.connection.on("failed",()=>{t.store.connectionState.value="failed",A().debug(Ia,"connect:failed")});try{yield s.auth.authorize(n.tokenRequest)}catch(e){return A().error(Ia,Ma("connect:authorize-failed",e)),void(t.store.connectionState.value="failed")}var o=s.connection.state;"connected"===o?(t.store.connectionState.value="connected",t.At(),A().debug(Ia,"connect:connected (sync)")):"disconnected"!==o&&"suspended"!==o&&"failed"!==o||(t.store.connectionState.value=o,A().debug(Ia,"connect:"+o+" (sync)"));var a="chat:"+n.projectId+":notifications";t._t=s.channels.get(a),t._t.subscribe("notification",e=>{!function(t,e,n){var i,r,s,{type:o,channel_id:a,data:l}=e;if("new_channel"!==o)if("channel_updated"===o&&l){var u=t.channels.value.findIndex(t=>t.id===a);if(-1!==u){var d={};void 0!==l.last_message_at&&(d.last_message_at=l.last_message_at),void 0!==l.last_message_preview&&(d.last_message_preview=l.last_message_preview),void 0!==l.last_message_sender&&(d.last_message_sender=l.last_message_sender),void 0!==l.user_unread_count&&(t.isOpen.value&&(null===(i=t.channel.value)||void 0===i?void 0:i.id)===a||(d.unread_count=l.user_unread_count)),void 0!==l.status&&(d.status=l.status),void 0!==l.ai_mode&&(d.ai_mode=l.ai_mode),t.patchChannelSummary(a,d)}(null===(r=t.channel.value)||void 0===r?void 0:r.id)===a&&"closed"===l.status&&(t.channel.value=h({},t.channel.value,{status:"closed"}))}else"channel_closed"===o&&(t.patchChannelSummary(a,{status:"closed"}),(null===(s=t.channel.value)||void 0===s?void 0:s.id)===a&&(t.channel.value=h({},t.channel.value,{status:"closed"})));else n.onNewChannel()}(t.store,e.data,{onNewChannel:t.hooks.onNewChannelNotification})}),t.store.lastConnectedDistinctId.value=r.split(":").slice(1).join(":")||e}else t.store.connectionState.value="failed"}})()}refreshToken(t){var e=this;return u(function*(){var n=e.xt;if(!n)return!1;if("failed"===n.connection.state)return A().warn(Ia,"token:skip — connection failed"),e.hooks.onIdentityChange(),!1;var i=yield Ta(e.instance,e.hooks.getDistinctId(),t);if(!(null==i?void 0:i.tokenRequest))return A().warn(Ia,"token:request:failed",null!=t?t:"(list)"),!1;var r=i.tokenRequest.clientId,s=n.auth.clientId;if(s&&r&&r!==s)return A().warn(Ia,"token:request:clientid-mismatch — recreating connection"),e.hooks.onIdentityChange(),!1;try{return yield n.auth.authorize(i.tokenRequest),!0}catch(t){return A().warn(Ia,Ma("token:authorize-failed",t)),!1}})()}attachConversation(t){var e=this;return u(function*(){var n;if(yield e.ensureConnected(),e.xt&&null!=e.store.ablyProjectId.value){if(e.kt||e.St||e.Ct){var i=null!==(n=e.Ct)&&void 0!==n?n:e.Et();try{yield i}catch(t){}}if(e.store.pendingRealtimeChannelId.value=t,!(yield e.refreshToken(t)))return A().warn(Ia,"channel:attach:no-capability for",t),void(e.store.pendingRealtimeChannelId.value===t&&(e.store.pendingRealtimeChannelId.value=null));var r="chat:"+e.store.ablyProjectId.value+":"+t,s=r+":typing",o=e.xt.channels.get(r),a=e.xt.channels.get(s);e.kt=o,e.St=a;var l=()=>e.kt!==o||e.St!==a;A().debug(Ia,"channel:attach:start",t);try{if(yield o.attach(),l())return void A().debug(Ia,"channel:attach:superseded",t);if(o.subscribe("message",t=>{e.kt===o&&Sa(e.store,t.data,e.hooks.getDistinctId()||null,{onAgentMessageWhileOpen:e.hooks.onAgentMessageWhileOpen,onTrack:e.hooks.onMessageTrack,onMessageDispatched:e.hooks.onMessageDispatched})}),o.subscribe("read",t=>{var n,i;e.kt===o&&(n=e.store,"agent"===(i=t.data).reader_type&&(n.agentLastReadAt.value=i.read_at))}),yield a.attach(),l())return void A().debug(Ia,"channel:attach:superseded",t);if(a.subscribe("typing",t=>{e.St===a&&function(t,e,n){if("user"!==e.sender_type){t.isTyping.value=e.is_typing,t.typingSenderType.value=e.is_typing?e.sender_type:null;var i="ai"===e.sender_type?null:e.sender_name||("agent"===e.sender_type?"Agent":null);t.typingSender.value=e.is_typing?i:null,n.onTyping(e.is_typing,i||"")}}(e.store,t.data,{onTyping:e.hooks.onTypingDispatched})}),e.store.pendingRealtimeChannelId.value!==t)return void A().debug(Ia,"channel:attach:abandoned (pending cleared)",t);e.store.realtimeChannelId.value=t,e.store.realtimeAttached.value=!0,e.store.pendingRealtimeChannelId.value===t&&(e.store.pendingRealtimeChannelId.value=null),A().debug(Ia,"channel:realtime.attached",{channelId:t})}catch(n){if(l())return void A().debug(Ia,"channel:attach:superseded (after error)",t);A().error(Ia,"channel:attach:failed",n),e.store.realtimeAttached.value=!1,e.store.pendingRealtimeChannelId.value===t&&(e.store.pendingRealtimeChannelId.value=null),yield e.Et()}}})()}detachConversation(){var t=this.Et().finally(()=>{this.Ct===t&&(this.Ct=null)});return this.Ct=t,t}Et(){var t=this.xt,e=this.kt,n=this.St;return this.kt=null,this.St=null,Promise.all([this.It(t,e),this.It(t,n)]).then(()=>{})}publishTyping(t){var e=this.St;e&&e.publish("typing",t).catch(t=>{A().warn(Ia,"failed to publish typing indicator:",t)})}disconnectAll(){var t=this;return u(function*(){if(t.Ct)try{yield t.Ct}catch(t){}var e=t.xt,n=t.kt,i=t.St,r=t._t;if(t.kt=null,t.St=null,t._t=null,t.store.realtimeChannelId.value=null,t.store.realtimeAttached.value=!1,null==n||n.unsubscribe(),null==i||i.unsubscribe(),null==r||r.unsubscribe(),e){try{e.close()}catch(t){A().debug(Ia,"disconnect:close:error",t)}t.xt=null}t.store.ablyProjectId.value=null,t.store.connectionState.value="disconnected",t.store.lastConnectedDistinctId.value=null})()}At(){var t,e=null===(t=this.xt)||void 0===t?void 0:t.auth.clientId,n=this.store.lastConnectedDistinctId.value;if(e&&n){var i=e.split(":").slice(1).join(":")||e;i&&i!==n&&(A().warn(Ia,"identity:drift detected on connected — recreating"),this.hooks.onIdentityChange())}}It(t,e){return u(function*(){if(e&&t){e.unsubscribe();try{yield e.detach()}catch(t){}}})()}}var Ra=["delivery_status"];function Da(t,e,n){var i=t.messages.value,r=i.findIndex(t=>t.id===e);if(-1!==r){var s=i[r];if(s.delivery_status!==n){var o=[...i];if(void 0===n){var a=function(t,e){if(null==t)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(-1!==e.indexOf(i))continue;n[i]=t[i]}return n}(s,Ra);o[r]=a}else o[r]=h({},s,{delivery_status:n});t.setMessages(o)}}}function Ua(t,e){return ja.apply(this,arguments)}function ja(){return ja=u(function*(t,e){var n;if(!t.ok)return!1;if(t.headers.get("X-Vtilt-User-Message-Id")===e)return!0;var i=t.headers.get("content-type")||"";if(i.includes("text/plain"))return t.ok;if(i.includes("application/json"))try{var r=yield t.clone().json();return(null===(n=null==r?void 0:r.message)||void 0===n?void 0:n.id)===e}catch(t){return!1}return t.ok}),ja.apply(this,arguments)}function Ba(t,e){return"vtilt-chat-outbox:"+t+":"+e}function Na(t){return t+":last-channel"}class La{constructor(t){this.Mt=t,this.Ot=[]}list(){var t=this.Pt();return t.length>0?(this.Ot=t,t):this.Ot}get(t){return this.list().find(e=>e.messageId===t)}upsert(t){var e=this.list().filter(e=>e.messageId!==t.messageId);e.push(t),this.Rt(e)}patch(t,e){var n=this.list(),i=n.findIndex(e=>e.messageId===t);-1!==i&&(n[i]=h({},n[i],e),this.Rt(n))}remove(t){this.Rt(this.list().filter(e=>e.messageId!==t))}dueEntries(t){return void 0===t&&(t=Date.now()),this.list().filter(e=>"sending"!==e.state&&e.nextRetryAt<=t&&!(e.newChannel&&!e.channelId))}requeueStaleSending(t,e){var n;void 0===t&&(t=3e4),void 0===e&&(e=Date.now());for(var i=this.list(),r=!1,s=0;s<i.length;s++){var o=i[s];if("sending"===o.state){var a=null!==(n=o.sendingSince)&&void 0!==n?n:0;(!a||e-a>=t)&&(i[s]=h({},o,{state:"pending",sendingSince:void 0}),r=!0)}}r&&this.Rt(i)}Pt(){if("undefined"==typeof sessionStorage)return[];try{var t=sessionStorage.getItem(this.Mt);if(!t)return[];var e=JSON.parse(t);return Array.isArray(e)?e:[]}catch(t){return[]}}Rt(t){if(this.Ot=t,"undefined"!=typeof sessionStorage)try{0===t.length?sessionStorage.removeItem(this.Mt):sessionStorage.setItem(this.Mt,JSON.stringify(t))}catch(t){}}}function $a(t,e){return void 0===e&&(e=Date.now()),e+Math.min(6e4,1e3*Math.pow(2,Math.max(0,t-1)))}var za="chat";class qa{constructor(t,e){var n,i,r,s,o,a,l,u,d;void 0===e&&(e={}),this.Dt=null,this.Ut=new dt,this.jt=[],this.Bt=[],this.Nt=[],this.Lt=null,this.$t=null,this.zt=null,this.qt=!1,this.Ft=null,this.Ht=!1,this.Wt=0,this.Jt=0,this.Vt=!1,this.Kt=null,this.Gt=!1,this.Xt=null,this.Qt=null,this.Zt=!1,this.Yt=null,this.te=null,this.ee=!1,this.ne=null,this.ie=()=>{this.re()},this.se=()=>{"undefined"!=typeof document&&"visible"===document.visibilityState&&this.re()},this.oe=!1,this._instance=t,this.ae=h({enabled:!0,position:"bottom-right",aiMode:!0,preload:!1},e,{theme:h({},yn,e.theme)}),this.le=new wn,this.le.isVisible.value=!1!==(null===(n=this.ae.bubble)||void 0===n?void 0:n.visible),this.le.theme.value={primaryColor:null!==(r=null===(i=this.ae.theme)||void 0===i?void 0:i.primaryColor)&&void 0!==r?r:yn.primaryColor,fontFamily:null!==(o=null===(s=this.ae.theme)||void 0===s?void 0:s.fontFamily)&&void 0!==o?o:yn.fontFamily,borderRadius:null!==(l=null===(a=this.ae.theme)||void 0===a?void 0:a.borderRadius)&&void 0!==l?l:yn.borderRadius},this.Ut.register(Re),this.Ut.register(He),this.ue=new Pa(t,this.le,{getDistinctId:()=>this.he,onIdentityChange:()=>{this.de()},onNewChannelNotification:()=>{this.getChannels()},onAgentMessageWhileOpen:()=>{setTimeout(()=>this.ce(),100)},onMessageTrack:t=>{var e,n,i,r;this.ve(t,t.channel_id,null!==(n=null===(e=this.le.channel.value)||void 0===e?void 0:e.ai_mode)&&void 0!==n&&n),"ai"!==t.sender_type&&"agent"!==t.sender_type||null===(r=(i=this.ae).onMessageReceived)||void 0===r||r.call(i,{channelId:t.channel_id,messageId:t.id,senderType:t.sender_type})},onMessageDispatched:t=>{this.jt.forEach(e=>e(t))},onTypingDispatched:(t,e)=>{this.Bt.forEach(n=>n(t,e))}}),this.te=this.fe(),this.Kt=this.le.realtimeReady.subscribe(t=>{if(t&&this.Vt){var e=Date.now()-this.Jt;this.Vt=!1,e<3e3&&(this.Ht=!0,this.pe(!0),this.Wt=Date.now(),this.ge())}}),this.Dt=Ni({store:this.le,controller:this,position:null!==(u=this.ae.position)&&void 0!==u?u:"bottom-right",bubbleDraggable:!!(null===(d=this.ae.bubble)||void 0===d?void 0:d.draggable)}),this.me(),this.$t=this._instance._emitter.on("user:identified",()=>{this.de()}),this.zt=this._instance._emitter.on("user:reset",()=>{this.de()}),this.be=this.he,this.ye=new La(this.we()),this.ye.requeueStaleSending(),this.xe(),this.re()}get isOpen(){return this.le.isOpen.value}get isConnected(){return this.le.isConnected.value}get isLoading(){return this.le.isLoading.value}get unreadCount(){return this.le.unreadCount.value}get channel(){return this.le.channel.value}get channels(){return this.le.channels.value}get currentView(){return this.le.currentView.value}get store(){return this.le}get widgets(){return this.Ut}get theme(){return this.le.theme.value}get config(){return this.ae}open(){var t,e;this.le.isOpen.value||(this.le.isVisible.value=!0,this.le.isOpen.value=!0,this.le.polledUnreadTotal.value=null,this.Yt=Date.now(),null===(e=(t=this.ae).onWidgetOpen)||void 0===e||e.call(t),this.ue.ensureConnected(),0===this.le.channels.value.length&&this.getChannels())}close(){var t,e,n;if(this.le.isOpen.value){var i=this.Yt?Math.round((Date.now()-this.Yt)/1e3):0;this.Yt=null,this.le.isOpen.value=!1,this.stopUserTyping(),this.oe||!1!==(null===(t=this.ae.bubble)||void 0===t?void 0:t.visible)||(this.le.isVisible.value=!1);var r=this.le.messages.value.filter(t=>"user"===t.sender_type).length;null===(n=(e=this.ae).onWidgetClose)||void 0===n||n.call(e,{timeOpenSeconds:i,messagesSent:r}),this._e()}}_e(){var t=this;return u(function*(){yield t.ue.detachConversation(),yield t.ue.disconnectAll()})()}applyPolledUnreadCount(t){this.le.isOpen.value||(this.le.polledUnreadTotal.value=t)}toggle(){this.le.isOpen.value?this.close():this.open()}show(){this.oe=!0,this.le.isVisible.value=!0}hide(){this.oe=!1,this.le.isVisible.value=!1}getChannels(){var t=this;return u(function*(){t.le.isLoading.value=!0;try{var e=yield it(t._instance,Y+"?distinct_id="+encodeURIComponent(t.he),{method:"GET"});e&&(t.le.channels.value=e.channels||[])}catch(t){A().error(za,"failed to fetch channels:",t)}finally{t.le.isLoading.value=!1}})()}selectChannel(t){var e=this;return u(function*(){var n=e.le.channels.value.find(e=>e.id===t);e.le.channel.value=n?e.ke(n):null,e.le.prepareChannelSwitch();var i=e.le.getCachedMessages(t);i&&(e.le.messages.value=i),e.le.currentView.value="conversation",e.le.isLoading.value=!0,e.le.pendingRealtimeChannelId.value=t,e.ue.detachConversation();var r=!1,s=!1;try{var o=yield it(e._instance,Y+"/"+t+"?distinct_id="+encodeURIComponent(e.he),{method:"GET"});if(e.le.pendingRealtimeChannelId.value!==t)return void(s=!0);if(!o)return void A().error(za,"selectChannel: server returned no data for channel",t);e.le.channel.value=o.channel;var a=o.messages||[];e.le.messages.value=a,e.le.cacheMessages(o.channel.id,a),e.le.agentLastReadAt.value=o.channel.agent_last_read_at||null,e.le.initialUserReadAt.value=o.channel.user_last_read_at||null,e.ue.attachConversation(o.channel.id),e.le.isOpen.value&&e.ce(),r=!0}catch(t){A().error(za,"failed to select channel:",t)}finally{e.le.pendingRealtimeChannelId.value===t&&(e.le.pendingRealtimeChannelId.value=null),e.le.isLoading.value=!1,s||r||null!==e.le.channel.value||"conversation"!==e.le.currentView.value||(e.le.currentView.value="list")}})()}createChannel(e){var n=this;return u(function*(){var i,r,s,o=!0===(null==e?void 0:e.skipGreeting),a=!0===(null==e?void 0:e.preserveMessages),l=a?n.le.messages.value.slice():[];n.le.channel.value=null,a||n.le.prepareChannelSwitch(),n.le.currentView.value="conversation",n.le.isLoading.value=!0,n.ue.detachConversation();var u=!1;try{var d=yield it(n._instance,Y,{method:"POST",body:JSON.stringify(h({distinct_id:n.he,page_url:null===(i=null==t?void 0:t.location)||void 0===i?void 0:i.href,page_title:"undefined"!=typeof document?document.title:""},o&&{skip_greeting:!0}))});if(!d)return void A().error(za,"createChannel: server returned no data, channel was not created");n.le.channel.value=d.channel;var c=d.messages||[];if(l.length>0){var v=new Set(c.map(t=>t.id)),f=l.filter(t=>!v.has(t.id)).map(t=>t.channel_id?t:h({},t,{channel_id:d.channel.id}));n.le.messages.value=[...c,...f]}else n.le.messages.value=c;n.le.agentLastReadAt.value=d.channel.agent_last_read_at||null,n.le.initialUserReadAt.value=d.channel.user_last_read_at||null;var p={id:d.channel.id,status:d.channel.status,ai_mode:d.channel.ai_mode,last_message_at:d.channel.last_message_at,last_message_preview:d.channel.last_message_preview,last_message_sender:d.channel.last_message_sender,unread_count:0,user_last_read_at:d.channel.user_last_read_at,created_at:d.channel.created_at};n.le.prependChannelSummary(p),null===(s=(r=n.ae).onConversationStart)||void 0===s||s.call(r,{channelId:d.channel.id,aiMode:d.channel.ai_mode}),n.ue.attachConversation(d.channel.id),n.Se(d.channel.id),n.Ce(d.channel.id),u=!0}catch(t){A().error(za,"failed to create channel:",t)}finally{if(n.le.pendingRealtimeChannelId.value=null,n.le.isLoading.value=!1,!u&&null===n.le.channel.value)if(l.length>0){var g=new Set(n.ye.list().map(t=>t.messageId)),m=l.filter(t=>g.has(t.id));m.length>0?(n.le.messages.value=m.map(t=>t.delivery_status?t:h({},t,{delivery_status:"failed"})),n.le.currentView.value="conversation"):(n.le.messages.value=[],n.le.currentView.value="list")}else n.le.currentView.value="list"}})()}goToChannelList(){var t,e,n,i=this.le.channel.value;if(i){var r=this.le.messages.value[this.le.messages.value.length-1];this.le.patchChannelSummary(i.id,{last_message_at:null!==(t=null==r?void 0:r.created_at)&&void 0!==t?t:void 0,last_message_preview:r?(n=r.content,n.replace(/\n?<!--vtilt:widget:[\s\S]*?-->/g,"").replace(/<[^>]*>/g,"").trim().substring(0,100)):void 0,last_message_sender:null!==(e=null==r?void 0:r.sender_type)&&void 0!==e?e:void 0,unread_count:0}),this.le.cacheMessages(i.id,this.le.messages.value)}this.le.clearActiveChannel(),this.le.currentView.value="list",this.ue.detachConversation().then(()=>{this.ue.isLive&&!this.le.pendingRealtimeChannelId.value&&this.ue.refreshToken()})}Te(){this.Xt&&(this.Xt.abort(),this.Xt=null),this.Qt&&(bi(this.le,this.Qt),this.Qt=null),this.Ae(),this.Ee()}Ae(){for(var t=this.le.messages.value,e=-1,n=t.length-1;n>=0;n--)if("user"===t[n].sender_type){e=n;break}if(-1!==e){var i=t.filter((t,n)=>n<=e||"ai"!==t.sender_type);i.length!==t.length&&this.le.setMessages(i)}}Ie(){this.Zt=!0,this.le.isTyping.value=!0,this.le.typingSenderType.value="ai",this.le.typingSender.value="AI Assistant"}Ee(){this.Zt&&(this.Zt=!1,this.le.isTyping.value=!1,this.le.typingSender.value=null,this.le.typingSenderType.value=null)}sendMessage(t,e){var n=this;return u(function*(){var i,r=ut(t,e);if(r){n.le.identityChangeInFlight.value&&(yield n.Me());var{content:s,content_type:o,metadata:a}=r,l=!1!==(null==e?void 0:e.open),u="conversation"===n.le.currentView.value&&null!==n.le.channel.value,d=null!==(i=null==e?void 0:e.channel)&&void 0!==i?i:u?void 0:"new",c=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();var t=crypto.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;var e=t=>t.toString(16).padStart(2,"0");return e(t[0])+e(t[1])+e(t[2])+e(t[3])+"-"+e(t[4])+e(t[5])+"-"+e(t[6])+e(t[7])+"-"+e(t[8])+e(t[9])+"-"+e(t[10])+e(t[11])+e(t[12])+e(t[13])+e(t[14])+e(t[15])}(),v=(new Date).toISOString(),f="new"===d;if(n.Oe(h({messageId:c,channelId:"",distinctId:n.he,body:s,content_type:o,metadata:a,created_at:v,state:"pending",attempts:0,nextRetryAt:0},f?{newChannel:{skipGreeting:!0}}:{})),n.Pe(c),f){n.le.currentView.value="conversation",n.le.channel.value=null;var p={id:c,channel_id:"",sender_type:"user",sender_id:n.he||null,sender_name:null,sender_avatar_url:null,content:s,content_type:o,metadata:a,created_at:v,delivery_status:"pending"};n.le.setMessages([p]),n.le.isLoading.value=!0,l&&n.open(),yield n.createChannel({skipGreeting:!0,preserveMessages:!0})}else l&&n.open(),d&&(yield n.selectChannel(d));if(!n.le.channel.value)throw A().error(za,"cannot send message: no active channel (channel creation or selection failed)"),n.ye.patch(c,{state:"failed"}),Da(n.le,c,"failed"),new Error("No active channel");if("conversation"!==n.le.currentView.value)throw A().error(za,"cannot send message: not in conversation view"),n.ye.patch(c,{state:"failed"}),Da(n.le,c,"failed"),new Error("Not in conversation view");var g,m=n.le.channel.value.id;if(n.ye.patch(c,{channelId:m,newChannel:void 0}),f){var b=n.le.messages.value.find(t=>t.id===c);if(!b)throw A().error(za,"sendMessage: optimistic temp message was lost during createChannel"),n.ye.patch(c,{state:"failed"}),new Error("Optimistic message lost");g=b}else g={id:c,channel_id:m,sender_type:"user",sender_id:n.he||null,sender_name:null,sender_avatar_url:null,content:s,content_type:o,metadata:a,created_at:v,delivery_status:"pending"},n.le.setMessages([...n.le.messages.value,g]);try{yield n.Re({messageId:c,channelId:m,body:s,content_type:o,metadata:a,tempMessage:g})}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)throw n.De(c),t;throw n.Ee(),A().error(za,"failed to send message:",t),n.De(c),n.re(),t}}else A().warn(za,"sendMessage: message is empty")})()}retryFailedMessage(t){var e,n=this.ye.get(t);if(n&&"failed"===n.state){this.ye.patch(t,{state:"pending",nextRetryAt:0,sendingSince:void 0}),Da(this.le,t,"pending");var i=n.channelId||(null===(e=this.le.channel.value)||void 0===e?void 0:e.id)||"";if(i){var r=this.le.messages.value.find(e=>e.id===t);r?(this.Pe(t),this.Re({messageId:t,channelId:i,body:n.body,content_type:n.content_type,metadata:n.metadata,tempMessage:r}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?this.De(t):(A().error(za,"retry send failed:",e),this.De(t),this.re())})):this.re()}}}markAsRead(){this.ce()}triggerAIAfterWidgetAction(t){var e=this;return u(function*(){try{e.Te();var n=new AbortController;e.Xt=n,e.Ie();var i=e._instance.getConfig(),r=c(i,tt(t)),s=yield fetch(r,{method:"POST",signal:n.signal,headers:h({"Content-Type":"application/json"},v(i)),body:JSON.stringify({channel_id:t,distinct_id:e.he,widget_action_trigger:!0})});if(!s.ok)return void e.Ee();(s.headers.get("content-type")||"").includes("text/plain")&&(yield gi({store:e.le,response:s,channelId:t,signal:n.signal,isActive:()=>e.Xt===n,onStreamStart:t=>{e.Ee(),e.Xt===n&&(e.Qt=t)},onComplete:()=>{e.Xt===n&&(e.Xt=null,e.Qt=null)}}))}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)return}})()}onMessage(t){return this.jt.push(t),()=>{var e=this.jt.indexOf(t);e>-1&&this.jt.splice(e,1)}}onTyping(t){return this.Bt.push(t),()=>{var e=this.Bt.indexOf(t);e>-1&&this.Bt.splice(e,1)}}onConnectionChange(t){return this.Nt.push(t),()=>{var e=this.Nt.indexOf(t);e>-1&&this.Nt.splice(e,1)}}updateConfig(t){var e,n,i,r,s,o,a;this.ae=function(t,e){var n,i,r=e.bubble,s=t.bubble;if(r){var o=null===r.offset?void 0:void 0!==r.offset?h({},null===(n=t.bubble)||void 0===n?void 0:n.offset,r.offset):null===(i=t.bubble)||void 0===i?void 0:i.offset;s=h({},t.bubble,r,{offset:o})}return h({},t,e,{theme:e.theme?h({},t.theme,e.theme):t.theme,bubble:s})}(this.ae,t),this.le.theme.value={primaryColor:null!==(n=null===(e=this.ae.theme)||void 0===e?void 0:e.primaryColor)&&void 0!==n?n:yn.primaryColor,fontFamily:null!==(r=null===(i=this.ae.theme)||void 0===i?void 0:i.fontFamily)&&void 0!==r?r:yn.fontFamily,borderRadius:null!==(o=null===(s=this.ae.theme)||void 0===s?void 0:s.borderRadius)&&void 0!==o?o:yn.borderRadius},(null===(a=this.ae.bubble)||void 0===a?void 0:a.draggable)||this.me()}me(){var t,e,n,i,r=null===(t=this.Dt)||void 0===t?void 0:t.host;if(r){var s=null!==(e=this.ae.position)&&void 0!==e?e:"bottom-right";!function(t,e){t.style.setProperty("--vt-bubble-offset-bottom",e.bottom+"px"),t.style.setProperty("--vt-bubble-offset-right",e.right+"px"),t.style.setProperty("--vt-bubble-offset-left",e.left+"px")}(r,kn(null===(n=this.ae.bubble)||void 0===n?void 0:n.offset));var o=null===(i=r.shadowRoot)||void 0===i?void 0:i.querySelector(".vt-container");o instanceof HTMLElement&&o.setAttribute("data-position",s)}}registerWidget(t){this.Ut.register(t)}notifyUserTyping(){this.Jt=Date.now(),this.le.realtimeReady.value?(this.Ht?Date.now()-this.Wt>4e3&&(this.pe(!0),this.Wt=Date.now()):(this.Ht=!0,this.pe(!0),this.Wt=Date.now()),this.ge()):this.Vt=!0}stopUserTyping(){this.Vt=!1,this.Ft&&(clearTimeout(this.Ft),this.Ft=null),this.Ht&&this.le.realtimeReady.value&&this.pe(!1),this.Ht=!1}ge(){this.Ft&&clearTimeout(this.Ft),this.Ft=setTimeout(()=>{this.Ft=null,this.Ht&&this.le.realtimeReady.value&&this.pe(!1),this.Ht=!1},5e3)}destroy(){var t,e,n,i,r;this.Ue(),this.ne&&(clearTimeout(this.ne),this.ne=null),this.ue.disconnectAll(),this.Ft&&(clearTimeout(this.Ft),this.Ft=null),null===(t=this.$t)||void 0===t||t.call(this),this.$t=null,null===(e=this.zt)||void 0===e||e.call(this),this.zt=null,null===(n=this.te)||void 0===n||n.call(this),this.te=null,null===(i=this.Kt)||void 0===i||i.call(this),this.Kt=null,null===(r=this.Dt)||void 0===r||r.destroy(),this.Dt=null,this.jt=[],this.Bt=[],this.Nt=[]}getWidgetContext(t,e){var n,i,r,s=this,o=this._instance.getConfig();return{channelId:null!==(i=null===(n=this.le.channel.value)||void 0===n?void 0:n.id)&&void 0!==i?i:"",distinctId:this.he,primaryColor:this.le.theme.value.primaryColor,apiBase:o.api_host||"",token:o.token||"",messageId:t,buildEndpointUrl:t=>c(this._instance.getConfig(),t),dispatch:(r=u(function*(n,i){var r=s.Ut.get(e);if(r){var o=s.getWidgetContext(t,e);try{var a=yield r.onAction(n,i,o);(null==a?void 0:a.success)&&s.markWidgetSubmittedAndFollowUp(t,e,i)}catch(t){A().warn(za,"widget action failed:",t)}}}),function(t,e){return r.apply(this,arguments)})}}markWidgetSubmittedAndFollowUp(t,e,n){var i,r,s,o,a=this.le.messages.value.find(e=>e.id===t);if(a){var l=h({},null!==(i=a.metadata)&&void 0!==i?i:{}),u=(null!==(s=null!==(r=l.T)&&void 0!==r?r:l.widgets)&&void 0!==s?s:[]).map(t=>{if(t.type!==e)return t;var i=h({},t,{submitted:!0});return n.email&&(i.submittedEmail=String(n.email).trim()),n.name&&(i.submittedName=String(n.name).trim()),i});l.widgets=u,l.T&&(l.T=u);var d=this.le.messages.value.map(e=>e.id===t?h({},e,{metadata:l}):e);this.le.setMessages(d);var c=null===(o=this.le.channel.value)||void 0===o?void 0:o.id;"escalate_to_human"!==e&&c&&this.triggerAIAfterWidgetAction(c)}}we(){return Ba(this._instance.getConfig().token||"unknown",this.he)}je(){this.ye=new La(this.we()),this.ye.requeueStaleSending()}Pe(t){this.ye.patch(t,{state:"sending",sendingSince:Date.now()})}De(t){var e,n,i=(null!==(n=null===(e=this.ye.get(t))||void 0===e?void 0:e.attempts)&&void 0!==n?n:0)+1;this.ye.patch(t,{state:"failed",attempts:i,nextRetryAt:$a(i),sendingSince:void 0}),Da(this.le,t,"failed")}Se(t){for(var e of this.ye.list())e.newChannel&&!e.channelId&&this.ye.patch(e.messageId,{channelId:t,newChannel:void 0})}Ce(t){!function(t,e){if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem(Na(t),JSON.stringify({channelId:e,at:Date.now()}))}catch(t){}}(this.we(),t)}Be(t){var e=this.he;if(t&&t!==e){var n=this._instance.getConfig().token||"unknown",i=new La(Ba(n,t)),r=i.list();for(var s of r)this.ye.upsert(h({},s,{distinctId:e})),i.remove(s.messageId)}}xe(){"undefined"!=typeof window&&(window.addEventListener("online",this.ie),document.addEventListener("visibilitychange",this.se))}Ue(){"undefined"!=typeof window&&(window.removeEventListener("online",this.ie),document.removeEventListener("visibilitychange",this.se))}Oe(t){this.ye.upsert(t)}Ne(t,e){var n,i;this.ye.remove(t),Da(this.le,t,void 0),null===(i=(n=this.ae).onMessageDelivered)||void 0===i||i.call(n,{channelId:e,messageId:t})}re(){this.ne&&clearTimeout(this.ne),this.ne=setTimeout(()=>{this.ne=null,this.Le()},0)}Le(){var t=this;return u(function*(){if(!t.ee){t.ee=!0,t.ye.requeueStaleSending();try{var e=Date.now(),n=function*(e){var n=t.le.messages.value.some(t=>t.id===e.messageId&&"sending"===t.delivery_status);if(n)return 1;try{yield t.$e(e)}catch(n){A().warn(za,"outbox drain failed:",n);var i=e.attempts+1;t.ye.patch(e.messageId,{state:"failed",attempts:i,nextRetryAt:$a(i)}),Da(t.le,e.messageId,"failed")}};for(var i of t.ye.dueEntries(e))yield*n(i)}finally{t.ee=!1;var r=t.ye.dueEntries(Date.now());if(r.length>0){var s=Math.max(0,r[0].nextRetryAt-Date.now());t.ne=setTimeout(()=>{t.ne=null,t.Le()},s)}}}})()}$e(t){var e=this;return u(function*(){var n=t.channelId||void 0;if(!n&&t.newChannel){var i=function(t,e){if(void 0===e&&(e=Date.now()),"undefined"==typeof sessionStorage)return null;try{var n=sessionStorage.getItem(Na(t));if(!n)return null;var i=JSON.parse(n);return!(null==i?void 0:i.channelId)||"number"!=typeof i.at||e-i.at>12e4?null:i}catch(t){return null}}(e.we());i&&(n=i.channelId,e.ye.patch(t.messageId,{channelId:n,newChannel:void 0}))}if(!n&&t.newChannel){var r=yield e.ze(t.newChannel.skipGreeting);if(!(n=null!=r?r:void 0))throw new Error("Failed to create channel for outbox entry");e.ye.patch(t.messageId,{channelId:n,newChannel:void 0}),e.Ce(n)}if(!n)throw new Error("Outbox entry missing channelId");var s=e.le.messages.value.find(e=>e.id===t.messageId);if(s)return e.Pe(t.messageId),void(yield e.Re({messageId:t.messageId,channelId:n,body:t.body,content_type:t.content_type,metadata:t.metadata,tempMessage:s}));yield e.qe({messageId:t.messageId,channelId:n,body:t.body,content_type:t.content_type,metadata:t.metadata}),e.Ne(t.messageId,n)})()}ze(e){var n=this;return u(function*(){var i,r,s,o=yield it(n._instance,Y,{method:"POST",body:JSON.stringify(h({distinct_id:n.he,page_url:null===(i=null==t?void 0:t.location)||void 0===i?void 0:i.href,page_title:"undefined"!=typeof document?document.title:""},e&&{skip_greeting:!0}))}),a=null!==(s=null===(r=null==o?void 0:o.channel)||void 0===r?void 0:r.id)&&void 0!==s?s:null;return a&&(n.Se(a),n.Ce(a)),a})()}qe(t){var e=this;return u(function*(){var n,i=e._instance.getConfig(),r=c(i,tt(t.channelId)),s=yield fetch(r,{method:"POST",keepalive:!0,headers:h({"Content-Type":"application/json"},v(i)),body:JSON.stringify({id:t.messageId,channel_id:t.channelId,distinct_id:e.he,content:t.body,content_type:t.content_type,metadata:t.metadata})});if(!s.ok)throw new Error("API error: "+s.status);if(!(yield Ua(s,t.messageId)))throw new Error("User message not acknowledged");(s.headers.get("content-type")||"").includes("text/plain")&&(yield null===(n=s.body)||void 0===n?void 0:n.cancel().catch(()=>{}))})()}Re(t){var e=this;return u(function*(){var n,i,r,s,o,{messageId:a,channelId:l,body:u,content_type:d,metadata:f,tempMessage:p}=t;Da(e.le,a,"sending"),e.Te();var g=new AbortController;e.Xt=g,!1!==(null===(n=e.le.channel.value)||void 0===n?void 0:n.ai_mode)&&e.Ie();var m=e._instance.getConfig(),b=c(m,tt(l)),y=yield fetch(b,{method:"POST",keepalive:!0,signal:g.signal,headers:h({"Content-Type":"application/json"},v(m)),body:JSON.stringify({id:a,channel_id:l,distinct_id:e.he,content:u,content_type:d,metadata:f})});if(!y.ok)throw new Error("API error: "+y.status);if(!(yield Ua(y,a)))throw new Error("User message not acknowledged");if(e.Ne(a,l),(y.headers.get("content-type")||"").includes("text/plain"))yield gi({store:e.le,response:y,channelId:l,signal:g.signal,isActive:()=>e.Xt===g,onStreamStart:t=>{e.Ee(),e.Xt===g&&(e.Qt=t)},onComplete:()=>{var t,n,i,r;e.Xt===g&&(e.Xt=null,e.Qt=null),null===(n=(t=e.ae).onMessageSent)||void 0===n||n.call(t,{channelId:l,messageId:p.id}),e.ve(p,l,null===(r=null===(i=e.le.channel.value)||void 0===i?void 0:i.ai_mode)||void 0===r||r)}});else{e.Ee(),e.Xt===g&&(e.Xt=null);var w=yield y.json();if(null==w?void 0:w.message){var x=e.le.messages.value.findIndex(t=>t.id===w.message.id);if(-1===x&&(x=e.le.messages.value.findIndex(t=>t.id===a)),-1!==x){var _=[...e.le.messages.value];_[x]=w.message,e.le.setMessages(_)}null===(r=(i=e.ae).onMessageSent)||void 0===r||r.call(i,{channelId:l,messageId:w.message.id}),e.ve(w.message,l,null!==(o=null===(s=e.le.channel.value)||void 0===s?void 0:s.ai_mode)&&void 0!==o&&o)}}})()}get he(){return this._instance.getDistinctId()||""}ke(t){return{id:t.id,project_id:"",person_id:"",distinct_id:this.he,status:t.status,ai_mode:t.ai_mode,unread_count:t.unread_count,last_message_at:t.last_message_at,last_message_preview:t.last_message_preview,last_message_sender:t.last_message_sender,user_last_read_at:t.user_last_read_at,agent_last_read_at:null,created_at:t.created_at}}de(){var t=this;return u(function*(){if(!t.qt){var e=t.he;if(e&&e!==t.le.lastConnectedDistinctId.value){t.qt=!0,t.le.identityChangeInFlight.value=!0,t.le.clearActiveChannel(),t.le.currentView.value="list",t.Be(t.be),t.je(),t.be=e;try{yield t.ue.disconnectAll(),t.le.channels.value=[],t.le.clearMessagesCache(),yield t.getChannels(),t.le.isOpen.value&&(yield t.ue.ensureConnected()),t.re()}catch(t){A().error(za,"failed to recreate Ably client after identity change:",t)}finally{t.qt=!1,t.le.identityChangeInFlight.value=!1}}}})()}Me(){return new Promise(t=>{if(this.le.identityChangeInFlight.value)var e=this.le.identityChangeInFlight.subscribe(n=>{n||(e(),t())});else t()})}ve(t,e,n){var i,r=this._instance.getRemoteConfig(),s=null==r?void 0:r.chatTracking;if("user"===t.sender_type){if(!1===(null==s?void 0:s.trackUserMessages))return}else if(("ai"===t.sender_type||"agent"===t.sender_type)&&!1===(null==s?void 0:s.trackAgentMessages))return;this._instance.capture(ht,{$channel_type:"chat",$conversation_id:e,$message_id:t.id,$direction:"user"===t.sender_type?"inbound":"outbound",$sender_type:t.sender_type,$content_preview:(null!==(i=t.content)&&void 0!==i?i:"").slice(0,100),$ai_mode:n})}ce(){var t,e=this.le.channel.value;if(e&&!this.Gt){var n=this.le.messages.value,i=n[n.length-1];if(i){var r=this.le.initialUserReadAt.value,s=n.some(t=>{return!("agent"!==t.sender_type&&"ai"!==t.sender_type||(e=t.created_at,r&&new Date(e)<=new Date(r)));var e}),o=this.le.channels.value.find(t=>t.id===e.id),a=(null!==(t=null==o?void 0:o.unread_count)&&void 0!==t?t:0)>0;(s||a)&&(this.Gt=!0,it(this._instance,et(e.id),{method:"POST",body:JSON.stringify({channel_id:e.id,distinct_id:this.he,read_at:i.created_at})}).then(t=>{t&&(this.le.initialUserReadAt.value=i.created_at,this.le.patchChannelSummary(e.id,{unread_count:0})),this.Gt=!1}).catch(()=>{this.Gt=!1}))}}}pe(t){this.ue.publishTyping({sender_type:"user",sender_name:null,is_typing:t,sender_id:this.he})}fe(){return this.le.isConnected.subscribe(t=>{this.Lt!==t&&(this.Lt=t,this.Nt.forEach(e=>e(t)))})}}a.__VTiltExtensions__=a.__VTiltExtensions__||{},a.__VTiltExtensions__.initChat=function(t,e){return new qa(t,e)};var Fa="external-scripts";a.__VTiltExtensions__=a.__VTiltExtensions__||{},a.__VTiltExtensions__.loadExternalDependency=(t,e,n)=>{if(function(t){var e=a.__VTiltExtensions__;if(!e)return!1;switch(t){case"chat":return!!e.initChat;case"recorder":return!!e.initSessionRecording;case"web-vitals":return!!e.webVitalsCallbacks;default:return!1}}(e))n();else{var r=((t,e)=>{var n=t.getConfig();return n.script_host?n.script_host.replace(/\/+$/gm,"")+"/"+e+".js":n.api_host?n.api_host.replace(/\/+$/gm,"")+"/dist/"+e+".js":(A().error(Fa,"cannot load "+e+".js: api_host is required"),"")})(t,e);((t,e,n)=>{if(t.getConfig().disable_external_dependency_loading)return A().warn(Fa,e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var r=null==i?void 0:i.querySelectorAll("script");if(r)for(var s,o=function(){if(r[a].src===e){var t=r[a];return t.__vtilt_loading_callback_fired?{v:n()}:(t.addEventListener("load",e=>{t.__vtilt_loading_callback_fired=!0,n(void 0,e)}),t.onerror=t=>n(t),{v:void 0})}},a=0;a<r.length;a++)if(s=o())return s.v;var l=()=>{var t;if(!i)return n("document not found");var r=i.createElement("script");r.type="text/javascript",r.crossOrigin="anonymous",r.src=e,r.onload=t=>{r.__vtilt_loading_callback_fired=!0,n(void 0,t)},r.onerror=t=>n(t);var s=i.querySelectorAll("body > script");s.length>0?null===(t=s[0].parentNode)||void 0===t||t.insertBefore(r,s[0]):i.body.appendChild(r)};(null==i?void 0:i.body)?l():null==i||i.addEventListener("DOMContentLoaded",l)})(t,r,n)}};var Ha="1.13.1",Wa="__vt_session",Ja="__vt_window_id",Va="__vt_primary_window",Ka="__vt_user_state",Ga="__vt_device_id",Xa="__vt_anonymous_id",Qa="__vt_remote_config",Za="__vt_distinct_id",Ya="__vt_user_properties",tl="localStorage",el="localStorage+cookie",nl="sessionStorage",il="memory",rl="$initial_person_info",sl="$pageview",ol="$pageleave",al="$identify",ll="$alias",ul="$set",hl="$performance_event",dl="$autocapture",cl="$scroll_depth",vl="$snapshot",fl="$snapshot_items",pl="$$client_ingestion_warning",gl="$current_url",ml="$pathname",bl="$prev_pageview_duration",yl="$prev_pageview_pathname",wl="$prev_pageview_url",xl="$scroll_depth_pct",_l="$scroll_depth_max_pct",kl="$prev_pageview_scroll_depth_pct";function Sl(t,e){var n,i,r=e.bubble,s=null==t?void 0:t.bubble;if(r){var o=null===r.offset?void 0:void 0!==r.offset?h({},null===(n=null==t?void 0:t.bubble)||void 0===n?void 0:n.offset,r.offset):null===(i=null==t?void 0:t.bubble)||void 0===i?void 0:i.offset;s=h({},null==t?void 0:t.bubble,r,{offset:o})}return h({},t,e,{bubble:s})}class Cl{constructor(t){void 0===t&&(t={}),this.config=this.parseConfigFromScript(t)}parseConfigFromScript(t){if(!(null==i?void 0:i.currentScript))return h({token:t.token||""},t);var e=i.currentScript,n=h({token:""},t);n.api_host=e.getAttribute("data-api-host")||e.getAttribute("data-host")||t.api_host,n.script_host=e.getAttribute("data-script-host")||t.script_host,n.token=e.getAttribute("data-token")||t.token||"",n.domain=e.getAttribute("data-domain")||t.domain,n.storage=e.getAttribute("data-storage")||t.storage,n.stringifyPayload="false"!==e.getAttribute("data-stringify-payload");var r="true"===e.getAttribute("data-capture-performance");for(var s of(n.capture_performance=!!r||t.capture_performance,n.globalAttributes=h({},t.globalAttributes),Array.from(e.attributes)))s.name.startsWith("data-vt-")&&(n.globalAttributes[s.name.slice(8).replace(/-/g,"_")]=s.value);return n}getConfig(){return h({},this.config)}updateConfig(t){var e=function(t,e){return void 0===e.chat?e:h({},e,{chat:Sl(t.chat,e.chat)})}(this.config,t);this.config=h({},this.config,e)}}var Tl=[Xa,Ga,Za,Ka],Al=31536e3,El=["herokuapp.com","vercel.app","netlify.app"];function Il(t){var e;if(!t||"undefined"==typeof document)return"";var n=null===(e=document.location)||void 0===e?void 0:e.hostname;if(!n)return"";var i=n.match(/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i);return i?"."+i[0]:""}class Ml{constructor(t){var e,n,i;this.memoryStorage=new Map,this.Fe=null,this.method=t.method,this.cross_subdomain=null!==(e=t.cross_subdomain)&&void 0!==e?e:function(){var t;if("undefined"==typeof document)return!1;var e=null===(t=document.location)||void 0===t?void 0:t.hostname;if(!e)return!1;var n=e.split(".").slice(-2).join(".");return!El.includes(n)}(),this.sameSite=null!==(n=t.sameSite)&&void 0!==n?n:"Lax",this.secure=null!==(i=t.secure)&&void 0!==i?i:"undefined"!=typeof location&&"https:"===location.protocol}isLocalStorageSupported(){if(null!==this.Fe)return this.Fe;if(void 0===t||!t.localStorage)return this.Fe=!1,!1;try{var e="__vt_ls_test__";t.localStorage.setItem(e,"1");var n="1"===t.localStorage.getItem(e);return t.localStorage.removeItem(e),this.Fe=n,n||A().warn("storage","localStorage unavailable, using cookies"),n}catch(t){return this.Fe=!1,A().warn("storage","localStorage unavailable, using cookies"),!1}}isCriticalProperty(t){return Tl.includes(t)}get(t){var e;try{switch(this.method){case il:return null!==(e=this.memoryStorage.get(t))&&void 0!==e?e:null;case el:return this.getLocalStoragePlusCookie(t);case tl:return this.getLocalStorage(t);case nl:return this.readFromSessionStorage(t);default:return this.getCookie(t)}}catch(e){return A().warn("storage",'get error for "'+t+'":',e),null}}set(t,e,n){try{switch(this.method){case il:this.memoryStorage.set(t,e);break;case el:this.setLocalStoragePlusCookie(t,e,n);break;case tl:this.setLocalStorage(t,e);break;case nl:this.writeToSessionStorage(t,e);break;default:this.setCookie(t,e,null!=n?n:Al)}}catch(e){A().warn("storage",'set error for "'+t+'":',e)}}remove(t){try{switch(this.method){case il:this.memoryStorage.delete(t);break;case el:this.removeLocalStoragePlusCookie(t);break;case tl:this.removeLocalStorage(t);break;case nl:this.removeFromSessionStorage(t);break;default:this.removeCookie(t)}}catch(e){A().warn("storage",'remove error for "'+t+'":',e)}}getLocalStoragePlusCookie(e){if(this.isCriticalProperty(e)){var n=this.getCookie(e),i=this.getLocalStorage(e);if(null!==n){if(i!==n&&this.isLocalStorageSupported())try{null==t||t.localStorage.setItem(e,n)}catch(t){}return n}return null!==i?i:this.readFromSessionStorage(e)}return this.getLocalStorage(e)}setLocalStoragePlusCookie(t,e,n){this.setLocalStorage(t,e),this.isCriticalProperty(t)&&(this.setCookie(t,e,null!=n?n:Al),this.writeToSessionStorage(t,e))}removeLocalStoragePlusCookie(t){this.removeLocalStorage(t),this.isCriticalProperty(t)&&(this.removeCookie(t),this.removeFromSessionStorage(t))}getLocalStorage(e){var n;if(!this.isLocalStorageSupported())return null;try{return null!==(n=null==t?void 0:t.localStorage.getItem(e))&&void 0!==n?n:null}catch(t){return null}}setLocalStorage(e,n){if(this.isLocalStorageSupported())try{null==t||t.localStorage.setItem(e,n)}catch(t){A().warn("storage","localStorage write error:",t)}}removeLocalStorage(e){if(this.isLocalStorageSupported())try{null==t||t.localStorage.removeItem(e)}catch(t){}}readFromSessionStorage(e){var n;try{return null!==(n=null==t?void 0:t.sessionStorage.getItem(e))&&void 0!==n?n:null}catch(t){return null}}writeToSessionStorage(e,n){try{null==t||t.sessionStorage.setItem(e,n)}catch(t){A().warn("storage","sessionStorage write error:",t)}}removeFromSessionStorage(e){try{null==t||t.sessionStorage.removeItem(e)}catch(t){}}getCookie(t){if("undefined"==typeof document)return null;var e=t+"=";for(var n of document.cookie.split(";")){var i=n.trim();if(i.startsWith(e))try{return decodeURIComponent(i.slice(e.length))}catch(t){return i.slice(e.length)}}return null}setCookie(t,e,n){if("undefined"!=typeof document){var i=Il(this.cross_subdomain),r=t+"="+encodeURIComponent(e)+"; Max-Age="+n+"; path=/; SameSite="+this.sameSite;this.secure&&(r+="; Secure"),i&&(r+="; domain="+i),document.cookie=r}}removeCookie(t){if("undefined"!=typeof document){var e=Il(this.cross_subdomain);document.cookie=t+"=; Max-Age=0; path=/"+(e?"; domain="+e:""),document.cookie=t+"=; Max-Age=0; path=/"}}getWithExpiry(t){var e=this.get(t);if(!e)return null;try{var n=JSON.parse(e);return n.expiry&&Date.now()>n.expiry?(this.remove(t),null):n.value}catch(t){return null}}setWithExpiry(t,e,n){var i=h({value:e},n?{expiry:Date.now()+n}:{});this.set(t,JSON.stringify(i))}getJSON(t){var e=this.get(t);if(!e)return null;try{return JSON.parse(e)}catch(t){return null}}setJSON(t,e,n){this.set(t,JSON.stringify(e),n)}canUseSessionStorage(){if(void 0===t||!(null==t?void 0:t.sessionStorage))return!1;try{var e="__vt_ss_test__";return t.sessionStorage.setItem(e,"1"),t.sessionStorage.removeItem(e),!0}catch(t){return!1}}getSessionStorage(){var e;return this.canUseSessionStorage()&&null!==(e=null==t?void 0:t.sessionStorage)&&void 0!==e?e:null}setMethod(t){this.method=t}getMethod(){return this.method}}class Ol{constructor(t,e){void 0===t&&(t="cookie"),this.He=!1,this.storage=new Ml({method:t,cross_subdomain:e,sameSite:"Lax"}),this.We=void 0,A().debug("session","ctor")}hydrateFromStorage(){A().debug("session","hydrate"),this.Je()}getSessionId(){var t=this.Ve();return t||(t=J(16),this.Ke(t),this.He=!0),t}setSessionId(){var t=this.Ve(),e=t||J(16);return t||(this.He=!0),this.Ke(e),e}resetSessionId(){this.Ge(),this.He=!0,this.setSessionId(),this.Xe(J(16))}consumeSessionStart(){return!!this.He&&(this.He=!1,!0)}Ve(){return this.storage.get(Wa)}Ke(t){this.storage.set(Wa,t,1800)}Ge(){this.storage.remove(Wa)}getWindowId(){if(this.We)return this.We;var t=this.storage.getSessionStorage();if(t){var e=t.getItem(Ja);if(e)return this.We=e,e}var n=J(16);return this.Xe(n),n}Xe(t){if(t!==this.We){this.We=t;var e=this.storage.getSessionStorage();e&&e.setItem(Ja,t)}}Je(){var t=this.storage.getSessionStorage();if(t){var e=t.getItem(Va),n=t.getItem(Ja);n&&!e?this.We=n:(n&&t.removeItem(Ja),this.Xe(J(16))),t.setItem(Va,"true"),this.Qe()}else this.We=J(16)}Qe(){var e=this.storage.getSessionStorage();t&&e&&G(t,"beforeunload",()=>{var t=this.storage.getSessionStorage();t&&t.removeItem(Va)},{capture:!1})}updateStorageMethod(t,e){this.storage=new Ml({method:t,cross_subdomain:e,sameSite:"Lax"})}}function Pl(t){if(!i)return null;var e=i.createElement("a");return e.href=t,e}function Rl(t){try{return decodeURIComponent(t).replace(/\+/g," ")}catch(e){return t.replace(/\+/g," ")}}function Dl(t){for(var e={},n=function(t){return((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"")}(t).split("&"),i=0;i<n.length;i++){var r=n[i];if(r){var s=r.indexOf("="),o=-1===s?r:r.slice(0,s);if(o){var a=Rl(o),l=-1===s?"":r.slice(s+1);e[a]=Rl(l)}}}return e}function Ul(t,e){var n;return null!==(n=Dl(t)[e])&&void 0!==n?n:""}function jl(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[0]||"",s=i[1],o=r.split("?"),a=o[1],l=o[0],u=(a||"").split("&"),h=[],d=0;d<u.length;d++){var c=u[d].split("="),v=c[0],f=c.slice(1).join("=");-1!==e.indexOf(v)?h.push(v+"="+n):v&&h.push(v+(f?"="+f:""))}var p=h.join("&");return l+(p?"?"+p:"")+(s?"#"+s:"")}var Bl="_fbp",Nl="_fbc",Ll=15552e3,$l=7776e3;function zl(){void 0!==i&&(function(){if(ql(Bl))return;var t=Date.now(),e=Math.floor(1e9+9e9*Math.random()),n="fb.1."+t+"."+e;Fl(Bl,n,Ll)}(),function(){if(!(null==r?void 0:r.search))return;try{var t=new URL(r.href).searchParams.get("fbclid");if(!(null==t?void 0:t.trim()))return;var e="fb.1."+Date.now()+"."+t.trim();Fl(Nl,e,$l)}catch(t){}}())}function ql(t){if(void 0===i||!(null==i?void 0:i.cookie))return null;var e=t+"=";for(var n of i.cookie.split(";")){var r=n.trim();if(r.startsWith(e))try{return decodeURIComponent(r.slice(e.length))}catch(t){return r.slice(e.length)}}return null}function Fl(t,e,n){if(void 0!==i){var s=void 0!==r&&"https:"===r.protocol?"; Secure":"";i.cookie=t+"="+encodeURIComponent(e)+"; Max-Age="+n+"; path=/; SameSite=Lax"+s}}var Hl="Mobile",Wl="iOS",Jl="Android",Vl="Tablet",Kl=Jl+" "+Vl,Gl="iPad",Xl="Apple",Ql=Xl+" Watch",Zl="Safari",Yl="BlackBerry",tu="Samsung",eu=tu+"Browser",nu=tu+" Internet",iu="Chrome",ru=iu+" OS",su=iu+" "+Wl,ou="Internet Explorer",au=ou+" "+Hl,lu="Opera",uu=lu+" Mini",hu="Edge",du="Microsoft "+hu,cu="Firefox",vu=cu+" "+Wl,fu="Nintendo",pu="PlayStation",gu="Xbox",mu=Jl+" "+Hl,bu=Hl+" "+Zl,yu="Windows",wu=yu+" Phone",xu="Nokia",_u="Ouya",ku="Generic",Su=ku+" "+Hl.toLowerCase(),Cu=ku+" "+Vl.toLowerCase(),Tu="Konqueror",Au="(\\d+(\\.\\d+)?)",Eu=new RegExp("Version/"+Au),Iu=new RegExp(gu,"i"),Mu=new RegExp(pu+" \\w+","i"),Ou=new RegExp(fu+" \\w+","i"),Pu=new RegExp(Yl+"|PlayBook|BB10","i"),Ru={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"};function Du(t,e){return t.toLowerCase().includes(e.toLowerCase())}var Uu=(t,e)=>e&&Du(e,Xl)||function(t){return Du(t,Zl)&&!Du(t,iu)&&!Du(t,Jl)}(t),ju=function(t,e){return e=e||"",Du(t," OPR/")&&Du(t,"Mini")?uu:Du(t," OPR/")?lu:Pu.test(t)?Yl:Du(t,"IE"+Hl)||Du(t,"WPDesktop")?au:Du(t,eu)?nu:Du(t,hu)||Du(t,"Edg/")?du:Du(t,"FBIOS")?"Facebook "+Hl:Du(t,"UCWEB")||Du(t,"UCBrowser")?"UC Browser":Du(t,"CriOS")?su:Du(t,"CrMo")||Du(t,iu)?iu:Du(t,Jl)&&Du(t,Zl)?mu:Du(t,"FxiOS")?vu:Du(t.toLowerCase(),Tu.toLowerCase())?Tu:Uu(t,e)?Du(t,Hl)?bu:Zl:Du(t,cu)?cu:Du(t,"MSIE")||Du(t,"Trident/")?ou:Du(t,"Gecko")?cu:""},Bu={[au]:[new RegExp("rv:"+Au)],[du]:[new RegExp(hu+"?\\/"+Au)],[iu]:[new RegExp("("+iu+"|CrMo)\\/"+Au)],[su]:[new RegExp("CriOS\\/"+Au)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Au)],[Zl]:[Eu],[bu]:[Eu],[lu]:[new RegExp("(Opera|OPR)\\/"+Au)],[cu]:[new RegExp(cu+"\\/"+Au)],[vu]:[new RegExp("FxiOS\\/"+Au)],[Tu]:[new RegExp("Konqueror[:/]?"+Au,"i")],[Yl]:[new RegExp(Yl+" "+Au),Eu],[mu]:[new RegExp("android\\s"+Au,"i")],[nu]:[new RegExp(eu+"\\/"+Au)],[ou]:[new RegExp("(rv:|MSIE )"+Au)],Mozilla:[new RegExp("rv:"+Au)]},Nu=function(t,e){var n=ju(t,e),i=Bu[n];if(void 0===i)return null;for(var r=0;r<i.length;r++){var s=i[r],o=t.match(s);if(o)return parseFloat(o[o.length-2])}return null},Lu=[[new RegExp(gu+"; "+gu+" (.*?)[);]","i"),t=>[gu,t&&t[1]||""]],[new RegExp(fu,"i"),[fu,""]],[new RegExp(pu,"i"),[pu,""]],[Pu,[Yl,""]],[new RegExp(yu,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[wu,""];if(new RegExp(Hl).test(e)&&!/IEMobile\b/.test(e))return[yu+" "+Hl,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=n[1],r=Ru[i]||"";return/arm/i.test(e)&&(r="RT"),[yu,r]}return[yu,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){var e=[t[3],t[4],t[5]||"0"];return[Wl,e.join(".")]}return[Wl,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=void 0===t[2]?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Jl+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Jl+")","i"),t=>{if(t&&t[2]){var e=[t[2],t[3],t[4]||"0"];return[Jl,e.join(".")]}return[Jl,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];if(t&&t[1]){var n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[ru,""]],[/Linux|debian/i,["Linux",""]]],$u=function(t){return Ou.test(t)?fu:Mu.test(t)?pu:Iu.test(t)?gu:new RegExp(_u,"i").test(t)?_u:new RegExp("("+wu+"|WPDesktop)","i").test(t)?wu:/iPad/.test(t)?Gl:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Ql:Pu.test(t)?Yl:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(xu,"i").test(t)?xu:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?!new RegExp(Hl).test(t)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)?/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Jl:Kl:Jl:new RegExp("(pda|"+Hl+")","i").test(t)?Su:new RegExp(Vl,"i").test(t)&&!new RegExp(Vl+" pc","i").test(t)?Cu:""},zu="https?://(.*)",qu=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Fu=Q(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],qu),Hu="<masked>";function Wu(t,e){var n=Fu.concat([]),i=X({},function(t){var e={};return K(Dl(t),function(t,n){"string"==typeof n&&n.startsWith("utm_")&&t&&(e[n]=t)}),e}(t));return K(n,function(e){if(e.startsWith("utm_")){if(!(e in i)){var n=Ul(t,e);i[e]=n||null}}else{var r=Ul(t,e);i[e]=r||null}}),i}function Ju(t){var e=function(t){return t?0===t.search(zu+"google.([^/?]*)")?"google":0===t.search(zu+"bing.com")?"bing":0===t.search(zu+"yahoo.com")?"yahoo":0===t.search(zu+"duckduckgo.com")?"duckduckgo":null:null}(t),n="yahoo"!==e?"q":"p",r={};if(!function(t){return null===t}(e)){r.$search_engine=e;var s=i?Ul(i.referrer,n):"";s.length&&(r.ph_keyword=s)}return r}function Vu(){if("undefined"!=typeof navigator)return navigator.language||navigator.userLanguage}function Ku(){return(null==i?void 0:i.referrer)||"$direct"}function Gu(){var t;return(null==i?void 0:i.referrer)&&(null===(t=Pl(i.referrer))||void 0===t?void 0:t.host)||"$direct"}function Xu(t){var e=function(t){var e,{r:n,u:i}=t,r={$referrer:n,$referring_domain:null==n?void 0:"$direct"===n?"$direct":null===(e=Pl(n))||void 0===e?void 0:e.host};if(i){r.$current_url=i;var s=Pl(i);r.$host=null==s?void 0:s.host,r.$pathname=null==s?void 0:s.pathname,X(r,Wu(i))}return n&&X(r,Ju(n)),r}(t),n={};return K(e,function(t,e){var i;n["$initial_"+(i=String(e),i.startsWith("$")?i.substring(1):i)]=t}),n}function Qu(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){return}}function Zu(){try{return(new Date).getTimezoneOffset()}catch(t){return}}function Yu(e,n){if(!o)return{};var i,s,a,l=e?Q([],qu,n||[]):[],[u,h]=function(t){for(var e=0;e<Lu.length;e++){var[n,i]=Lu[e],r=n.exec(t);if(r){var s="function"==typeof i?i(r,t):i;if(s)return s}}return["",""]}(o),d=ql(Bl)||void 0,c=ql(Nl)||void 0;return X(Z({$os:u,$os_version:h,$browser:ju(o,navigator.vendor),$device:$u(o),$device_type:(s=o,a=$u(s),a===Gl||a===Kl||"Kobo"===a||"Kindle Fire"===a||a===Cu?Vl:a===fu||a===gu||a===pu||a===_u?"Console":a===Ql?"Wearable":a?Hl:"Desktop"),$timezone:Qu(),$timezone_offset:Zu(),$fb_browser_id:d,$fb_click_id:c}),{$current_url:jl(null==r?void 0:r.href,l,Hu),$host:null==r?void 0:r.host,$pathname:null==r?void 0:r.pathname,$raw_user_agent:o.length>1e3?o.substring(0,997)+"...":o,$browser_version:Nu(o,navigator.vendor),$browser_language:Vu(),$browser_language_prefix:(i=Vu(),"string"==typeof i?i.split("-")[0]:void 0),$screen_height:null==t?void 0:t.screen.height,$screen_width:null==t?void 0:t.screen.width,$viewport_height:null==t?void 0:t.innerHeight,$viewport_width:null==t?void 0:t.innerWidth,$lib:"web",$lib_version:Ha,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10)})}class th{constructor(t,e){void 0===t&&(t="localStorage"),this.Ze=!1,this.storage=new Ml({method:t,cross_subdomain:e,sameSite:"Lax"}),this.userIdentity=this.generateEphemeralIdentity(),A().debug("user","ctor","ephemeral identity only")}hydrateFromStorage(){A().debug("user","hydrate start"),this.userIdentity=this.loadUserIdentity();var t=this.userIdentity.anonymous_id,e=this.userIdentity.distinct_id;A().debug("user","hydrate done","anonymous_id",t?t.slice(0,12)+"...":"n/a","distinct_id",e?e.slice(0,12)+"...":"null")}generateEphemeralIdentity(){return{distinct_id:null,anonymous_id:this.generateAnonymousId(),device_id:this.generateDeviceId(),properties:{},user_state:"anonymous"}}getUserIdentity(){return h({},this.userIdentity)}getDistinctId(){return this.userIdentity.distinct_id}getAnonymousId(){var t=this.userIdentity.anonymous_id;return t||(this.userIdentity.anonymous_id=this.generateAnonymousId(),this.storage.set(Xa,this.userIdentity.anonymous_id,Al),A().debug("user","getAnonymousId generated (was missing)",this.userIdentity.anonymous_id.slice(0,12)+"..."),this.userIdentity.anonymous_id)}getUserProperties(){return h({},this.userIdentity.properties)}getEffectiveId(){return this.userIdentity.distinct_id||this.getAnonymousId()}getDeviceId(){return this.userIdentity.device_id}getUserState(){return this.userIdentity.user_state}consumeFirstVisit(){return!!this.Ze&&(this.Ze=!1,!0)}applyUpdate(t){if(void 0!==t.distinct_id&&(this.userIdentity.distinct_id=t.distinct_id),void 0!==t.user_state&&(this.userIdentity.user_state=t.user_state),void 0!==t.device_id&&(this.userIdentity.device_id=t.device_id),t.properties_set&&(this.userIdentity.properties=h({},this.userIdentity.properties,t.properties_set)),t.properties_set_once)for(var e of Object.keys(t.properties_set_once))e in this.userIdentity.properties||(this.userIdentity.properties[e]=t.properties_set_once[e]);this.saveUserIdentity()}reset(t){this.userIdentity={distinct_id:null,anonymous_id:this.generateAnonymousId(),device_id:t?this.generateDeviceId():this.userIdentity.device_id,properties:{$last_vtilt_reset:(new Date).toISOString()},user_state:"anonymous"},this.saveUserIdentity()}set_initial_person_info(t,e){if(!this.getStoredUserProperties()[rl]){var n=function(t,e){var n=t?Q([],qu,e||[]):[],i=null==r?void 0:r.href.substring(0,1e3);return{r:Ku().substring(0,1e3),u:i?jl(i,n,Hu):void 0}}(t,e);this.register_once({[rl]:n},void 0)}}get_initial_props(){var t=this.getStoredUserProperties()[rl];return t?Xu(t):{}}update_referrer_info(){var t={$referrer:Ku(),$referring_domain:Gu()};this.register_once(t,void 0)}loadUserIdentity(){var t=this.storage.get(Xa),e=this.storage.get(Ga),n=this.storage.get(Za),i=this.storage.get(Ka),r=this.getStoredUserProperties(),s=t||this.generateAnonymousId(),o=e||this.generateDeviceId(),a=n||null,l=i||"anonymous";t?A().debug("user","hydrate","loaded from storage",t.slice(0,12)+"..."):(this.Ze=!0,A().debug("user","hydrate","generated new anonymous_id"));var u=s||this.generateAnonymousId();return t||this.storage.set(Xa,u,Al),e||this.storage.set(Ga,o,Al),i||this.storage.set(Ka,l,Al),{distinct_id:a,anonymous_id:u,device_id:o,properties:r,user_state:l}}saveUserIdentity(){this.storage.set(Xa,this.userIdentity.anonymous_id,Al),this.storage.set(Ga,this.userIdentity.device_id,Al),this.storage.set(Ka,this.userIdentity.user_state,Al),this.userIdentity.distinct_id?this.storage.set(Za,this.userIdentity.distinct_id,Al):this.storage.remove(Za),this.setStoredUserProperties(this.userIdentity.properties)}getStoredUserProperties(){return this.storage.getJSON(Ya)||{}}setStoredUserProperties(t){this.storage.setJSON(Ya,t,Al)}register_once(t,e){var n=this.getStoredUserProperties(),i=!1;for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(r in n||(n[r]=t[r],i=!0));if(e)for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(s in n||(n[s]=e[s],i=!0));i&&this.setStoredUserProperties(n)}generateAnonymousId(){return"anon_"+J(16)}generateDeviceId(){return"device_"+J(16)}updateStorageMethod(t,e){this.storage=new Ml({method:t,cross_subdomain:e,sameSite:"Lax"})}}var eh=["LCP","CLS","FCP","INP","TTFB"],nh=["LCP","CLS","FCP","INP"];class ih{constructor(t,e){this.Ye=!1,this.tn=!1,this.en=[],this.nn=!1,this.rn=[],this._instance=t,this.ae=e}get isEnabled(){return!1!==this.ae.enabled}get isStarted(){return this.Ye}get isLoaded(){return!!this.sn}an(t){var e;if(this.sn)t(this.sn);else if(this.en.push(t),!this.tn){this.tn=!0;var n=null===(e=a.__VTiltExtensions__)||void 0===e?void 0:e.loadExternalDependency;if(!n)return A().error("feature",this.name,"loadExternalDependency not available"),this.tn=!1,void(this.en=[]);n(this._instance,this.scriptName,t=>{if(this.tn=!1,t)return A().error("feature",this.name,"could not load "+this.scriptName+":",t),void(this.en=[]);this.sn||(this.sn=this.ln());var e=this.sn,n=this.en;for(var i of(this.en=[],n))try{i(e)}catch(t){A().error("feature",this.name,"load callback error:",t)}})}}startIfEnabled(){this.isEnabled&&!this.Ye&&(this.Ye=!0,this.an(t=>this.un(t)))}un(t){}stop(){this.Ye=!1}updateConfig(t){this.ae=h({},this.ae,t)}hn(t){this.nn?t():this.rn.push(t)}dn(){if(!this.nn){this.nn=!0;var t=this.rn;for(var e of(this.rn=[],t))try{e()}catch(t){A().error("feature",this.name,"deferred call error:",t)}}}cn(){this.nn=!1,this.rn=[]}}class rh extends ih{startIfEnabledOrStop(t){if(this.isEnabled){if(this.Ye&&this.sn)return;this.Ye=!0,this.an(t=>this.un(t))}else this.stop()}}var sh=9e5,oh="web-vitals";class ah extends ih{static extractConfig(t){var e=t.capture_performance;return"boolean"==typeof e?{web_vitals:e}:"object"==typeof e&&null!==e?e:{web_vitals:!1}}constructor(t,e){super(t,null!=e?e:ah.extractConfig(t.getConfig())),this.name="WebVitals",this.scriptName="web-vitals",this.vn=this.fn()}get isEnabled(){var t=null==r?void 0:r.protocol;return("http:"===t||"https:"===t)&&!0===this.ae.web_vitals}startIfEnabled(){if(this.isEnabled&&!this.Ye&&t){var e=this.pn();e?(this.Ye=!0,this.sn=e,this.gn(e)):(this.Ye=!0,this.an(t=>this.un(t)))}}stop(){this.Ye&&(this.mn(),this.bn&&(clearTimeout(this.bn),this.bn=void 0),this.Ye=!1)}onConfigUpdate(t){var e=ah.extractConfig(t),n=this.isEnabled;this.ae=e,n||!this.isEnabled||this.Ye?n&&!this.isEnabled&&this.Ye&&this.stop():this.startIfEnabled()}ln(){var t=this.pn();if(!t)throw new Error("[vTilt:web-vitals] web-vitals loaded but callbacks not registered");return t}un(t){this.gn(t)}get allowedMetrics(){return this.ae.web_vitals_allowed_metrics||nh}get flushTimeoutMs(){return this.ae.web_vitals_delayed_flush_ms||5e3}get maxAllowedValue(){var t=this.ae.__web_vitals_max_value;return void 0===t?sh:0===t?0:t<6e4?sh:t}fn(){return{url:void 0,pathname:void 0,metrics:[],firstMetricTimestamp:void 0}}pn(){var t;return null===(t=a.__VTiltExtensions__)||void 0===t?void 0:t.webVitalsCallbacks}gn(t){var e=this.allowedMetrics,n=this.yn.bind(this);e.includes("LCP")&&t.onLCP&&t.onLCP(n),e.includes("CLS")&&t.onCLS&&t.onCLS(n,{reportAllChanges:!0}),e.includes("FCP")&&t.onFCP&&t.onFCP(n),e.includes("INP")&&t.onINP&&t.onINP(n),e.includes("TTFB")&&t.onTTFB&&t.onTTFB(n)}wn(){var e;return null===(e=null==t?void 0:t.location)||void 0===e?void 0:e.href}xn(){return null==r?void 0:r.pathname}yn(e){var n,s,o;try{if(!t||!i||!r)return;if(!(null==e?void 0:e.name)||void 0===(null==e?void 0:e.value))return void A().warn(oh,"invalid metric received",e);if(this.maxAllowedValue>0&&e.value>=this.maxAllowedValue&&"CLS"!==e.name)return void A().warn(oh,"ignoring "+e.name+" with value >= "+this.maxAllowedValue+"ms");var a=this.wn(),l=this.xn();if(!a)return void A().warn(oh,"could not determine current URL");this.vn.url&&this.vn.url!==a&&this.mn(),this.vn.url||(this.vn.url=a,this.vn.pathname=l),this.vn.firstMetricTimestamp||(this.vn.firstMetricTimestamp=Date.now());var u=this._n(e.attribution),d=null!==(o=null===(s=(n=this._instance).getSessionId)||void 0===s?void 0:s.call(n))&&void 0!==o?o:null,c=this.kn(),v=h({},e,{attribution:u,timestamp:Date.now(),$current_url:a,$session_id:d,$window_id:c}),f=this.vn.metrics.findIndex(t=>t.name===e.name);f>=0?this.vn.metrics[f]=v:this.vn.metrics.push(v),this.Sn(),this.vn.metrics.length>=this.allowedMetrics.length&&this.mn()}catch(t){A().error(oh,"error adding metric to buffer:",t)}}_n(t){if(t){var e=h({},t);return"interactionTargetElement"in e&&delete e.interactionTargetElement,e}}kn(){var t;try{return(null===(t=this._instance.sessionManager)||void 0===t?void 0:t.getWindowId())||null}catch(t){return null}}Sn(){this.bn&&clearTimeout(this.bn),this.bn=setTimeout(()=>{this.mn()},this.flushTimeoutMs)}mn(){if(this.bn&&(clearTimeout(this.bn),this.bn=void 0),0!==this.vn.metrics.length){try{var t={$pathname:this.vn.pathname,$current_url:this.vn.url};for(var e of this.vn.metrics)t["$web_vitals_"+e.name+"_value"]=e.value,t["$web_vitals_"+e.name+"_event"]={name:e.name,value:e.value,delta:e.delta,rating:e.rating,id:e.id,navigationType:e.navigationType,attribution:e.attribution,$session_id:e.$session_id,$window_id:e.$window_id};this._instance.capture("$web_vitals",t)}catch(t){A().error(oh,"error flushing metrics:",t)}this.vn=this.fn()}}}function lh(t,e,n){try{if(!(e in t))return()=>{};var i=t[e],r=n(i);return b(r)&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__vtilt_wrapped__:{enumerable:!1,value:!0}})),t[e]=r,()=>{t[e]=i}}catch(t){return()=>{}}}class uh{constructor(e,n){var i;this.name="HistoryAutocapture",this.Ye=!1,this._instance=e,this.ae=n||uh.extractConfig(e.getConfig()),this.Cn=(null===(i=null==t?void 0:t.location)||void 0===i?void 0:i.pathname)||""}static extractConfig(t){return{enabled:!1!==t.capture_pageview}}get isEnabled(){return!1!==this.ae.enabled&&!1!==this._instance.getConfig().capture_pageview}get isStarted(){return this.Ye}startIfEnabled(){this.isEnabled&&!this.Ye&&this.Tn()}stop(){this.Ye&&(this.An&&(this.An(),this.An=void 0),this.Ye=!1)}onConfigUpdate(t){this.ae=uh.extractConfig(t),this.isEnabled&&!this.Ye?this.Tn():!this.isEnabled&&this.Ye&&this.stop()}Tn(){t&&r&&(this.Cn=r.pathname||"",this.En(),this.In(),this.Ye=!0,A().info("history-autocapture","started"))}En(){var e,n;if(null==t?void 0:t.history){var i=this;(null===(e=t.history.pushState)||void 0===e?void 0:e.__vtilt_wrapped__)||lh(t.history,"pushState",t=>function(e,n,r){i.Mn(r),t.call(this,e,n,r),i.On("pushState")}),(null===(n=t.history.replaceState)||void 0===n?void 0:n.__vtilt_wrapped__)||lh(t.history,"replaceState",t=>function(e,n,r){i.Mn(r),t.call(this,e,n,r),i.On("replaceState")})}}Mn(t){var e;if(r){var n=r.pathname||"",i=null!==(e=function(t){if(!r)return null;if(null==t||""===t)return r.pathname||null;try{return new URL(String(t),r.href).pathname}catch(t){return null}}(t))&&void 0!==e?e:n;i!==n&&this._instance.tryCapturePageleave("spa_transition")}}In(){if(!this.An&&t){var e=()=>{this.On("popstate")};G(t,"popstate",e),this.An=()=>{null==t||t.removeEventListener("popstate",e)}}}On(e){this.isEnabled&&this.Ye&&I(()=>{var n,s=null===(n=null==t?void 0:t.location)||void 0===n?void 0:n.pathname;if(s&&r&&i)if(s!==this.Cn){A().debug("history-autocapture",e,s),this.Cn=s;var o={navigation_type:e};this._instance.capture(sl,o)}else this.Cn=s})}}var hh=["a","button","form","input","select","textarea","label"],dh="$copy_autocapture",ch=['[id*="cookie" i]','[class*="cookie" i]','[id*="consent" i]','[class*="consent" i]','[id*="gdpr" i]','[class*="gdpr" i]','[id*="privacy-banner" i]','[class*="privacy-banner" i]','[id*="cookie-banner" i]','[class*="cookie-banner" i]','[id*="cookie-notice" i]','[class*="cookie-notice" i]',"#CybotCookiebotDialog",'[class^="CybotCookiebotDialog"]','[id^="onetrust"]','[class^="onetrust"]','[id^="cc-"]',".cc-banner",".cc-window",".cc-revoke",'[id^="cookieconsent"]','[class^="cookieconsent"]','[id^="gdpr-cookie"]','[id^="qc-cmp"]',"#termly-code-snippet-support",'[id^="iubenda"]','[id^="truste"]','[class^="truste"]',"#consent_blackbar",'[id^="didomi"]','[id^="usercentrics"]',"#uc-center-container",".klaro","#klaro","#cookiescript_injected",".cky-consent-container","#cky-consent","#cmplz-cookiebanner-container","#gdpr-cookie-message",'[class*="fs-cc"]','[class*="fc-cc"]',"[fs-cc]","[fs-cc-checkbox]",'[class*="cookie-preferences"]',"#cookie-preferences",'[role="dialog"][aria-label*="cookie" i]','[role="dialog"][aria-label*="consent" i]','[aria-describedby*="cookie" i]','[aria-label*="Cookie Preferences" i]'];function vh(t){return t.replace(/^\s+|\s+$/g,"")}function fh(t,e){return t.indexOf(e)>-1}function ph(t){return 1===(null==t?void 0:t.nodeType)}function gh(t){return 3===(null==t?void 0:t.nodeType)}function mh(t,e){var n;return(null===(n=null==t?void 0:t.tagName)||void 0===n?void 0:n.toLowerCase())===e}function bh(t){return 11===(null==t?void 0:t.nodeType)}function yh(t){return t?vh(t).split(/\s+/):[]}function wh(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className&&"string"==typeof t.className.baseVal?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return yh(e)}function xh(t){return g(t)?null:vh(t).split(/(\s+)/).filter(t=>Dh(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function _h(t){var e,n="";if(jh(t)&&!Bh(t)&&t.childNodes&&t.childNodes.length)for(var i=0;i<t.childNodes.length;i++){var r=t.childNodes[i];gh(r)&&r.textContent&&(n+=null!==(e=xh(r.textContent))&&void 0!==e?e:"")}return vh(n)}function kh(t){var e,n="";if(t&&t.childNodes&&t.childNodes.length)for(var i=0;i<t.childNodes.length;i++){var r=t.childNodes[i];if(r&&"span"===(null===(e=r.tagName)||void 0===e?void 0:e.toLowerCase()))try{n=(n+" "+_h(r)).trim(),r.childNodes&&r.childNodes.length&&(n=(n+" "+kh(r)).trim())}catch(t){}}return n}function Sh(t){var e=_h(t);return Dh(e=(e+" "+kh(t)).trim())?e:""}function Ch(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do{e=e.previousSibling}while(e&&!ph(e));return e}function Th(t){var e=t.parentNode;return!(!e||!ph(e))&&e}function Ah(e){var n=null==t?void 0:t.location.href;return!!(n&&e&&e.some(t=>n.match(t)))}var Eh="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",Ih=new RegExp("^(?:"+Eh+")$"),Mh=new RegExp(Eh),Oh="\\d{3}-?\\d{2}-?\\d{4}",Ph=new RegExp("^("+Oh+")$"),Rh=new RegExp("("+Oh+")");function Dh(t,e){if(void 0===e&&(e=!0),g(t))return!1;if(f(t)){if(t=vh(t),(e?Ih:Mh).test((t||"").replace(/[- ]/g,"")))return!1;if((e?Ph:Rh).test(t))return!1}return!0}function Uh(t){return!!f(t)&&("_ngcontent"===t.substring(0,10)||"_nghost"===t.substring(0,7))}function jh(t){for(var e=t;e&&e.parentNode&&!mh(e,"body");e=e.parentNode){var n=wh(e);if(fh(n,"vt-sensitive")||fh(n,"vt-no-capture"))return!1}if(fh(wh(t),"vt-include"))return!0;var i=t.type||"";if(f(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var r=t.name||t.id||"";if(f(r)){if(/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(r.replace(/[^a-zA-Z0-9]/g,"")))return!1}return!0}function Bh(t){return!!(mh(t,"input")&&!["button","checkbox","submit","reset","radio"].includes(t.type)||mh(t,"textarea")||"true"===t.getAttribute("contenteditable"))}function Nh(t){if(!jh(t))return null;if(mh(t,"input")){var e=t,n=(e.type||"text").toLowerCase();if("password"===n||"hidden"===n)return null;if("checkbox"===n||"radio"===n){var i={$el_value:e.checked?"true":"false"},r=function(t){var e=t.closest("label");if(e){var n=vh(e.textContent||"");if(n&&Dh(n))return xh(n)||null}if(t.id)try{var i=null===document||void 0===document?void 0:document.querySelector('label[for="'+t.id+'"]');if(i){var r=vh(i.textContent||"");if(r&&Dh(r))return xh(r)||null}}catch(t){}return null}(e);return r?i.$selected_text=r:e.value&&Dh(e.value)&&(i.$selected_text=e.value),i}var s=e.value;if(s&&Dh(s)){var o=xh(s);if(o)return{$el_value:o}}return null}if(mh(t,"select")){var a=t,l=a.selectedIndex;if(l>=0&&a.options[l]){var u=a.options[l],h={};u.value&&Dh(u.value)&&(h.$el_value=u.value);var d=u.text;if(d&&Dh(d)){var c=xh(d);c&&(h.$selected_text=c)}if(h.$el_value||h.$selected_text)return h}return null}return mh(t,"textarea"),null}function Lh(e,n,i,r,s){if(void 0===i&&(i=void 0),!t)return{capture:!1,reason:"no_window"};if(!e)return{capture:!1,reason:"no_element"};if(mh(e,"html")||!ph(e))return{capture:!1,reason:"html_element"};if((null==i?void 0:i.url_allowlist)&&!Ah(i.url_allowlist))return{capture:!1,reason:"url_allowlist_miss"};if((null==i?void 0:i.url_ignorelist)&&Ah(i.url_ignorelist))return{capture:!1,reason:"url_ignorelist_hit"};if(null==i?void 0:i.dom_event_allowlist){var o=i.dom_event_allowlist;if(o&&!o.some(t=>n.type===t))return{capture:!1,reason:"dom_event_not_allowed"}}for(var a=!1,l=[e],u=!0,h=e;h.parentNode&&!mh(h,"body");)if(bh(h.parentNode))l.push(h.parentNode.host),h=h.parentNode.host;else{if(!(u=Th(h)))break;if(r||hh.indexOf(u.tagName.toLowerCase())>-1)a=!0;else{var d=t.getComputedStyle(u);d&&"pointer"===d.getPropertyValue("cursor")&&(a=!0)}l.push(u),h=u}if(!function(t,e){var n=null==e?void 0:e.element_allowlist;if(p(n))return!0;var i,r=function(t){if(n.some(e=>t.tagName.toLowerCase()===e))return{v:!0}};for(var s of t)if(i=r(s))return i.v;return!1}(l,i))return{capture:!1,reason:"element_allowlist_miss"};if(!function(t,e){var n=null==e?void 0:e.css_selector_allowlist;if(p(n))return!0;var i,r=function(t){if(n.some(e=>t.matches(e)))return{v:!0}};for(var s of t)if(i=r(s))return i.v;return!1}(l,i))return{capture:!1,reason:"css_selector_allowlist_miss"};if(function(t,e){var n=null==e?void 0:e.css_selector_ignorelist,i=void 0===n?ch:n;if(0===i.length)return!1;for(var r of t)for(var s of i)try{if(r.matches(s))return!0}catch(t){}return!1}(l,i))return{capture:!1,reason:"css_selector_ignorelist_hit"};var c=t.getComputedStyle(e);if(c&&"pointer"===c.getPropertyValue("cursor")&&"click"===n.type)return{capture:!0};var v=e.tagName.toLowerCase();switch(v){case"html":return{capture:!1,reason:"tag_html"};case"form":return(s||["submit"]).indexOf(n.type)>=0?{capture:!0}:{capture:!1,reason:"form_event_not_allowed"};case"input":case"select":case"textarea":return(s||["change","click"]).indexOf(n.type)>=0?{capture:!0}:{capture:!1,reason:"input_event_not_allowed"};default:return a?(s||["click"]).indexOf(n.type)>=0?{capture:!0}:{capture:!1,reason:"dom_event_not_allowed"}:(s||["click"]).indexOf(n.type)>=0&&(hh.indexOf(v)>-1||"true"===e.getAttribute("contenteditable"))?{capture:!0}:{capture:!1,reason:"tag_not_capturable"}}}function $h(t,e){return e.length>t?e.slice(0,t)+"...":e}function zh(t,e,n,i){var r=t.tagName.toLowerCase(),s={tag_name:r};hh.indexOf(r)>-1&&!n&&(s.$el_text=$h(1024,"a"===r||"button"===r?Sh(t):_h(t)));var o=wh(t);o.length>0&&(s.classes=o.filter(t=>""!==t));for(var a=0;a<t.attributes.length;a++){var l=t.attributes[a];if((!Bh(t)||-1!==["name","id","class","aria-label"].indexOf(l.name))&&(!(null==i?void 0:i.includes(l.name))&&!e&&Dh(l.value)&&!Uh(l.name))){var u=l.value;"class"===l.name&&(u=yh(u).join(" ")),s["attr__"+l.name]=$h(1024,u)}}for(var h=1,d=1,c=t;c=Ch(c);)h++,c.tagName===t.tagName&&d++;return s.nth_child=h,s.nth_of_type=d,s}function qh(t){if(!jh(t))return{};for(var e={},n=0;n<t.attributes.length;n++){var i=t.attributes[n];if(i.name&&0===i.name.indexOf("data-vt-capture-attribute")){var r=i.name.replace("data-vt-capture-attribute-",""),s=i.value;r&&s&&Dh(s)&&(e[r]=s)}}return e}function Fh(t){return t.replace(/"|\\"/g,'\\"')}function Hh(t){var e=t.attr__class;return e?m(e)?e:yh(e):void 0}function Wh(t){return function(t){var e=t.map(t=>{var e,n,i="";if(t.tag_name&&(i+=t.tag_name),t.attr_class)for(var r of(t.attr_class.sort(),t.attr_class))i+="."+r.replace(/"/g,"");var s=h({},t.text?{text:t.text}:{},{"nth-child":null!==(e=t.nth_child)&&void 0!==e?e:0,"nth-of-type":null!==(n=t.nth_of_type)&&void 0!==n?n:0},t.href?{href:t.href}:{},t.attr_id?{attr_id:t.attr_id}:{},t.attributes),o={};return Object.entries(s).sort((t,e)=>{var[n]=t,[i]=e;return n.localeCompare(i)}).forEach(t=>{var[e,n]=t;return o[Fh(e.toString())]=Fh(String(n))}),(i+=":")+Object.entries(o).map(t=>{var[e,n]=t;return e+'="'+n+'"'}).join("")});return e.join(";")}(function(t){return t.map(t=>{var e,n,i={text:null===(e=t.$el_text)||void 0===e?void 0:e.slice(0,400),tag_name:t.tag_name,href:null===(n=t.attr__href)||void 0===n?void 0:n.slice(0,2048),attr_class:Hh(t),attr_id:t.attr__id,nth_child:t.nth_child,nth_of_type:t.nth_of_type,attributes:{}};return Object.entries(t).filter(t=>{var[e]=t;return 0===e.indexOf("attr__")}).forEach(t=>{var[e,n]=t;return i.attributes[e]=n}),i})}(t))}var Jh=[25,50,75,100];function Vh(t){var e;if(!t)return null;var n=t.milestones,i=!0===n||"object"==typeof n&&null!==n,r="object"==typeof n&&null!==n&&(null===(e=n.thresholds)||void 0===e?void 0:e.length)?[...n.thresholds].sort((t,e)=>t-e):[...Jh],s=!0===t.pageleave;return i||s?{milestones:i,thresholds:r,pageleave:s,scroll_root_selector:t.scroll_root_selector}:null}class Kh{constructor(t){this.Pn=t,this.Rn=0,this.Dn=new Set,this.Un=null,this.jn=null,this.Bn=null,this.Nn=null}start(){this.stop(),this.jn=function(e){if(!t)return null;if(e){var n=Array.isArray(e)?e:[e];for(var r of n){var s=null==i?void 0:i.querySelector(r);if(s instanceof Element)return s}}return t}(this.Pn.scroll_root_selector),this.jn&&(this.Un=()=>this.Ln(),G(this.jn,"scroll",this.Un,{passive:!0}),this.$n(),this.Nn=this.Pn.onPageview(()=>this.reset()))}stop(){this.Nn&&(this.Nn(),this.Nn=null),null!=this.Bn&&t&&(t.cancelAnimationFrame(this.Bn),this.Bn=null),this.Un&&this.jn&&(this.jn.removeEventListener("scroll",this.Un,{passive:!0}),this.Un=null,this.jn=null)}reset(){this.Rn=0,this.Dn.clear(),this.$n()}getMaxPct(){return this.Rn}Ln(){t&&null==this.Bn&&(this.Bn=t.requestAnimationFrame(()=>{this.Bn=null,this.$n()}))}$n(){if(this.jn){var e=function(e){var n,r,s,o,a,l;if(!e)return 0;if(e===t){var u=null!==(n=t.scrollY)&&void 0!==n?n:0,h=null!==(r=t.innerHeight)&&void 0!==r?r:0,d=null==i?void 0:i.documentElement,c=null==i?void 0:i.body,v=Math.max(null!==(s=null==d?void 0:d.scrollHeight)&&void 0!==s?s:0,null!==(o=null==c?void 0:c.scrollHeight)&&void 0!==o?o:0,null!==(a=null==d?void 0:d.offsetHeight)&&void 0!==a?a:0,null!==(l=null==c?void 0:c.offsetHeight)&&void 0!==l?l:0)-h;return v<=0?100:Math.round(Math.min(100,u/v*100))}var f=e,p=f.scrollHeight-f.clientHeight;return p<=0?100:Math.round(Math.min(100,f.scrollTop/p*100))}(this.jn);if(e>this.Rn&&(this.Rn=e),this.Pn.milestones&&this.Pn.isUrlAllowed())for(var n of this.Pn.thresholds)this.Rn>=n&&!this.Dn.has(n)&&(this.Dn.add(n),this.Pn.capture(cl,{[xl]:n,[_l]:this.Rn}))}}}function Gh(t,e){return t.indexOf(e)>-1}class Xh{constructor(){this.clicks=[],this.RAGE_CLICK_THRESHOLD_PX=30,this.RAGE_CLICK_TIMEOUT_MS=1e3,this.RAGE_CLICK_CLICK_COUNT=3}isRageClick(t,e,n){if(this.clicks=this.clicks.filter(t=>n-t.timestamp<this.RAGE_CLICK_TIMEOUT_MS),this.clicks.length>0){var i=this.clicks[this.clicks.length-1];Math.sqrt(Math.pow(t-i.x,2)+Math.pow(e-i.y,2))>this.RAGE_CLICK_THRESHOLD_PX&&(this.clicks=[])}return this.clicks.push({x:t,y:e,timestamp:n}),this.clicks.length>=this.RAGE_CLICK_CLICK_COUNT}}function Qh(e,n){for(var i,r,s,o,{e:a,maskAllElementAttributes:l,maskAllText:u,elementAttributeIgnoreList:h,elementsChainAsString:d,captureElementValues:c}=n,v=[e],f=e;f.parentNode&&!mh(f,"body");)bh(f.parentNode)?(v.push(f.parentNode.host),f=f.parentNode.host):(v.push(f.parentNode),f=f.parentNode);var p,g=[],m={},b=!1,y=!1;for(var w of v){var x=jh(w);if("a"===w.tagName.toLowerCase()){var _=w.getAttribute("href");b=!!(x&&_&&Dh(_))&&_}Gh(wh(w),"vt-no-capture")&&(y=!0),g.push(zh(w,l,u,h));var k=qh(w);Object.assign(m,k)}if(y)return{props:{},explicitNoCapture:y};if(u||("a"===e.tagName.toLowerCase()||"button"===e.tagName.toLowerCase()?g[0].$el_text=Sh(e):g[0].$el_text=_h(e)),"change"===a.type&&c){var S=Nh(e);S&&(S.$el_value&&(g[0].$el_value=S.$el_value),S.$selected_text&&(g[0].$selected_text=S.$selected_text))}if(b){g[0].attr__href=b;var C=null===(i=Pl(b))||void 0===i?void 0:i.host,T=null===(r=null==t?void 0:t.location)||void 0===r?void 0:r.host;C&&T&&C!==T&&(p=b)}var A=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return Object.assign({},...e)}({$event_type:a.type,$ce_version:1},d?{}:{$elements:g},{$elements_chain:Wh(g)},(null===(s=g[0])||void 0===s?void 0:s.$el_text)?{$el_text:null===(o=g[0])||void 0===o?void 0:o.$el_text}:{},p&&"click"===a.type?{$external_click_url:p}:{},m);return{props:A}}var Zh=["copy","cut"];class Yh{static extractConfig(t){return{enabled:!1!==t.autocapture}}constructor(t,e){this.name="Autocapture",this.zn=!1,this.qn=null,this.Fn=null,this.Hn=null,this.Wn=new Xh,this.Jn=!0,this.Vn=null,this.Kn=null,this.Gn=null,this.Xn=null,this.Qn=!1,this.Zn=null,this.Yn=null,this._instance=t}get ae(){var t=this._instance.getConfig().autocapture;if(t===this.Kn&&this.Vn)return this.Vn;this.Kn=t;var e=function(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}(t)?t:{};return e.url_allowlist&&(e.url_allowlist=e.url_allowlist.map(t=>"string"==typeof t?new RegExp(t):t)),e.url_ignorelist&&(e.url_ignorelist=e.url_ignorelist.map(t=>"string"==typeof t?new RegExp(t):t)),this.Vn=e,e}get isEnabled(){return this.ti().enabled}get isStarted(){return this.zn}startIfEnabled(){var{enabled:t,reason:e}=this.ti();t?this.zn?(this.ei(),this.ni()):(this.ii(),this.zn=!0,A().info("autocapture","started; listening for click/change/submit events")):this.zn?(A().info("autocapture","stopping; reason:",null!=e?e:"unknown"),this.ri(),this.zn=!1):(A().debug("autocapture","not started; reason:",null!=e?e:"unknown"),this.si())}stop(){this.zn&&(this.ri(),this.zn=!1,A().info("autocapture","stopped (DOM listeners detached)")),this.si()}getMaxScrollDepthPctForPageleave(){var t=Vh(this.ae.scroll_depth);return(null==t?void 0:t.pageleave)&&this.Zn?this.Zn.getMaxPct():null}onConfigUpdate(t){var e=t;"boolean"==typeof e.elementsChainAsString&&(this.Jn=e.elementsChainAsString),void 0!==e.autocapture_opt_out&&(this.qn=!!e.autocapture_opt_out),this.startIfEnabled()}updateConfig(t){void 0!==t.enabled&&(this.Fn=t.enabled,t.enabled&&(this.qn=!1),this.startIfEnabled())}getDiagnostics(){var t,e,n,{enabled:i,reason:r}=this.ti(),s=Vh(this.ae.scroll_depth);return{isEnabled:i,isStarted:this.zn,disabledReason:i?null:r,inputs:{configAutocapture:this._instance.getConfig().autocapture,isDisabledServerSide:null!==(t=this.qn)&&void 0!==t&&t,userOverride:this.Fn,elementsChainAsString:this.Jn,captureCopiedText:!!this.ae.capture_copied_text,scrollDepthMilestones:null!==(e=null==s?void 0:s.milestones)&&void 0!==e&&e,scrollDepthPageleave:null!==(n=null==s?void 0:s.pageleave)&&void 0!==n&&n,scrollDepthListenerAttached:null!==this.Zn}}}setElementSelectors(t){this.Hn=t}getElementSelectors(t){var e,n=[];return null===(e=this.Hn)||void 0===e||e.forEach(e=>{var r=null==i?void 0:i.querySelectorAll(e);null==r||r.forEach(i=>{t===i&&n.push(e)})}),n}ti(){if(!1===this.Fn)return{enabled:!1,reason:"user_stop_called"};if(this.qn)return{enabled:!1,reason:"server_opt_out"};if(!0===this.Fn)return{enabled:!0,reason:null};var t=this._instance.getConfig().autocapture;return!1===t?{enabled:!1,reason:"config_autocapture_false"}:null==t?{enabled:!1,reason:"config_autocapture_undefined"}:{enabled:!0,reason:null}}ii(){this.oi()?t&&i&&(this.Gn=e=>{var n=e||(null==t?void 0:t.event);if(n)try{this.ai(n)}catch(t){A().error("autocapture","capture handler threw",t)}},G(i,"submit",this.Gn,{capture:!0}),G(i,"change",this.Gn,{capture:!0}),G(i,"click",this.Gn,{capture:!0}),this.ei(),this.ni()):A().warn("autocapture","browser unsupported (no querySelectorAll)")}ri(){i&&(this.Gn&&(i.removeEventListener("submit",this.Gn,!0),i.removeEventListener("change",this.Gn,!0),i.removeEventListener("click",this.Gn,!0),this.Gn=null),this.Xn&&this.Qn&&(i.removeEventListener("copy",this.Xn,!0),i.removeEventListener("cut",this.Xn,!0),this.Qn=!1,this.Xn=null),this.si())}ni(){var e,n=Vh(this.ae.scroll_depth),i=this.isEnabled&&null!==n&&null!==Vh(null==(e=this.ae)?void 0:e.scroll_depth);i&&!this.Zn?(this.Zn=new Kh({milestones:n.milestones,pageleave:n.pageleave,thresholds:n.thresholds,scroll_root_selector:n.scroll_root_selector,capture:(t,e)=>this._instance.capture(t,e),isUrlAllowed:()=>{return e=this.ae,!(!t||(null==e?void 0:e.url_allowlist)&&!Ah(e.url_allowlist)||(null==e?void 0:e.url_ignorelist)&&Ah(e.url_ignorelist));var e},onPageview:t=>(this.Yn&&this.Yn(),this.Yn=this._instance.on(U,e=>{(null==e?void 0:e.event)===sl&&t()}),()=>{var t;null===(t=this.Yn)||void 0===t||t.call(this),this.Yn=null})}),this.Zn.start(),A().info("autocapture","scroll depth tracking started",{milestones:n.milestones,pageleave:n.pageleave})):i||this.si()}si(){this.Zn&&(this.Zn.stop(),this.Zn=null,A().info("autocapture","scroll depth tracking stopped")),this.Yn&&(this.Yn(),this.Yn=null)}ei(){if(i){var e=!!this.ae.capture_copied_text;e&&!this.Qn?(this.Xn=e=>{var n=e||(null==t?void 0:t.event);if(n)try{this.ai(n,dh)}catch(t){A().error("autocapture","copy handler threw",t)}},G(i,"copy",this.Xn,{capture:!0}),G(i,"cut",this.Xn,{capture:!0}),this.Qn=!0):!e&&this.Qn&&this.Xn&&(i.removeEventListener("copy",this.Xn,!0),i.removeEventListener("cut",this.Xn,!0),this.Qn=!1,this.Xn=null)}}ai(e,n){var i,r,s,o,a,l,u,h;if(void 0===n&&(n="$autocapture"),this.isEnabled)if(e.isTrusted){var d=function(t){var e;return p(t.target)?t.srcElement||null:(null===(e=t.target)||void 0===e?void 0:e.shadowRoot)?t.composedPath()[0]||null:t.target||null}(e);if(gh(d)&&(d=d.parentNode||null),"$autocapture"===n&&"click"===e.type&&e instanceof MouseEvent)this._instance.getConfig().rageclick&&(null===(i=this.Wn)||void 0===i?void 0:i.isRageClick(e.clientX,e.clientY,(new Date).getTime()))&&(A().info("autocapture","$rageclick detected"),this.ai(e,"$rageclick"));var c=n===dh;if(d){var v=Lh(d,e,this.ae,c,c?[...Zh]:void 0);if(v.capture){var f=this._instance.getConfig(),{props:g,explicitNoCapture:m}=Qh(d,{e:e,maskAllElementAttributes:null!==(o=f.mask_all_element_attributes)&&void 0!==o&&o,maskAllText:null!==(a=f.mask_all_text)&&void 0!==a&&a,elementAttributeIgnoreList:this.ae.element_attribute_ignorelist,elementsChainAsString:this.Jn,captureElementValues:null!==(l=this.ae.capture_element_values)&&void 0!==l&&l});if(m)return A().debug("autocapture","skip: vt-no-capture class on element chain",{tag:null===(u=d.tagName)||void 0===u?void 0:u.toLowerCase()}),!1;var b=this.getElementSelectors(d);if(b&&b.length>0&&(g.$element_selectors=b),n===dh){var y=xh(null===(h=null==t?void 0:t.getSelection())||void 0===h?void 0:h.toString()),w=e.type||"clipboard";if(!y)return A().debug("autocapture","skip copy: empty selection"),!1;g.$selected_content=y,g.$copy_type=w}return this._instance.capture(n,g),!0}A().debug("autocapture","skip:",null!==(r=v.reason)&&void 0!==r?r:"unknown",{type:e.type,tag:null===(s=d.tagName)||void 0===s?void 0:s.toLowerCase()})}else A().debug("autocapture","skip: no event target",{type:e.type})}else A().debug("autocapture","skip: synthetic event (isTrusted=false)",{type:e.type})}oi(){return b(null==i?void 0:i.querySelectorAll)}}var td="replay";class ed extends rh{constructor(t,e){super(t,e||ed.extractConfig(t.getConfig())),this.name="SessionRecording",this.scriptName="recorder"}static extractConfig(t){var e,n,i,r=t.session_recording||{};return{enabled:null!==(e=r.enabled)&&void 0!==e&&e,sampleRate:r.sampleRate,minimumDurationMs:r.minimumDurationMs,sessionIdleThresholdMs:r.sessionIdleThresholdMs,fullSnapshotIntervalMs:r.fullSnapshotIntervalMs,captureConsole:null!==(n=r.captureConsole)&&void 0!==n&&n,captureNetwork:null!==(i=r.captureNetwork)&&void 0!==i&&i,captureCanvas:r.captureCanvas,blockClass:r.blockClass,blockSelector:r.blockSelector,skipDefaultInvisibleBlocking:r.skipDefaultInvisibleBlocking,ignoreClass:r.ignoreClass,maskTextClass:r.maskTextClass,maskTextSelector:r.maskTextSelector,maskAllInputs:r.maskAllInputs,maskInputOptions:r.maskInputOptions,masking:r.masking,recordHeaders:r.recordHeaders,recordBody:r.recordBody,compressEvents:r.compressEvents,__mutationThrottlerRefillRate:r.__mutationThrottlerRefillRate,__mutationThrottlerBucketSize:r.__mutationThrottlerBucketSize}}get isEnabled(){var e,n=this._instance.getConfig(),i=null!==(e=this.ae.enabled)&&void 0!==e&&e,r=!n.disable_session_recording;return!!t&&i&&r}get isStarted(){var t;return this.Ye&&!!(null===(t=this.sn)||void 0===t?void 0:t.isStarted)}startIfEnabled(){this.startIfEnabledOrStop("recording_initialized")}startIfEnabledOrStop(t){var e;if(!this.isEnabled||!(null===(e=this.sn)||void 0===e?void 0:e.isStarted)){var n=void 0!==Object.assign&&void 0!==Array.from;this.isEnabled&&n?(this.Ye=!0,this.an(e=>this.un(e,t)),A().info(td,"starting")):this.stop()}}stop(){I(()=>{var t;null===(t=this.sn)||void 0===t||t.stop(),this.Ye=!1})}onConfigUpdate(t){var e;this.ae=ed.extractConfig(t),null===(e=this.sn)||void 0===e||e.updateConfig(this.ae),this.startIfEnabledOrStop("config_updated")}ln(){var t,e=null===(t=a.__VTiltExtensions__)||void 0===t?void 0:t.initSessionRecording;if(!e)throw new Error("[vTilt:replay] initSessionRecording not available after script load");return e(this._instance,this.ae)}un(t,e){t.start(e)}get started(){return this.isStarted}get status(){var t;return(null===(t=this.sn)||void 0===t?void 0:t.status)||"lazy_loading"}get sessionId(){var t;return(null===(t=this.sn)||void 0===t?void 0:t.sessionId)||""}stopRecording(){this.stop()}log(t,e){var n;void 0===e&&(e="log"),(null===(n=this.sn)||void 0===n?void 0:n.log)?this.sn.log(t,e):A().warn(td,"log called before recorder was ready")}updateConfig(t){var e;this.ae=h({},this.ae,t),null===(e=this.sn)||void 0===e||e.updateConfig(this.ae)}}var nd=(t=>(t[t.Mutation=0]="Mutation",t[t.MouseMove=1]="MouseMove",t[t.MouseInteraction=2]="MouseInteraction",t[t.Scroll=3]="Scroll",t[t.ViewportResize=4]="ViewportResize",t[t.Input=5]="Input",t[t.TouchMove=6]="TouchMove",t[t.MediaInteraction=7]="MediaInteraction",t[t.StyleSheetRule=8]="StyleSheetRule",t[t.CanvasMutation=9]="CanvasMutation",t[t.Font=10]="Font",t[t.Log=11]="Log",t[t.Drag=12]="Drag",t[t.StyleDeclaration=13]="StyleDeclaration",t[t.Selection=14]="Selection",t[t.AdoptedStyleSheet=15]="AdoptedStyleSheet",t[t.CustomElement=16]="CustomElement",t))(nd||{});nd.MouseMove,nd.MouseInteraction,nd.Scroll,nd.ViewportResize,nd.Input,nd.TouchMove,nd.MediaInteraction,nd.Drag;var id=Uint8Array,rd=Uint16Array,sd=Int32Array,od=new id([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ad=new id([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ld=new id([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ud=function(t,e){for(var n=new rd(31),i=0;i<31;++i)n[i]=e+=1<<t[i-1];var r=new sd(n[30]);for(i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)r[s]=s-n[i]<<5|i;return{b:n,r:r}},hd=ud(od,2),dd=hd.b,cd=hd.r;dd[28]=258,cd[258]=28;for(var vd=ud(ad,0).r,fd=new rd(32768),pd=0;pd<32768;++pd){var gd=(43690&pd)>>1|(21845&pd)<<1;gd=(61680&(gd=(52428&gd)>>2|(13107&gd)<<2))>>4|(3855&gd)<<4,fd[pd]=((65280&gd)>>8|(255&gd)<<8)>>1}var md=function(t,e,n){for(var i=t.length,r=0,s=new rd(e);r<i;++r)t[r]&&++s[t[r]-1];var o,a=new rd(e);for(r=1;r<e;++r)a[r]=a[r-1]+s[r-1]<<1;if(n){o=new rd(1<<e);var l=15-e;for(r=0;r<i;++r)if(t[r])for(var u=r<<4|t[r],h=e-t[r],d=a[t[r]-1]++<<h,c=d|(1<<h)-1;d<=c;++d)o[fd[d]>>l]=u}else for(o=new rd(i),r=0;r<i;++r)t[r]&&(o[r]=fd[a[t[r]-1]++]>>15-t[r]);return o},bd=new id(288);for(pd=0;pd<144;++pd)bd[pd]=8;for(pd=144;pd<256;++pd)bd[pd]=9;for(pd=256;pd<280;++pd)bd[pd]=7;for(pd=280;pd<288;++pd)bd[pd]=8;var yd=new id(32);for(pd=0;pd<32;++pd)yd[pd]=5;var wd=md(bd,9,0),xd=md(yd,5,0),_d=function(t){return(t+7)/8|0},kd=function(t,e,n){return(null==n||n>t.length)&&(n=t.length),new id(t.subarray(e,n))},Sd=function(t,e,n){n<<=7&e;var i=e/8|0;t[i]|=n,t[i+1]|=n>>8},Cd=function(t,e,n){n<<=7&e;var i=e/8|0;t[i]|=n,t[i+1]|=n>>8,t[i+2]|=n>>16},Td=function(t,e){for(var n=[],i=0;i<t.length;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return{t:Rd,l:0};if(1==r){var o=new id(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(t,e){return t.f-e.f}),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,h=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};h!=r-1;)a=n[n[u].f<n[d].f?u++:d++],l=n[u!=h&&n[u].f<n[d].f?u++:d++],n[h++]={s:-1,f:a.f+l.f,l:a,r:l};var c=s[0].s;for(i=1;i<r;++i)s[i].s>c&&(c=s[i].s);var v=new rd(c+1),f=Ad(n[h-1],v,0);if(f>e){i=0;var p=0,g=f-e,m=1<<g;for(s.sort(function(t,e){return v[e.s]-v[t.s]||t.f-e.f});i<r;++i){var b=s[i].s;if(!(v[b]>e))break;p+=m-(1<<f-v[b]),v[b]=e}for(p>>=g;p>0;){var y=s[i].s;v[y]<e?p-=1<<e-v[y]++-1:++i}for(;i>=0&&p;--i){var w=s[i].s;v[w]==e&&(--v[w],++p)}f=e}return{t:new id(v),l:f}},Ad=function(t,e,n){return-1==t.s?Math.max(Ad(t.l,e,n+1),Ad(t.r,e,n+1)):e[t.s]=n},Ed=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new rd(++e),i=0,r=t[0],s=1,o=function(t){n[i++]=t},a=1;a<=e;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return{c:n.subarray(0,i),n:e}},Id=function(t,e){for(var n=0,i=0;i<e.length;++i)n+=t[i]*e[i];return n},Md=function(t,e,n){var i=n.length,r=_d(e+2);t[r]=255&i,t[r+1]=i>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;s<i;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Od=function(t,e,n,i,r,s,o,a,l,u,h){Sd(e,h++,n),++r[256];for(var d=Td(r,15),c=d.t,v=d.l,f=Td(s,15),p=f.t,g=f.l,m=Ed(c),b=m.c,y=m.n,w=Ed(p),x=w.c,_=w.n,k=new rd(19),S=0;S<b.length;++S)++k[31&b[S]];for(S=0;S<x.length;++S)++k[31&x[S]];for(var C=Td(k,7),T=C.t,A=C.l,E=19;E>4&&!T[ld[E-1]];--E);var I,M,O,P,R=u+5<<3,D=Id(r,bd)+Id(s,yd)+o,U=Id(r,c)+Id(s,p)+o+14+3*E+Id(k,T)+2*k[16]+3*k[17]+7*k[18];if(l>=0&&R<=D&&R<=U)return Md(e,h,t.subarray(l,l+u));if(Sd(e,h,1+(U<D)),h+=2,U<D){I=md(c,v,0),M=c,O=md(p,g,0),P=p;var j=md(T,A,0);Sd(e,h,y-257),Sd(e,h+5,_-1),Sd(e,h+10,E-4),h+=14;for(S=0;S<E;++S)Sd(e,h+3*S,T[ld[S]]);h+=3*E;for(var B=[b,x],N=0;N<2;++N){var L=B[N];for(S=0;S<L.length;++S){var z=31&L[S];Sd(e,h,j[z]),h+=T[z],z>15&&(Sd(e,h,L[S]>>5&127),h+=L[S]>>12)}}}else I=wd,M=bd,O=xd,P=yd;for(S=0;S<a;++S){var q=i[S];if(q>255){Cd(e,h,I[(z=q>>18&31)+257]),h+=M[z+257],z>7&&(Sd(e,h,q>>23&31),h+=od[z]);var F=31&q;Cd(e,h,O[F]),h+=P[F],F>3&&(Cd(e,h,q>>5&8191),h+=ad[F])}else Cd(e,h,I[q]),h+=M[q]}return Cd(e,h,I[256]),h+M[256]},Pd=new sd([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Rd=new id(0),Dd=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var n=e,i=9;--i;)n=(1&n&&-306674912)^n>>>1;t[e]=n}return t}(),Ud=function(t,e,n,i,r){if(!r&&(r={l:1},e.dictionary)){var s=e.dictionary.subarray(-32768),o=new id(s.length+t.length);o.set(s),o.set(t,s.length),t=o,r.w=s.length}return function(t,e,n,i,r,s){var o=s.z||t.length,a=new id(i+o+5*(1+Math.ceil(o/7e3))+r),l=a.subarray(i,a.length-r),u=s.l,h=7&(s.r||0);if(e){h&&(l[0]=s.r>>3);for(var d=Pd[e-1],c=d>>13,v=8191&d,f=(1<<n)-1,p=s.p||new rd(32768),g=s.h||new rd(f+1),m=Math.ceil(n/3),b=2*m,y=function(e){return(t[e]^t[e+1]<<m^t[e+2]<<b)&f},w=new sd(25e3),x=new rd(288),_=new rd(32),k=0,S=0,C=s.i||0,T=0,A=s.w||0,E=0;C+2<o;++C){var I=y(C),M=32767&C,O=g[I];if(p[M]=O,g[I]=M,A<=C){var P=o-C;if((k>7e3||T>24576)&&(P>423||!u)){h=Od(t,l,0,w,x,_,S,T,E,C-E,h),T=k=S=0,E=C;for(var R=0;R<286;++R)x[R]=0;for(R=0;R<30;++R)_[R]=0}var D=2,U=0,j=v,B=M-O&32767;if(P>2&&I==y(C-B))for(var N=Math.min(c,P)-1,L=Math.min(32767,C),z=Math.min(258,P);B<=L&&--j&&M!=O;){if(t[C+D]==t[C+D-B]){for(var q=0;q<z&&t[C+q]==t[C+q-B];++q);if(q>D){if(D=q,U=B,q>N)break;var F=Math.min(B,q-2),H=0;for(R=0;R<F;++R){var W=C-B+R&32767,J=W-p[W]&32767;J>H&&(H=J,O=W)}}}B+=(M=O)-(O=p[M])&32767}if(U){w[T++]=268435456|cd[D]<<18|vd[U];var V=31&cd[D],K=31&vd[U];S+=od[V]+ad[K],++x[257+V],++_[K],A=C+D,++k}else w[T++]=t[C],++x[t[C]]}}for(C=Math.max(C,A);C<o;++C)w[T++]=t[C],++x[t[C]];h=Od(t,l,u,w,x,_,S,T,E,C-E,h),u||(s.r=7&h|l[h/8|0]<<3,h-=7,s.h=g,s.p=p,s.i=C,s.w=A)}else{for(C=s.w||0;C<o+u;C+=65535){var G=C+65535;G>=o&&(l[h/8|0]=u,G=o),h=Md(l,h+1,t.subarray(C,G))}s.i=o}return kd(a,0,i+_d(h)+r)}(t,null==e.level?6:e.level,null==e.mem?r.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):20:12+e.mem,n,i,r)},jd=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function Bd(t,e){e||(e={});var n=function(){var t=-1;return{p:function(e){for(var n=t,i=0;i<e.length;++i)n=Dd[255&n^e[i]]^n>>>8;t=n},d:function(){return~t}}}(),i=t.length;n.p(t);var r=Ud(t,e,function(t){return 10+(t.filename?t.filename.length+1:0)}(e),8),s=r.length;return function(t,e){var n=e.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=e.level<2?4:9==e.level?2:0,t[9]=3,0!=e.mtime&&jd(t,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),n){t[3]=8;for(var i=0;i<=n.length;++i)t[i+10]=n.charCodeAt(i)}}(r,e),jd(r,s-8,n.d()),jd(r,s-4,i),r}var Nd="undefined"!=typeof TextEncoder&&new TextEncoder,Ld="undefined"!=typeof TextDecoder&&new TextDecoder;try{Ld.decode(Rd,{stream:!0})}catch(t){}var $d="chat";class zd extends ih{constructor(t,e){super(t,e||zd.extractConfig(t.getConfig())),this.name="Chat",this.scriptName="chat",this.li=null,this.ui=!1,this.hi=null,this.di=null,this.ci=[],this.fi=[],this.jt=[],this.Bt=[],this.Nt=[],this.oe=!1,this.pi=null,this.gi=()=>{if("visible"===document.visibilityState)return this.mi(),void this.bi();this.yi()}}static extractConfig(t){var e,n=t.chat||{};return{enabled:n.enabled,autoConfig:null===(e=n.autoConfig)||void 0===e||e,position:n.position,greeting:n.greeting,color:n.color,aiMode:n.aiMode,aiGreeting:n.aiGreeting,preload:n.preload,offlineMessage:n.offlineMessage,collectEmailOffline:n.collectEmailOffline,bubble:n.bubble}}get isEnabled(){var t;return!1!==this.ae.enabled&&(!0===this.ae.enabled||!this._instance.getConfig().disable_chat&&!0===(null===(t=this.li)||void 0===t?void 0:t.enabled))}startIfEnabled(){A().debug($d,"startIfEnabled"),this.wi().catch(t=>{A().error($d,"error starting:",t)})}stop(){this.destroy(),this.Ye=!1}onConfigUpdate(t){var e,n;this.ae=zd.extractConfig(t),this.xi()||this.ki(),this.sn&&(null===(n=(e=this.sn).updateConfig)||void 0===n||n.call(e,this.getMergedConfig()))}ln(){var e,n,i,r=null===(e=a.__VTiltExtensions__)||void 0===e?void 0:e.initChat;if(!r)throw new Error("[vTilt:chat] initChat not available after script load");var s=this.getMergedConfig(),o=r(this._instance,s);this.oe&&o.show(),this.jt.forEach(t=>o.onMessage(t)),this.Bt.forEach(t=>o.onTyping(t)),this.Nt.forEach(t=>o.onConnectionChange(t)),null===(n=this.di)||void 0===n||n.destroy(),this.di=null;var l=null===(i=null==t?void 0:t.document)||void 0===i?void 0:i.getElementById("vtilt-chat-bubble");return l&&!l.closest("#vtilt-chat-container")&&l.remove(),o}un(t){this.fi.forEach(t=>t()),this.fi=[],t.isOpen||(this.mi(),this.bi()),A().info($d,"loaded and ready")}wi(){var t=this;return u(function*(){var e,n;try{if(!1===t.ae.enabled)return void A().info($d,"disabled by code config");if(t._instance.getConfig().disable_chat)return void A().info($d,"disabled by disable_chat config");if(!1!==t.ae.autoConfig&&(yield t.Si()),!t.isEnabled)return void A().info($d,"not enabled (check dashboard settings)");A().debug($d,"startIfEnabled enabled"),t.Ye=!0,!0===t.ae.preload&&t.Ci();var i=t.getMergedConfig();(null===(e=t.li)||void 0===e?void 0:e.enabled)&&!1!==(null===(n=i.bubble)||void 0===n?void 0:n.visible)&&t.Ti(),A().info($d,"ready (lazy-load on demand)")}finally{t.dn()}})()}get isOpen(){var t,e;return null!==(e=null===(t=this.sn)||void 0===t?void 0:t.isOpen)&&void 0!==e&&e}get isConnected(){var t,e;return null!==(e=null===(t=this.sn)||void 0===t?void 0:t.isConnected)&&void 0!==e&&e}get isLoading(){var t,e;return this.tn||null!==(e=null===(t=this.sn)||void 0===t?void 0:t.isLoading)&&void 0!==e&&e}get unreadCount(){var t,e;return null!==(e=null===(t=this.sn)||void 0===t?void 0:t.unreadCount)&&void 0!==e?e:0}get channel(){var t,e;return null!==(e=null===(t=this.sn)||void 0===t?void 0:t.channel)&&void 0!==e?e:null}get channels(){var t,e;return null!==(e=null===(t=this.sn)||void 0===t?void 0:t.channels)&&void 0!==e?e:[]}get currentView(){var t,e;return null!==(e=null===(t=this.sn)||void 0===t?void 0:t.currentView)&&void 0!==e?e:"list"}open(){this.hn(()=>{this.yi(),this.Ai(()=>{var t;return null===(t=this.sn)||void 0===t?void 0:t.open()})})}close(){this.hn(()=>{this.sn?(this.sn.close(),this.mi(),this.bi()):this.Ai(()=>{var t;null===(t=this.sn)||void 0===t||t.close(),this.mi(),this.bi()})})}toggle(){this.hn(()=>{this.sn?this.sn.toggle():this.open()})}show(){this.hn(()=>{this.oe=!0,this.sn?this.sn.show():this.Ye&&this.Ti()})}hide(){this.hn(()=>{var e;if(this.oe=!1,this.sn)this.sn.hide();else{var n=null===(e=null==t?void 0:t.document)||void 0===e?void 0:e.getElementById("vtilt-chat-bubble");n&&(n.style.display="none")}})}getChannels(){this.hn(()=>{this.Ai(()=>{var t;return null===(t=this.sn)||void 0===t?void 0:t.getChannels()})})}selectChannel(t){this.hn(()=>{this.Ai(()=>{var e;return null===(e=this.sn)||void 0===e?void 0:e.selectChannel(t)})})}createChannel(){this.hn(()=>{this.Ai(()=>{var t;return null===(t=this.sn)||void 0===t?void 0:t.createChannel()})})}goToChannelList(){this.hn(()=>{this.sn?this.sn.goToChannelList():this.Ai(()=>{var t;return null===(t=this.sn)||void 0===t?void 0:t.goToChannelList()})})}sendMessage(t,e){return this.sn?this.sn.sendMessage(t,e):new Promise((n,i)=>{this.hn(()=>{this.sn?this.sn.sendMessage(t,e).then(n).catch(i):(this.ci.push({content:t,options:e,resolve:n,reject:i}),this.Ai(()=>{var t,e=this.ci;for(var n of(this.ci=[],e))null===(t=this.sn)||void 0===t||t.sendMessage(n.content,n.options).then(n.resolve).catch(n.reject)}))})})}markAsRead(){this.hn(()=>{this.sn?this.sn.markAsRead():this.Ai(()=>{var t;return null===(t=this.sn)||void 0===t?void 0:t.markAsRead()})})}registerWidget(t){this.hn(()=>{var e,n;this.sn?null===(n=(e=this.sn).registerWidget)||void 0===n||n.call(e,t):this.Ai(()=>{var e,n;null===(n=null===(e=this.sn)||void 0===e?void 0:e.registerWidget)||void 0===n||n.call(e,t)})})}onMessage(t){return this.jt.push(t),this.sn?this.sn.onMessage(t):()=>{var e=this.jt.indexOf(t);e>-1&&this.jt.splice(e,1)}}onTyping(t){return this.Bt.push(t),this.sn?this.sn.onTyping(t):()=>{var e=this.Bt.indexOf(t);e>-1&&this.Bt.splice(e,1)}}onConnectionChange(t){return this.Nt.push(t),this.sn?this.sn.onConnectionChange(t):()=>{var e=this.Nt.indexOf(t);e>-1&&this.Nt.splice(e,1)}}xi(){var t;return!0===(null===(t=this.getMergedConfig().bubble)||void 0===t?void 0:t.draggable)}getMergedConfig(){var t,e,n,i,r,s,o,a,l,u,h,d,c,v,f,p,g,m,b,y,w,x,_,k,S,C=this.li,T=this.ae;return{enabled:null!==(e=null!==(t=T.enabled)&&void 0!==t?t:null==C?void 0:C.enabled)&&void 0!==e&&e,autoConfig:null===(n=T.autoConfig)||void 0===n||n,position:null!==(r=null!==(i=T.position)&&void 0!==i?i:null==C?void 0:C.position)&&void 0!==r?r:"bottom-right",greeting:null!==(s=T.greeting)&&void 0!==s?s:null==C?void 0:C.greeting,color:null!==(a=null!==(o=T.color)&&void 0!==o?o:null==C?void 0:C.color)&&void 0!==a?a:"#6366f1",aiMode:null===(u=null!==(l=T.aiMode)&&void 0!==l?l:null==C?void 0:C.ai_enabled)||void 0===u||u,aiGreeting:null!==(h=T.aiGreeting)&&void 0!==h?h:null==C?void 0:C.ai_greeting,preload:null!==(d=T.preload)&&void 0!==d&&d,theme:null!==(c=T.theme)&&void 0!==c?c:{primaryColor:null!==(f=null!==(v=T.color)&&void 0!==v?v:null==C?void 0:C.color)&&void 0!==f?f:"#6366f1"},offlineMessage:null!==(p=T.offlineMessage)&&void 0!==p?p:null==C?void 0:C.offline_message,collectEmailOffline:null===(m=null!==(g=T.collectEmailOffline)&&void 0!==g?g:null==C?void 0:C.collect_email_offline)||void 0===m||m,bubble:{draggable:null!==(w=null!==(y=null===(b=T.bubble)||void 0===b?void 0:b.draggable)&&void 0!==y?y:null==C?void 0:C.bubble_draggable)&&void 0!==w&&w,visible:null===(k=null!==(_=null===(x=T.bubble)||void 0===x?void 0:x.visible)&&void 0!==_?_:null==C?void 0:C.bubble_visible)||void 0===k||k,offset:null===(S=T.bubble)||void 0===S?void 0:S.offset}}}ki(){var t,e,n=this.getMergedConfig(),i=null!==(t=n.position)&&void 0!==t?t:"bottom-right",r=kn(null===(e=n.bubble)||void 0===e?void 0:e.offset),s=document.getElementById("vtilt-chat-bubble");s&&Sn(s,i,r)}destroy(){I(()=>{var e,n,i;this.yi(),document.removeEventListener("visibilitychange",this.gi),null===(e=this.sn)||void 0===e||e.destroy(),this.sn=void 0,this.oe=!1,this.ci=[],this.fi=[],this.jt=[],this.Bt=[],this.Nt=[],this.cn(),null===(n=this.di)||void 0===n||n.destroy(),this.di=null;var r=null===(i=null==t?void 0:t.document)||void 0===i?void 0:i.getElementById("vtilt-chat-bubble");r&&r.remove()})}Si(){var t=this;return u(function*(){if(!t.ui){var e=t._instance.getConfig();if(!e.token)return A().warn($d,"cannot fetch settings: missing token"),void(t.ui=!0);try{var n=c(e,"/api/chat/settings"),i=yield fetch(n,{headers:v(e)});if(!i.ok)return A().warn($d,"failed to fetch settings: "+i.status),void(t.ui=!0);t.li=yield i.json(),t.ui=!0,A().info($d,"loaded settings from dashboard")}catch(e){A().warn($d,"error fetching settings:",e),t.ui=!0}}})()}mi(){var t=this;return u(function*(){var e,n,i,r,s,o,a=t._instance.getConfig(),l=a.token,u=null!==(i=null===(n=(e=t._instance).getDistinctId)||void 0===n?void 0:n.call(e))&&void 0!==i?i:"";if(A().debug("chat","fetchUnread","distinctId",u?u.slice(0,12)+"...":"empty"),l&&u)try{var h=c(a,"/api/chat/widget/unread"),d=h.includes("?")?"&":"?",f=""+h+d+"distinct_id="+encodeURIComponent(u),p=yield fetch(f,{headers:v(a)});if(!p.ok)return;var g=yield p.json(),m=Number(null!==(r=g.unread_count)&&void 0!==r?r:0);null===(o=null===(s=t.sn)||void 0===s?void 0:s.applyPolledUnreadCount)||void 0===o||o.call(s,m);var b=document.getElementById("vtilt-chat-bubble");if(!b)return;var y=b.querySelector(".vtilt-chat-bubble-badge");if(!y)return;m>0?(y.style.display="flex",y.textContent=m>99?"99+":String(m)):y.style.display="none"}catch(t){}else{var w=l?"missing distinctId":"missing token";A().debug("chat","fetchUnread skip","reason",w)}})()}Ti(){var e,n,i,r;if(null==t?void 0:t.document){var s=document.getElementById("vtilt-chat-bubble");if(s)return s.style.display="flex",void this.ki();var o=this.getMergedConfig(),a=null!==(e=o.position)&&void 0!==e?e:"bottom-right",l=kn(null===(n=o.bubble)||void 0===n?void 0:n.offset),u=o.color||"#6366f1",h=document.createElement("div");h.id="vtilt-chat-bubble",h.setAttribute("style",("\n position: fixed;\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background: "+u+";\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n transition: transform 0.2s, box-shadow 0.2s;\n z-index: 999999;\n ").trim()),Sn(h,a,l),h.innerHTML='\n <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">\n <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>\n </svg>\n <div class="vtilt-chat-bubble-badge" style="\n display: none;\n position: absolute;\n top: -4px;\n right: -4px;\n background: #E53935;\n color: white;\n font-size: 11px;\n font-weight: 700;\n min-width: 20px;\n height: 20px;\n border-radius: 10px;\n align-items: center;\n justify-content: center;\n padding: 0 6px;\n box-sizing: border-box;\n border: 2px solid white;\n ">0</div>\n ';var d=!0===(null===(i=o.bubble)||void 0===i?void 0:i.draggable);d||(h.addEventListener("mouseenter",()=>{h.style.transform="scale(1.05)",h.style.boxShadow="0 6px 16px rgba(0, 0, 0, 0.2)"}),h.addEventListener("mouseleave",()=>{h.style.transform="scale(1)",h.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.15)"})),h.addEventListener("click",()=>{this.open()}),document.body.appendChild(h),d&&(null===(r=this.di)||void 0===r||r.destroy(),this.di=In(h)),this.mi(),this.bi(),document.addEventListener("visibilitychange",this.gi)}}Ei(){return"undefined"!=typeof document&&("visible"===document.visibilityState&&(!!document.getElementById("vtilt-chat-bubble")||!(!this.sn||this.sn.isOpen)))}bi(){this.Ei()&&null===this.pi&&(this.pi=setInterval(()=>{this.mi()},3e4))}yi(){null!==this.pi&&(clearInterval(this.pi),this.pi=null)}Ci(){"undefined"!=typeof requestIdleCallback?requestIdleCallback(()=>this.an(()=>{}),{timeout:5e3}):setTimeout(()=>this.an(()=>{}),3e3)}Ai(t){this.sn?t():(this.fi.push(t),this.an(t=>this.un(t)))}}function qd(t,e){t("js",new Date);var{tagIds:n,configParams:i,sendPageView:r,debugMode:s,conversionLinker:o,linkerDomains:a}=e,l=h({},i||{});for(var u of(!1===r&&(l.send_page_view=!1),s&&(l.debug_mode=!0),!1===o&&(l.conversion_linker=!1),a&&a.length>0&&(l.linker={domains:a,decorate_forms:!0}),n))u&&t("config",u,l)}function Fd(e,n){var i,r=(e.tagIds||[]).filter(t=>!!t);if(0===r.length)return null;var s,o,a,l=null!==(i=e.proxyMode)&&void 0!==i?i:"proxied";if("direct"===l)s=Wd,o=Wd,a="";else{var u=function(e){var n,i=void 0!==t&&(null===(n=null==t?void 0:t.location)||void 0===n?void 0:n.origin)?t.location.origin:"";if(!e)return i?{base:i,absoluteBase:i}:null;var r=e.replace(/\/+$/g,"");if(!r)return i?{base:i,absoluteBase:i}:null;try{var s=new URL(r),o=s.pathname.replace(/\/$/,""),a=""+s.origin+o;return{base:a,absoluteBase:a}}catch(t){}if(r.startsWith("/"))return{base:r,absoluteBase:i?""+i+r:r};return i?{base:i,absoluteBase:i}:null}(n);if(!u)return null;s=u.base,o=u.absoluteBase,a=Hd}var h={};if("direct"!==l){var d=function(t){if(!t)return"";var e=t.startsWith("/")?t:"/"+t;return e.replace(/\/$/,"")}(a);h.transport_url=""+o.replace(/\/$/,"")+d}return{origin:s,gatewayPath:a,primaryTagId:r.find(t=>t.startsWith("G-"))||r[0]||"",tagIds:r,configParams:h,sendPageView:!1!==e.capturePageview,debugMode:!!e.debugMode,conversionLinker:!1!==e.conversionLinker,linkerDomains:e.linkerDomains}}var Hd="/gt",Wd="https://www.googletagmanager.com";function Jd(t,e){var n=!0===t.advertising,i={ad_storage:n?"granted":"denied",ad_user_data:n?"granted":"denied",ad_personalization:n?"granted":"denied",analytics_storage:!0===t.analytics?"granted":"denied"};if(!e)return i;var r=h({},i);return Object.keys(i).forEach(n=>{var i=e[n];void 0!==i&&(r[n]=function(t,e){return"granted"===e?"granted":"denied"===e?"denied":"follow_advertising"===e?!0===t.advertising?"granted":"denied":"follow_analytics"===e&&!0===t.analytics?"granted":"denied"}(t,i))}),r}function Vd(t){if(null==t)return null;var e=String(t).trim().toLowerCase();return e||null}function Kd(t,e){if(t&&e){var n=e.split("."),i=t;for(var r of n){if(null==i||"object"!=typeof i)return;i=i[r]}return i}}function Gd(t){if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t&&""!==t.trim()){var e=Number(t);if(Number.isFinite(e))return e}}function Xd(t){if(null!=t)return"string"==typeof t?t:"number"==typeof t||"boolean"==typeof t?String(t):void 0}function Qd(t){var{mapping:e,payload:n}=t,i={send_to:e.send_to},r=e.value_param_path||"value",s=e.currency_param_path||"currency",o=Gd(Kd(n,r));void 0!==o&&(i.value=o);var a=Xd(Kd(n,s))||e.default_currency||void 0;if(a&&(i.currency=a),!1!==e.send_transaction_id){var l=Xd(Kd(n,e.transaction_id_param_path||"transaction_id"));l&&(i.transaction_id=l)}return{send_to:e.send_to,params:i}}var Zd=[{source:"$pageview",destination:"page_view",buildParams:t=>{var e,n={},i=Xd(t.$current_url);i&&(n.page_location=i);var r=Xd(t.$pathname);r&&(n.page_path=r);var s=null!==(e=Xd(t.title))&&void 0!==e?e:Xd(t.$title);s&&(n.page_title=s);var o=Xd(t.$referrer);return o&&(n.page_referrer=o),n}},{source:"$pageleave",destination:"user_engagement",buildParams:t=>{var e,n,i={},r=Gd(null!==(n=null!==(e=t.$dwell_time_ms)&&void 0!==e?e:t.engagement_time_msec)&&void 0!==n?n:t.$time_on_page_ms);return void 0!==r&&(i.engagement_time_msec=Math.round(r)),i}}];function Yd(t,e,n){var i=e.split(".").filter(Boolean);if(0!==i.length)if(1!==i.length){for(var r=t,s=0;s<i.length-1;s++){var o=i[s],a=i[s+1];if(null==r||"object"!=typeof r||Array.isArray(r))return;var l=r;if(/^\d+$/.test(a)){var u=Array.isArray(l[o])?l[o]:[];Array.isArray(l[o])||(l[o]=u);for(var h=parseInt(a,10);u.length<=h;)u.push({});if(s+1===i.length-1)return void(u[h]=n);var d=u[h];d&&"object"==typeof d&&!Array.isArray(d)||(d={},u[h]=d),r=d,s++}else{var c=l[o];c&&"object"==typeof c&&!Array.isArray(c)||(c={},l[o]=c),r=c}}var v=i[i.length-1];r&&"object"==typeof r&&!Array.isArray(r)&&(r[v]=n)}else t[i[0]]=n}var tc=new Set(["client_id","user_id","first_visit","session_start"]);function ec(t,e,n,i){if(!function(t,e){return!(e&&(Array.isArray(e.exclude)&&e.exclude.includes(t)||Array.isArray(e.include)&&e.include.length>0&&!e.include.includes(t)))}(e,i.eventFilter))return{fired:!1};var r=(i.eventMappings||[]).find(t=>(null==t?void 0:t.source)===e);if(r&&r.destination){var{name:s,params:o}=function(t,e){var n={},i=Array.isArray(t.param_mappings)?t.param_mappings:[];for(var r of i){var s=null==r?void 0:r.source,o=null==r?void 0:r.destination;if(s&&o){var a=Kd(e,s);void 0!==a&&(o.includes(".")?Yd(n,o,a):n[o]=a)}}return{name:t.destination,params:n}}(r,n);return t("event",s,o),{fired:!0,eventName:s,params:o,source:"mapping"}}if(!1===i.autoForward)return{fired:!1};var a=Zd.find(t=>t.source===e);if(a){var l=a.buildParams(n);return t("event",a.destination,l),{fired:!0,eventName:a.destination,params:l,source:"preset"}}if(e.startsWith("$"))return{fired:!1};var u=function(t){var e={};for(var[n,i]of Object.entries(t))n.startsWith("$")||tc.has(n)||void 0!==i&&(e[n]=i);return e}(n);return t("event",e,u),{fired:!0,eventName:e,params:u,source:"auto"}}function nc(){var t=null,e=[],n=[];return{call:function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];if((t=>{n.push(t),n.length>50&&n.shift()})(r),t)try{t(...r)}catch(t){}else e.push(r)},flush(n){for(t=n;e.length;){var i=e.shift();try{n(...i)}catch(t){}}},getRecentCalls:()=>n.slice()}}function ic(t){return rc.apply(this,arguments)}function rc(){return rc=u(function*(t){try{var e="undefined"!=typeof crypto&&crypto.subtle?crypto.subtle:null;if(!e)return null;var n=(new TextEncoder).encode(t),i=yield e.digest("SHA-256",n),r=Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("");return r}catch(t){return null}}),rc.apply(this,arguments)}function sc(){return(sc=u(function*(t){var e={},n=function(t){if(!t)return null;var e=String(t).trim().toLowerCase();if(!e)return null;if(!e.includes("@"))return null;var[n,i]=e.split("@");if(!n||!i)return null;if("gmail.com"===i||"googlemail.com"===i){var r=n.split("+")[0].replace(/\./g,"");return r?r+"@"+i:null}return n+"@"+i}(t.email),i=function(t){if(!t)return null;var e=String(t).trim();if(!e)return null;if(e.startsWith("+")){var n=e.slice(1).replace(/\D/g,"");return n?"+"+n:null}return null}(t.phone),r=Vd(t.first_name),s=Vd(t.last_name),o=Vd(t.street),a=Vd(t.city),l=Vd(t.region),u=function(t){if(!t)return null;var e=String(t).trim().toUpperCase().replace(/\s+/g,"");return e||null}(t.postal_code),h=Vd(t.country);if(n){var d=yield ic(n);d&&(e.sha256_email_address=d)}if(i){var c=yield ic(i);c&&(e.sha256_phone_number=c)}var v={};if(r){var f=yield ic(r);f&&(v.sha256_first_name=f)}if(s){var p=yield ic(s);p&&(v.sha256_last_name=p)}if(o){var g=yield ic(o);g&&(v.sha256_street=g)}return a&&(v.city=a),l&&(v.region=l),u&&(v.postal_code=u),h&&(v.country=h),Object.keys(v).length>0&&(e.address=v),0===Object.keys(e).length?null:e})).apply(this,arguments)}class oc{constructor(t){void 0===t&&(t=Number.POSITIVE_INFINITY),this.Ii=t,this.Mi=[]}get length(){return this.Mi.length}enqueue(t){return!(this.Mi.length>=this.Ii)&&(this.Mi.push(t),!0)}takeAll(){if(0===this.Mi.length)return[];var t=this.Mi;return this.Mi=[],t}clear(){this.Mi=[]}}var ac="google-tag";class lc{constructor(t,e){this.name="GoogleTagGateway",this.Ye=!1,this.Oi=!1,this.Pi=!1,this.Ri=!1,this.Di=null,this.Ui=null,this.ji=null,this.Bi=null,this.Ni=[],this.Li=100,this.$i=new oc(100),this._instance=t,this.ae=e||lc.extractConfig(t.getConfig()),this.zi=nc(),this.qi()}static extractConfig(t){if(t.disable_google_tag)return{enabled:!1};var e=t.google_tag;return e?{enabled:(e.tagIds||[]).some(t=>!!t),remote:e}:{enabled:!1}}get isEnabled(){return!1!==this.ae.enabled&&!!this.ae.remote}get isStarted(){return this.Ye}get gtag(){return this.zi.call}get deliveryLog(){return this.Ni.slice()}startIfEnabled(){this.Ye||this.isEnabled&&this._instance.getConfig().__remote_config_loaded&&this.Tn()}stop(){var t;this.Ye&&(null===(t=this.Bi)||void 0===t||t.call(this),this.Bi=null,this.Ye=!1)}onConfigUpdate(t){var e=lc.extractConfig(t),n=this.isEnabled;this.ae=e;var i=!0===t.__remote_config_loaded;if(n&&!this.isEnabled)this.stop();else if(this.Ye&&e.remote&&this.Ui){var r=Fd(e.remote,this._instance.getConfig().api_host);r&&(this.Ui=r,qd(this.Di,r))}i&&!this.isEnabled&&this.$i.clear(),i&&this.isEnabled&&!this.Ye&&this.startIfEnabled()}setUserData(t){var e=this;return u(function*(){var n=e.ae.remote;if(n&&n.enhancedConversions){var i=yield function(t){return sc.apply(this,arguments)}(t);i&&e.zi.call("set","user_data",i)}})()}getRecentPublicCalls(){return this.zi.getRecentCalls()}Tn(){var e=this.ae.remote;if(e){var n=Fd(e,this._instance.getConfig().api_host);if(n){this.Ui=n;var{gtag:i}=function(){var t,e,n=a,i=null!==(t=(e=n).dataLayer)&&void 0!==t?t:e.dataLayer=[],r=n.gtag;if(r)return{gtag:r,dataLayer:i};var s=function(){i.push(arguments)};return n.gtag=s,{gtag:s,dataLayer:i}}();this.Di=i,this.zi.flush(i),this.Fi(),qd(i,n),this.Oi||(this.Oi=!0,function(e,n,i){var r=null==t?void 0:t.document;if(!r)return null;var{origin:s,gatewayPath:o,primaryTagId:a}=e;if(!s||!a)return null;var l=""+s.replace(/\/$/,"")+(o?o.startsWith("/")?o.replace(/\/$/,""):"/"+o.replace(/\/$/,""):"")+"/gtag/js?id="+encodeURIComponent(a)+"&l=dataLayer",u=r.querySelector('script[data-vtilt-gtag-loader="'+a+'"]');if(u)return u;var h=r.createElement("script");h.async=!0,h.src=l,h.setAttribute("data-vtilt-gtag-loader",a),h.onload=()=>null==n?void 0:n(),h.onerror=()=>{var t=new Error("[GoogleTagGateway] failed to load "+l);null==i||i(t)},(r.head||r.body||r.documentElement).appendChild(h)}(n,()=>{this.Pi=!0},t=>{A().warn(ac,t.message)})),this.Hi(),this.Ye=!0,this.Wi()}else A().warn(ac,"skipped — missing tag_ids or resolvable origin")}}Wi(){for(var t of this.$i.takeAll())this.Ji(t.event,t.payload)}Fi(){var t;if(!this.Ri&&this.Di){var e=I(()=>this._instance.consentManager.getConsent());!function(t,e,n){t("consent","default",h({},Jd(e,n),{wait_for_update:500}))}(this.Di,e||{},null===(t=this.ae.remote)||void 0===t?void 0:t.consentOverride),this.Ri=!0}}qi(){if(!this.ji){this.ji=this._instance._emitter.on(U,t=>{var e=t;e&&"string"==typeof e.event&&this.Ji(e.event,e.payload||{})})}}Ji(t,e){var n=this._instance.getConfig();if(!n.disable_google_tag)if(n.__remote_config_loaded){if(this.isEnabled&&(this.Ye||this.startIfEnabled(),this.Di&&this.ae.remote&&this.Ye)){var i=this.ae.remote,r=i.tagIds||[],s=ec(this.Di,t,e,i);if(s.fired&&s.eventName&&this.Vi({ts:Date.now(),tag_ids:r,event_name:t,send_to:"ga4:"+s.eventName,status:"fired",reason:s.source}),!1!==i.sendAdsConversions){var o=function(t,e,n,i){var r=(i.conversions||[]).filter(t=>t.event_name===e);if(0===r.length)return[];var s=[];for(var o of r){var a=Qd({mapping:o,payload:n});t("event","conversion",a.params),s.push(a)}return s}(this.Di,t,e,i);for(var a of o)this.Vi({ts:Date.now(),tag_ids:r,event_name:t,send_to:a.send_to,status:"fired"})}}}else this.$i.enqueue({event:t,payload:e})}Hi(){if(!this.Bi){this.Bi=this._instance._emitter.on(D,t=>{var e;if(this.Di){var n,i,r,s=t;n=this.Di,i=s.consent||{},r=null===(e=this.ae.remote)||void 0===e?void 0:e.consentOverride,n("consent","update",Jd(i,r))}})}}Vi(t){this.Ni.push(t),this.Ni.length>this.Li&&this.Ni.shift()}}var uc="vtd-overlay";class hc{constructor(t,e){this.name="VtdOverlay",this.Ye=!1,this.Ki=null,this.Gi=null,this.tn=!0,this.Xi=null,this.Qi=null,this.Zi=null,this._instance=t,this.ae=e||hc.extractConfig(t.getConfig())}static extractConfig(t){return{enabled:!1!==t.vtd_overlay}}get isEnabled(){return!1!==this.ae.enabled}get isStarted(){return this.Ye}startIfEnabled(){}stop(){this.Ye&&I(()=>{this.Yi(),this.Ye=!1})}onConfigUpdate(t){this.ae=hc.extractConfig(t),!this.isEnabled&&this.Ye&&this.stop()}setDestinationUrl(e){var n;if(this.isEnabled)if(null==e?void 0:e.trim()){var i=e;try{i=decodeURIComponent(e)}catch(t){i=e}if(this.tr(i)){var r=this.er(i);this.Gi=i,this.Ki=r,this.tn=!0,this.nr(),this.Ye=!0,this._instance.capture("$vtd_view",{$vtd_url:i,$vtd_embed_url:r!==i?r:void 0,$current_url:null===(n=null==t?void 0:t.location)||void 0===n?void 0:n.href})}else A().warn(uc,"invalid URL: "+i)}else A().warn(uc,"empty URL provided");else A().warn(uc,"feature is disabled")}getDestinationUrl(){return this.Ki}close(){this._instance.capture("$vtd_close",{$vtd_url:this.Gi}),this.Xi?(this.Xi.classList.add("vtilt-vtd-closing"),setTimeout(()=>{this.Yi(),this.Ye=!1,this.Ki=null,this.Gi=null},200)):(this.Yi(),this.Ye=!1,this.Ki=null,this.Gi=null)}tr(t){try{var e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol}catch(t){return!1}}er(t){try{var e=new URL(t),n=e.hostname.toLowerCase();if("youtube.com"===n||"www.youtube.com"===n||"m.youtube.com"===n){var i=e.searchParams.get("v");if(i){var r=e.searchParams.get("t"),s="https://www.youtube.com/embed/"+i+"?autoplay=1";return r&&(s+="&start="+r.replace("s","")),s}}if("youtu.be"===n){var o=e.pathname.slice(1);if(o){var a=e.searchParams.get("t"),l="https://www.youtube.com/embed/"+o+"?autoplay=1";return a&&(l+="&start="+a.replace("s","")),l}}if("vimeo.com"===n||"www.vimeo.com"===n){var u=e.pathname.match(/^\/(\d+)/);if(u)return"https://player.vimeo.com/video/"+u[1]+"?autoplay=1"}if("loom.com"===n||"www.loom.com"===n){var h=e.pathname.match(/^\/share\/([a-zA-Z0-9]+)/);if(h)return"https://www.loom.com/embed/"+h[1]+"?autoplay=1"}if(n.endsWith("wistia.com")){var d=e.pathname.match(/^\/medias\/([a-zA-Z0-9]+)/);if(d)return"https://fast.wistia.net/embed/iframe/"+d[1]+"?autoplay=1"}if("dailymotion.com"===n||"www.dailymotion.com"===n){var c=e.pathname.match(/^\/video\/([a-zA-Z0-9]+)/);if(c)return"https://www.dailymotion.com/embed/video/"+c[1]+"?autoplay=1"}if("open.spotify.com"===n){var v=e.pathname.match(/^\/(track|album|playlist|episode|show)\/([a-zA-Z0-9]+)/);if(v)return"https://open.spotify.com/embed/"+v[1]+"/"+v[2]}return"drive.google.com"===n&&e.pathname.includes("/view")?t.replace("/view","/preview"):t}catch(e){return t}}ir(t){try{return new URL(t).hostname}catch(e){return t}}rr(t){try{return"https://www.google.com/s2/favicons?domain="+new URL(t).hostname+"&sz=32"}catch(t){return""}}nr(){if(i&&this.Ki){this.Yi(),this.Xi=i.createElement("div"),this.Xi.id="vtilt-vtd-overlay",this.Xi.className="vtilt-vtd-opening",this.Xi.setAttribute("style",this.sr());var t=i.createElement("div");t.className="vtilt-vtd-modal",t.setAttribute("style",this.ar());var e=i.createElement("div");e.className="vtilt-vtd-header",e.setAttribute("style",this.lr()),e.innerHTML=this.ur(),t.appendChild(e);var n=i.createElement("div");n.className="vtilt-vtd-iframe-wrapper",n.setAttribute("style",this.hr()),this.Zi=i.createElement("div"),this.Zi.className="vtilt-vtd-loading",this.Zi.setAttribute("style",this.dr()),this.Zi.innerHTML=this.cr(),n.appendChild(this.Zi),this.Qi=i.createElement("iframe"),this.Qi.id="vtilt-vtd-iframe",this.Qi.className="vtilt-vtd-iframe",this.Qi.setAttribute("style",this.vr()),this.Qi.setAttribute("frameborder","0"),this.Qi.setAttribute("allowfullscreen","true"),this.Qi.setAttribute("allow","accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share");var r=()=>{this.tn=!1,this.Zi&&(this.Zi.style.opacity="0",setTimeout(()=>{var t;(null===(t=this.Zi)||void 0===t?void 0:t.parentNode)&&(this.Zi.style.display="none")},300)),this.Qi&&(this.Qi.style.opacity="1")};this.Qi.onload=r,this.Qi.onerror=r,setTimeout(()=>{this.tn&&r()},5e3),n.appendChild(this.Qi),this.Qi.src=this.Ki,t.appendChild(n),this.Xi.appendChild(t);var s=i.createElement("style");s.id="vtilt-vtd-styles",s.textContent=this.pr(),i.head.appendChild(s),i.body.appendChild(this.Xi),this.gr(),i.body.style.overflow="hidden"}}Yi(){var t;(null===(t=this.Xi)||void 0===t?void 0:t.parentNode)&&(this.Xi.parentNode.removeChild(this.Xi),this.Xi=null,this.Qi=null,this.Zi=null);var e=null==i?void 0:i.getElementById("vtilt-vtd-styles");(null==e?void 0:e.parentNode)&&e.parentNode.removeChild(e),(null==i?void 0:i.body)&&(i.body.style.overflow="")}gr(){var e,n,r,s=null===(e=this.Xi)||void 0===e?void 0:e.querySelector(".vtilt-vtd-close");null==s||s.addEventListener("click",()=>this.close());var o=null===(n=this.Xi)||void 0===n?void 0:n.querySelector(".vtilt-vtd-open");null==o||o.addEventListener("click",()=>{this.Gi&&(null==t||t.open(this.Gi,"_blank"))}),null===(r=this.Xi)||void 0===r||r.addEventListener("click",t=>{t.target===this.Xi&&this.close()});var a=t=>{"Escape"===t.key&&(this.close(),null==i||i.removeEventListener("keydown",a))};null==i||i.addEventListener("keydown",a)}sr(){return'\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2147483647;\n background: rgba(0, 0, 0, 0.85);\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 0;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n '}ar(){return"\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n background: #0a0a0a;\n overflow: hidden;\n "}lr(){return"\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0 16px;\n height: 56px;\n background: linear-gradient(180deg, rgba(20, 20, 20, 1) 0%, rgba(15, 15, 15, 1) 100%);\n border-bottom: 1px solid rgba(255, 255, 255, 0.08);\n flex-shrink: 0;\n gap: 16px;\n "}ur(){var t=this.Gi||this.Ki,e=t?this.ir(t):"";return'\n <div style="display: flex; align-items: center; gap: 12px; flex: 1; min-width: 0;">\n <img \n src="'+(t?this.rr(t):"")+'" \n alt="" \n style="width: 20px; height: 20px; border-radius: 4px; flex-shrink: 0;"\n onerror="this.style.display=\'none\'"\n />\n <div style="\n display: flex;\n flex-direction: column;\n min-width: 0;\n gap: 2px;\n ">\n <div style="\n color: rgba(255, 255, 255, 0.95);\n font-size: 14px;\n font-weight: 500;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n line-height: 1.2;\n ">'+this.mr(e)+'</div>\n <div style="\n color: rgba(255, 255, 255, 0.45);\n font-size: 12px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n line-height: 1.2;\n ">'+this.mr(this.br(t||"",50))+'</div>\n </div>\n </div>\n <div style="display: flex; align-items: center; gap: 8px; flex-shrink: 0;">\n <button class="vtilt-vtd-open vtilt-vtd-btn" title="Open in new tab">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>\n <polyline points="15 3 21 3 21 9"></polyline>\n <line x1="10" y1="14" x2="21" y2="3"></line>\n </svg>\n <span class="vtilt-vtd-btn-text">Open</span>\n </button>\n <button class="vtilt-vtd-close vtilt-vtd-btn vtilt-vtd-btn-primary" title="Close (Esc)">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <line x1="18" y1="6" x2="6" y2="18"></line>\n <line x1="6" y1="6" x2="18" y2="18"></line>\n </svg>\n <span class="vtilt-vtd-btn-text">Close</span>\n </button>\n </div>\n '}hr(){return"\n flex: 1;\n position: relative;\n background: #000;\n overflow: hidden;\n "}dr(){return"\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background: #0a0a0a;\n z-index: 1;\n transition: opacity 0.3s ease;\n "}cr(){var t=this.Gi||this.Ki,e=t?this.ir(t):"";return'\n <div class="vtilt-vtd-spinner"></div>\n <div style="\n margin-top: 20px;\n color: rgba(255, 255, 255, 0.7);\n font-size: 14px;\n font-weight: 500;\n ">Loading '+this.mr(e)+'...</div>\n <div style="\n margin-top: 8px;\n color: rgba(255, 255, 255, 0.35);\n font-size: 12px;\n ">Press <kbd style="\n display: inline-block;\n padding: 2px 6px;\n background: rgba(255, 255, 255, 0.1);\n border-radius: 4px;\n font-family: inherit;\n font-size: 11px;\n ">Esc</kbd> to close</div>\n '}vr(){return"\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n border: none;\n background: white;\n opacity: 0;\n transition: opacity 0.3s ease;\n "}pr(){return"\n /* Animations */\n @keyframes vtilt-vtd-fade-in {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes vtilt-vtd-fade-out {\n from { opacity: 1; }\n to { opacity: 0; }\n }\n \n @keyframes vtilt-vtd-scale-in {\n from { opacity: 0; transform: scale(0.96); }\n to { opacity: 1; transform: scale(1); }\n }\n \n @keyframes vtilt-vtd-spin {\n to { transform: rotate(360deg); }\n }\n \n /* Container animations */\n #vtilt-vtd-overlay.vtilt-vtd-opening {\n animation: vtilt-vtd-fade-in 0.2s ease-out forwards;\n }\n \n #vtilt-vtd-overlay.vtilt-vtd-opening .vtilt-vtd-modal {\n animation: vtilt-vtd-scale-in 0.25s ease-out forwards;\n }\n \n #vtilt-vtd-overlay.vtilt-vtd-closing {\n animation: vtilt-vtd-fade-out 0.2s ease-in forwards;\n }\n \n /* Loading spinner */\n .vtilt-vtd-spinner {\n width: 40px;\n height: 40px;\n border: 3px solid rgba(255, 255, 255, 0.1);\n border-top-color: rgba(255, 255, 255, 0.8);\n border-radius: 50%;\n animation: vtilt-vtd-spin 0.8s linear infinite;\n }\n \n /* Button base styles */\n .vtilt-vtd-btn {\n background: rgba(255, 255, 255, 0.08);\n border: 1px solid rgba(255, 255, 255, 0.1);\n color: rgba(255, 255, 255, 0.9);\n padding: 8px 14px;\n border-radius: 8px;\n cursor: pointer;\n font-size: 13px;\n font-weight: 500;\n display: flex;\n align-items: center;\n gap: 6px;\n transition: all 0.15s ease;\n -webkit-tap-highlight-color: transparent;\n outline: none;\n }\n \n .vtilt-vtd-btn:hover {\n background: rgba(255, 255, 255, 0.14);\n border-color: rgba(255, 255, 255, 0.18);\n }\n \n .vtilt-vtd-btn:active {\n background: rgba(255, 255, 255, 0.18);\n transform: scale(0.98);\n }\n \n .vtilt-vtd-btn:focus-visible {\n box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.3);\n }\n \n /* Primary button variant */\n .vtilt-vtd-btn-primary {\n background: rgba(255, 255, 255, 0.95);\n border-color: transparent;\n color: #0a0a0a;\n }\n \n .vtilt-vtd-btn-primary:hover {\n background: rgba(255, 255, 255, 1);\n border-color: transparent;\n }\n \n .vtilt-vtd-btn-primary:active {\n background: rgba(255, 255, 255, 0.85);\n }\n \n /* Desktop responsive - modal with margin */\n @media (min-width: 768px) {\n #vtilt-vtd-overlay {\n padding: 32px;\n }\n \n .vtilt-vtd-modal {\n max-width: 1200px;\n max-height: 90vh;\n width: 100%;\n height: auto;\n min-height: 500px;\n border-radius: 16px;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255, 255, 255, 0.1);\n }\n \n .vtilt-vtd-header {\n border-radius: 16px 16px 0 0;\n }\n \n .vtilt-vtd-iframe-wrapper {\n border-radius: 0 0 16px 16px;\n min-height: 400px;\n }\n }\n \n /* Large desktop - bigger modal */\n @media (min-width: 1400px) {\n #vtilt-vtd-overlay {\n padding: 48px;\n }\n \n .vtilt-vtd-modal {\n max-width: 1400px;\n max-height: 85vh;\n }\n }\n \n /* Tablet */\n @media (min-width: 768px) and (max-width: 1024px) {\n #vtilt-vtd-overlay {\n padding: 24px;\n }\n \n .vtilt-vtd-modal {\n max-width: 95%;\n max-height: 90vh;\n }\n }\n \n /* Mobile - fullscreen */\n @media (max-width: 767px) {\n #vtilt-vtd-overlay {\n padding: 0 !important;\n background: #0a0a0a !important;\n }\n \n .vtilt-vtd-modal {\n width: 100% !important;\n height: 100% !important;\n max-width: none !important;\n max-height: none !important;\n border-radius: 0 !important;\n }\n \n .vtilt-vtd-header {\n border-radius: 0 !important;\n padding: 0 12px !important;\n height: 52px !important;\n }\n \n .vtilt-vtd-btn {\n padding: 8px 10px !important;\n }\n \n .vtilt-vtd-btn-text {\n display: none !important;\n }\n \n .vtilt-vtd-iframe-wrapper {\n border-radius: 0 !important;\n }\n }\n \n /* Reduced motion */\n @media (prefers-reduced-motion: reduce) {\n #vtilt-vtd-overlay,\n #vtilt-vtd-overlay *,\n .vtilt-vtd-spinner {\n animation-duration: 0.01ms !important;\n transition-duration: 0.01ms !important;\n }\n }\n "}br(t,e){return t.length<=e?t:t.substring(0,e-3)+"..."}mr(t){if(void 0===i)return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var e=i.createElement("div");return e.textContent=t,e.innerHTML}}var dc,cc="text/plain",vc=61440;!function(t){t.GZipJS="gzip-js",t.Base64="base64",t.None="none"}(dc||(dc={}));var fc=function(t,e){void 0===e&&(e="binary");var{data:n,compression:i}=t;if(n){var r=(t=>JSON.stringify(t,(t,e)=>"bigint"==typeof e?e.toString():e))(n),s=new Blob([r]).size;if(i===dc.GZipJS&&s>=1024)try{var o=Bd(function(t,e){if(Nd)return Nd.encode(t);for(var n=t.length,i=new id(t.length+(t.length>>1)),r=0,s=function(t){i[r++]=t},o=0;o<n;++o){if(r+5>i.length){var a=new id(r+8+(n-o<<1));a.set(i),i=a}var l=t.charCodeAt(o);l<128||e?s(l):l<2048?(s(192|l>>6),s(128|63&l)):l>55295&&l<57344?(s(240|(l=65536+(1047552&l)|1023&t.charCodeAt(++o))>>18),s(128|l>>12&63),s(128|l>>6&63),s(128|63&l)):(s(224|l>>12),s(128|l>>6&63),s(128|63&l))}return kd(i,0,r)}(r),{mtime:0});if("text-base64"===e){var a=function(t){if("undefined"==typeof btoa)throw new Error("btoa is not available in this environment");for(var e="",n=0;n<t.length;n+=32768){var i=Math.min(n+32768,t.length),r=t.subarray(n,i);e+=String.fromCharCode.apply(null,r)}return btoa(e)}(o);if(a.length>0&&a.length<.95*s)return{contentType:cc,body:a,estimatedSize:a.length,compressionApplied:dc.Base64}}else{var l=new Blob([o],{type:cc});if(l.size>0&&l.size<.95*s)return{contentType:cc,body:l,estimatedSize:l.size,compressionApplied:dc.GZipJS}}}catch(t){}return{contentType:"application/json",body:r,estimatedSize:s,compressionApplied:null}}};function pc(t,e){return e.compressionApplied?(n=t.url,i=e.compressionApplied,r=n.includes("?")?"&":"?",""+n+r+"compression="+i):t.url;var n,i,r}function gc(t,e){var n={};return e&&(n["Content-Type"]=e),t.headers&&Object.assign(n,t.headers),t.projectToken&&(n[d]=t.projectToken),n}var mc=[{name:"fetch",isAvailable:()=>"undefined"!=typeof fetch,method:t=>{var e=fc(t,"binary");if(e){var{contentType:n,body:i,estimatedSize:r}=e,s=pc(t,e),o=gc(t,n),a=new AbortController,l=t.timeout?setTimeout(()=>a.abort(),t.timeout):null;fetch(s,{method:t.method||"POST",headers:o,body:i,keepalive:r<vc,signal:a.signal}).then(function(){var e=u(function*(e){var n,i=yield e.text(),r={statusCode:e.status,text:i};if(200===e.status){F();try{r.json=JSON.parse(i)}catch(t){}}null===(n=t.callback)||void 0===n||n.call(t,r)});return function(t){return e.apply(this,arguments)}}()).catch(()=>{var e;q("capture"),null===(e=t.callback)||void 0===e||e.call(t,{statusCode:0})}).finally(()=>{l&&clearTimeout(l)})}}},{name:"XHR",isAvailable:()=>"undefined"!=typeof XMLHttpRequest,method:t=>{var e=fc(t,"binary");if(e){var{contentType:n,body:i}=e,r=pc(t,e),s=gc(t,n),o=new XMLHttpRequest;for(var[a,l]of(o.open(t.method||"POST",r,!0),Object.entries(s)))o.setRequestHeader(a,l);t.timeout&&(o.timeout=t.timeout),o.onreadystatechange=()=>{var e;if(4===o.readyState){var n={statusCode:o.status,text:o.responseText};if(200===o.status){F();try{n.json=JSON.parse(o.responseText)}catch(t){}}null===(e=t.callback)||void 0===e||e.call(t,n)}},o.onerror=()=>{var e;q("capture"),null===(e=t.callback)||void 0===e||e.call(t,{statusCode:0})},o.send(i)}}},{name:"sendBeacon",isAvailable:()=>"undefined"!=typeof navigator&&!!navigator.sendBeacon,method:t=>{var e=fc(t,"text-base64");if(e){var{contentType:n,body:i,estimatedSize:r}=e;if(0!==r){var s=pc(t,e),o=t.projectToken?function(t,e){if(!e||/[?&]token=/.test(t))return t;var n=t.includes("?")?"&":"?";return""+t+n+"token="+e}(s,t.projectToken):s;if(r<=vc)try{var a="string"==typeof i?new Blob([i],{type:n}):i;if("undefined"!=typeof navigator&&navigator.sendBeacon)if(navigator.sendBeacon(o,a))return}catch(t){}try{var l="string"==typeof i?new Blob([i],{type:n}):i,u=h({"Content-Type":n},t.headers||{});fetch(o,{method:t.method||"POST",headers:u,body:l,keepalive:r<vc}).catch(()=>{})}catch(t){}}}}}],bc=t=>{var e,n;if(H())null===(e=t.callback)||void 0===e||e.call(t,{statusCode:0});else{var i=t.transport||"fetch",r=mc.find(t=>t.name===i&&t.isAvailable())||mc.find(t=>t.isAvailable());if(!r)return A().error("request","no available transport method"),void(null===(n=t.callback)||void 0===n||n.call(t,{statusCode:0}));r.method(t)}};class yc{constructor(t,e){var n,i,r,s;this.yr=!0,this.wr=[],this._r=(n=(null==e?void 0:e.flush_interval_ms)||3e3,i=250,r=5e3,s=3e3,"number"!=typeof n||isNaN(n)?s:Math.min(Math.max(n,i),r)),this.kr=t}get length(){return this.wr.length}enqueue(t){this.wr.push(t),this.Sr||this.Cr()}unload(){if(this.Tr(),0!==this.wr.length){var t=this.Ar();for(var e in t){var n=t[e];this.kr(h({},n,{transport:"sendBeacon"}))}}}enable(){this.yr=!1,this.Cr()}pause(){this.yr=!0,this.Tr()}flush(){this.Tr(),this.Er(),this.Cr()}Cr(){this.yr||(this.Sr=setTimeout(()=>{this.Tr(),this.Er(),this.wr.length>0&&this.Cr()},this._r))}Tr(){this.Sr&&(clearTimeout(this.Sr),this.Sr=void 0)}Er(){if(0!==this.wr.length){var t=this.Ar(),e=Date.now();for(var n in t){var i=t[n];i.events.forEach(t=>{var n=new Date(t.timestamp).getTime();t.$offset=Math.abs(n-e)}),this.kr(i)}}}Ar(){var t={};return this.wr.forEach(e=>{var n=e.batchKey||e.url;t[n]||(t[n]={url:e.url,events:[],batchKey:e.batchKey}),t[n].events.push(e.event)}),this.wr=[],t}}class wc{constructor(e){this.Ir=!1,this.Mr=3e3,this.wr=[],this.Or=!0,this.kr=e.sendRequest,this.Pr=e.sendBeacon,t&&void 0!==n&&"onLine"in n&&(this.Or=n.onLine,G(t,"online",()=>{this.Or=!0,this.mn()}),G(t,"offline",()=>{this.Or=!1}))}get length(){return this.wr.length}enqueue(t,e){if(void 0===e&&(e=0),e>=10)A().error("retry","request failed after 10 retries, giving up");else if(!H()){var n=function(t){var e=3e3*Math.pow(2,t),n=e/2,i=Math.min(18e5,e),r=(Math.random()-.5)*(i-n);return Math.ceil(i+r)}(e),i=Date.now()+n;this.wr.push({retryAt:i,request:t,retriesPerformedSoFar:e+1});var r="enqueued failed request for retry in "+Math.round(n/1e3)+"s";this.Or||(r+=" (browser is offline)"),A().warn("retry",r),this.Ir||(this.Ir=!0,this.Rr())}}retriableRequest(t){var e=this;return u(function*(){try{var n=yield e.kr(t);200!==n.statusCode&&(n.statusCode<400||n.statusCode>=500)&&e.enqueue(t,0)}catch(n){e.enqueue(t,0)}})()}Rr(){this.Dr&&clearTimeout(this.Dr),this.Dr=setTimeout(()=>{this.Or&&this.wr.length>0&&this.mn(),this.wr.length>0?this.Rr():this.Ir=!1},this.Mr)}mn(){var t=this,e=Date.now(),n=[],i=[];this.wr.forEach(t=>{t.retryAt<e?i.push(t):n.push(t)}),this.wr=n,i.forEach(function(){var e=u(function*(e){var{request:n,retriesPerformedSoFar:i}=e;try{var r=yield t.kr(n);200!==r.statusCode&&(r.statusCode<400||r.statusCode>=500)&&t.enqueue(n,i)}catch(e){t.enqueue(n,i)}});return function(t){return e.apply(this,arguments)}}())}unload(){this.Dr&&(clearTimeout(this.Dr),this.Dr=void 0),this.wr.forEach(t=>{var{request:e}=t;try{this.Pr(e)}catch(t){A().error("retry","failed to send beacon on unload",t)}}),this.wr=[]}}var xc="vt_rate_limit";class _c{constructor(t){var e,n;void 0===t&&(t={}),this.lastEventRateLimited=!1,this.eventsPerSecond=null!==(e=t.eventsPerSecond)&&void 0!==e?e:10,this.eventsBurstLimit=Math.max(null!==(n=t.eventsBurstLimit)&&void 0!==n?n:10*this.eventsPerSecond,this.eventsPerSecond),this.persistence=t.persistence,this.captureWarning=t.captureWarning,this.lastEventRateLimited=this.checkRateLimit(!0).isRateLimited}checkRateLimit(t){var e,n,i,r;void 0===t&&(t=!1);var s=Date.now(),o=null!==(n=null===(e=this.persistence)||void 0===e?void 0:e.get(xc))&&void 0!==n?n:{tokens:this.eventsBurstLimit,last:s},a=(s-o.last)/1e3;o.tokens+=a*this.eventsPerSecond,o.last=s,o.tokens>this.eventsBurstLimit&&(o.tokens=this.eventsBurstLimit);var l=o.tokens<1;return l||t||(o.tokens=Math.max(0,o.tokens-1)),!l||this.lastEventRateLimited||t||null===(i=this.captureWarning)||void 0===i||i.call(this,"vTilt client rate limited. Config: "+this.eventsPerSecond+" events/second, "+this.eventsBurstLimit+" burst limit."),this.lastEventRateLimited=l,null===(r=this.persistence)||void 0===r||r.set(xc,o),{isRateLimited:l,remainingTokens:o.tokens}}shouldAllowEvent(){return!this.checkRateLimit(!1).isRateLimited}getRemainingTokens(){return this.checkRateLimit(!0).remainingTokens}}class kc{constructor(t){this.Ur=null,this.jr=null,this.Br=t}get config(){return this.Ur}onApply(t){this.Nr=t}onLoad(t){this.Lr=t}load(){var e,n=this.Br.getConfig();if(n.token){if(this.jr||(this.jr=h({},n)),null===(e=n.bootstrap)||void 0===e?void 0:e.remoteConfig)return this.Ur=n.bootstrap.remoteConfig,this.$r(this.Ur),void this.zr();var i=I(()=>t.__VTILT_BOOTSTRAP__);if(null==i?void 0:i.remoteConfig)return this.Ur=i.remoteConfig,this.$r(this.Ur),void this.zr();I(()=>{var t=localStorage.getItem(Qa+"_"+n.token);t&&(this.Ur=JSON.parse(t),this.$r(this.Ur,!0))}),this.zr()}}zr(){var t=this.Br.getConfig();if(t.token)if(H())this.Br.updateConfig({__remote_config_loaded:!0});else{var e=this.Br.buildEndpointUrl("/api/d"),n=new AbortController,i=setTimeout(()=>n.abort(),3e3);(s||fetch)(e,{method:"GET",signal:n.signal,headers:h({Accept:"application/json"},v(t))}).then(t=>t.json()).then(e=>{var n;clearTimeout(i),F(),this.Ur=e,I(()=>{localStorage.setItem(Qa+"_"+t.token,JSON.stringify(e))}),this.$r(e),null===(n=this.Lr)||void 0===n||n.call(this,e)}).catch(()=>{clearTimeout(i),q("config"),this.Br.updateConfig({__remote_config_loaded:!0})})}}$r(t,e){var n,i,r,s;void 0===e&&(e=!1);var o=this.jr||this.Br.getConfig(),a={};for(var[,l]of this.Br.featureManager.getDescriptors())if(l.remoteConfig&&l.configKey){var u=t[l.remoteConfig.key];u&&void 0===o[l.configKey]&&(a[l.configKey]=l.remoteConfig.map(u))}if(t.analytics&&!e&&(void 0!==t.analytics.capturePageview&&void 0===o.capture_pageview&&(a.capture_pageview=t.analytics.capturePageview),void 0!==t.analytics.capturePageleave&&void 0===o.capture_pageleave&&(a.capture_pageleave=!!t.analytics.capturePageleave),void 0!==t.analytics.capturePerformance&&void 0===o.capture_performance&&(a.capture_performance=t.analytics.capturePerformance),void 0===o.autocapture)){var d=t.analytics.autocapture,c=t.analytics.scrollDepthMilestones,v=t.analytics.scrollDepthPageleave;void 0!==d&&(a.autocapture=d&&(c||v)?{scroll_depth:h({},c?{milestones:!0}:{},v?{pageleave:!0}:{})}:d)}e||(a.__remote_config_loaded=!0),void 0!==(null===(n=t.privacy)||void 0===n?void 0:n.respectDnt)&&void 0===o.respect_dnt&&(a.respect_dnt=t.privacy.respectDnt),void 0!==(null===(i=t.privacy)||void 0===i?void 0:i.requireConsent)&&void 0===o.require_consent&&(a.require_consent=t.privacy.requireConsent),void 0!==t.autocapture_opt_out&&(a.autocapture_opt_out=t.autocapture_opt_out),void 0!==t.elementsChainAsString&&(a.elementsChainAsString=t.elementsChainAsString),(null===(r=t.diagnostics)||void 0===r?void 0:r.defaultLogLevel)&&A().setLevelFromRemote(t.diagnostics.defaultLogLevel),Object.keys(a).length>0&&this.Br.updateConfig(a),null===(s=this.Nr)||void 0===s||s.call(this,t)}}var Sc=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"];function Cc(t,e){if(void 0===e&&(e=[]),!t)return!1;var n=t.toLowerCase();return[...Sc,...e].some(t=>-1!==n.indexOf(t.toLowerCase()))}function Tc(t,e){var n;if(void 0===e&&(e=[]),!t)return!1;var i=t.userAgent;if(i&&Cc(i,e))return!0;try{var r=t.userAgentData;if(null===(n=null==r?void 0:r.brands)||void 0===n?void 0:n.some(t=>Cc(null==t?void 0:t.brand,e)))return!0}catch(t){}return!!t.webdriver}var Ac=36e5;function Ec(){var e,n,i;return null!==(i=null===(n=null===(e=null==t?void 0:t.performance)||void 0===e?void 0:e.now)||void 0===n?void 0:n.call(e))&&void 0!==i?i:Date.now()}class Ic{constructor(){this.qr=Ec(),this.Fr=null,this.Hr=Ec(),this.Wr="",this.Jr="",this.Vr="",this.Kr=""}onAfterPageview(){var t=Ec();this.qr=t,this.Fr=t,this.Kr="",r&&(this.Wr=r.href||"",this.Jr=r.pathname||""),i&&(this.Vr=i.title||"")}peekEngagementSinceLastCaptureMs(){var t,e=Ec(),n=null!==(t=this.Fr)&&void 0!==t?t:this.Hr,i=Math.round(e-n);return i<1&&(i=1),i>Ac&&(i=Ac),i}commitCaptureClock(){this.Fr=Ec()}Gr(){return this.Wr+"\0"+this.Jr}clearLeaveDedupe(){this.Kr=""}tryCapturePageleave(t,e,n,i){if(function(t){var e=t.capture_pageleave;return!1!==e&&(!0===e||!1!==t.capture_pageview)}(t)){var r=this.Gr();if((this.Wr||this.Jr)&&r&&this.Kr!==r){this.Kr=r;var s=Ec(),o=Math.round(s-this.qr);o<1&&(o=1),o>Ac&&(o=Ac);var a={navigation_type:n,engagement_time_msec:o,[gl]:this.Wr,[ml]:this.Jr,[bl]:Math.round(o/1e3),[yl]:this.Jr,[wl]:this.Wr},l=this.Wr?function(t){try{return new URL(t).host}catch(t){return""}}(this.Wr):"";l&&(a.$host=l),this.Vr&&(a.title=this.Vr),i&&Object.assign(a,i),e(ol,a,{skip_engagement:!0})}}}}var Mc=[al,ll,ul,ol,vl,fl,hl,pl],Oc=new Set([al,ll,ul]),Pc=new Set([ol,pl,vl,fl,hl]);class Rc{constructor(t){this.Xr=!1,this.Qr=!1,this.Zr=null,this.Yr=null,this.es=new Ic,this.Br=t}setVtPersonId(t){this.Yr=t}capture(t,e,i){var r,s,o;this.Br.sessionManager.setSessionId();var a=this.Br.getConfig();if(a.opt_out_useragent_filter||!Tc(n,null!==(r=a.custom_blocked_useragents)&&void 0!==r?r:[]))if((null==n?void 0:n.userAgent)&&function(t){return!(t&&"string"==typeof t&&t.length>500)}(n.userAgent))if((null==i?void 0:i.skip_client_rate_limiting)||Mc.includes(t)||this.Br.rateLimiter.shouldAllowEvent())if(!this.Br.getConfig().require_consent||Oc.has(t)||(null===(s=this.Br.consentManager)||void 0===s?void 0:s.hasConsent())){var l=this.Br.buildUrl(),u=!0===(null==i?void 0:i.skip_engagement)||Pc.has(t),d=h({},e);u||"number"==typeof d.engagement_time_msec||(d=h({},d,{engagement_time_msec:this.es.peekEngagementSinceLastCaptureMs()}));var c=h({},this.ns(t,d),a.globalAttributes),v=JSON.stringify(c);if(!(f=v)||"string"!=typeof f||f.length<2||f.length>V)A().debug("capture","dropped",t,{reason:"payload_invalid_size",bytes:v.length,limitBytes:V,hint:t===dl?"Trim global / event properties; $elements is already off by default in compact mode.":"Trim event properties; payload exceeded the runaway-guard cap."});else{var f,p=t===al?this.Br.userManager.getAnonymousId():null!==(o=this.Br.userManager.getDistinctId())&&void 0!==o?o:this.Br.userManager.getAnonymousId(),g={timestamp:(new Date).toISOString(),event:t,payload:c,distinct_id:p,anonymous_id:this.Br.userManager.getAnonymousId()};this.Br.bufferEvent(t,l,g),A().debug("capture","enqueued",t,h({distinct_id:p,$current_url:c.$current_url,$session_id:c.$session_id,$debug:c.$debug},t===dl&&"object"==typeof c&&null!==c?{$event_type:c.$event_type}:{})),this.Yr&&(this.Yr=null),t===sl?this.es.onAfterPageview():this.es.commitCaptureClock()}}else A().debug("capture","dropped",t,{reason:"require_consent_and_no_consent"});else A().debug("capture","dropped",t,{reason:"client_rate_limited",hint:"Token bucket (~10/s, burst ~100). $autocapture counts toward the same limit as custom events."});else A().debug("capture","dropped",t,{reason:"invalid_or_missing_user_agent"});else A().debug("capture","dropped",t,{reason:"bot"})}captureInternal(t,e){this.capture(t,e,{skip_client_rate_limiting:!0})}captureInitialPageview(){i&&("visible"===i.visibilityState?this.Qr||(this.Qr=!0,setTimeout(()=>{i&&r&&!1!==this.Br.getConfig().capture_pageview&&this.capture(sl,{navigation_type:"initial_load"})},300),this.Zr&&(i.removeEventListener("visibilitychange",this.Zr),this.Zr=null)):this.Zr||(this.Zr=()=>this.captureInitialPageview(),G(i,"visibilitychange",this.Zr)))}tryCapturePageleave(t,e){this.es.tryCapturePageleave(this.Br.getConfig(),(t,e,n)=>this.capture(t,e,n),t,e)}resetPageleaveDedupe(){this.es.clearLeaveDedupe()}rs(){if(this.Br.getConfig().debug)return!0;try{if(null==r?void 0:r.search)if("1"===new URLSearchParams(r.search).get("vtilt_debug"))return!0}catch(t){}return!1}ns(t,e){var n,r,s=this.Br.getConfig(),o=s.mask_personal_data_properties,a=s.custom_personal_data_properties,l=Yu(o,a),u=Z(function(t,e,n){if(!i)return{};var r=e?Q([],qu,n||[]):[];return X({},Wu(jl(i.URL,r,Hu)))}(0,o,a)),d=this.Br.userManager.getUserProperties(),c=this.Br.userManager.get_initial_props(),v=this.Br.sessionManager.getSessionId(),f=this.Br.sessionManager.getWindowId(),p={};!this.Xr&&Object.keys(c).length>0&&Object.assign(p,c),e.$set_once&&Object.assign(p,e.$set_once);var g=h({},l,u,d,null!==(r=null===(n=this.Br.consentManager)||void 0===n?void 0:n.getConsentProperties())&&void 0!==r?r:{},{$session_id:v,$window_id:f},this.Yr?{$vt:this.Yr}:{},Object.keys(p).length>0?{$set_once:p}:{},e.$set?{$set:e.$set}:{},e);!this.Xr&&Object.keys(c).length>0&&(this.Xr=!0),t===sl&&i&&(g.title=i.title),this.rs()&&(g.$debug=!0);var m=this.Br.sessionManager.consumeSessionStart(),b=this.Br.userManager.consumeFirstVisit();return m&&(g.$session_start=!0),b&&(g.$first_visit=!0),g}}var Dc=["null","undefined","false","true","anonymous","anon","user","test","guest","visitor","unknown","none","demo","example","sample","placeholder"];function Uc(t){return!(!t||"string"!=typeof t)&&Dc.includes(t.toLowerCase().trim())}class jc{constructor(t){this.ss=null,this.ls=null,this.Br=t}identify(t,e,n){var i;if("number"==typeof t&&(t=String(t),A().warn("identify","first argument should be a string, not a number")),t)if(Uc(t))A().error("identify",'"'+t+'" appears to be a hardcoded string');else if("COOKIELESS_SENTINEL_VALUE"!==t){var r=JSON.stringify([t,e,n]);if(this.ss!==r){var s=this.Br.userManager,o=s.getDistinctId(),a=s.getAnonymousId(),l=s.getDeviceId();if(!("identified"===s.getUserState())&&a!==t||t!==o){this.Br.capture(al,{distinct_id:t,$set:e||{},$set_once:n||{}});var u={user_state:"identified",distinct_id:t,properties_set:e,properties_set_once:n};if(!l){var d=o||a;u.device_id=d,u.properties_set=h({$had_persisted_distinct_id:!0,$device_id:d},u.properties_set||{})}s.applyUpdate(u),null===(i=this.Br._emitter)||void 0===i||i.emit("user:identified",{distinctId:t})}else(e||n)&&this.setUserProperties(e,n);this.ss=r}}else A().error("identify","cannot use sentinel value as distinct_id");else A().error("identify","unique user id is required")}setUserProperties(t,e){var n,i;if(t||e){var r=this.Br.userManager,s=JSON.stringify([null!==(n=r.getDistinctId())&&void 0!==n?n:r.getAnonymousId(),t,e]);this.ls!==s&&(r.applyUpdate({properties_set:t,properties_set_once:e}),this.Br.capture(ul,{$set:t||{},$set_once:e||{}}),null===(i=this.Br._emitter)||void 0===i||i.emit("user:properties_set",{properties:t}),this.ls=s)}}resetUser(t){var e;this.Br.sessionManager.resetSessionId(),this.Br.userManager.reset(t),this.ss=null,this.ls=null,null===(e=this.Br._emitter)||void 0===e||e.emit("user:reset")}alias(t,e){var n;if(t&&!Uc(t)){var i=this.Br.userManager,r=null!==(n=null!=e?e:i.getDistinctId())&&void 0!==n?n:i.getAnonymousId();r&&!Uc(r)?t!==r?this.Br.capture(ll,{$original_id:r,$alias_id:t}):this.identify(t):A().warn("alias","invalid original distinct ID")}else A().warn("alias","invalid alias")}getUserIdentity(){return this.Br.userManager.getUserIdentity()}getDeviceId(){return this.Br.userManager.getDeviceId()}getUserState(){return this.Br.userManager.getUserState()}getDistinctId(){var t;return null!==(t=this.Br.userManager.getDistinctId())&&void 0!==t?t:this.Br.userManager.getAnonymousId()}getAnonymousId(){return this.Br.userManager.getAnonymousId()}}var Bc="_vtilt_consent";class Nc{constructor(t){this.us={},this.hs=!1,this.Br=t,this.ds()}setConsent(t){var e;this.us=h({},this.us,t),this.hs=!0,this.cs(),null===(e=this.Br._emitter)||void 0===e||e.emit("consent:updated",{consent:this.us})}getConsent(){return h({},this.us)}hasConsent(){return this.hs}setDefaultGranted(){this.hs||(this.us={analytics:!0,marketing:!0,advertising:!0},this.hs=!0)}getConsentProperties(){var t={};return void 0!==this.us.analytics&&(t.$consent_analytics=this.us.analytics),void 0!==this.us.marketing&&(t.$consent_marketing=this.us.marketing),void 0!==this.us.advertising&&(t.$consent_advertising=this.us.advertising),t}reset(){this.us={},this.hs=!1,this.vs()}ds(){if(void 0!==i&&(null==i?void 0:i.cookie)){var t=Bc+"=";for(var e of i.cookie.split(";")){var n=e.trim();if(n.startsWith(t)){try{var r=decodeURIComponent(n.slice(15)),s=JSON.parse(r);s&&"object"==typeof s&&(this.us=s,this.hs=!0)}catch(t){}return}}}}cs(){if(void 0!==i){var t=encodeURIComponent(JSON.stringify(this.us)),e="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";i.cookie=Bc+"="+t+"; Max-Age=31536000; path=/; SameSite=Lax"+e}}vs(){void 0!==i&&(i.cookie=Bc+"=; Max-Age=0; path=/")}}class Lc{constructor(t){this.fs=new Map,this.ps=new Map,this.Br=t}register(t){this.fs.set(t.name,t)}createInstances(){var t=this,e=this.Br.getConfig(),n=function(n,i){return t.ps.has(n)||t.gs(e,i)?0:void I(()=>{var r=i.FeatureClass.extractConfig(e),s=new i.FeatureClass(t.Br,r);t.ps.set(n,s)})};for(var[i,r]of this.fs)n(i,r)}initAll(){this.createInstances();var t=function(t){I(()=>{t.isStarted||t.startIfEnabled()})};for(var[,e]of this.ps)t(e)}notifyAll(t){var e=function(e){e.onConfigUpdate&&I(()=>e.onConfigUpdate(t))};for(var[,n]of this.ps)e(n)}get(t){return this.ps.get(t)}set(t,e){this.ps.set(t,e)}getDescriptors(){return this.fs}gs(t,e){if(e.disableKey&&!0===t[e.disableKey])return!0;if(e.configKey){var n=t[e.configKey];if(n&&"object"==typeof n&&!1===n.enabled)return!0}return!1}}class $c{constructor(t){this.wr=new oc,this.bs=!1,this.ys=!1,this.Br=t,this.ws(),this.bs||(this.xs=setTimeout(()=>this.forceFlush(),5e3))}push(t){this.bs?this._s(t):this.wr.enqueue(t)}markConfigReady(){this.ys||(this.ys=!0,this.ks())}forceFlush(){this.Ss(),this.mn(),this.bs=!0}ws(){this.bs=this.ys}ks(){this.ws(),this.bs&&(this.Ss(),this.mn())}mn(){var t=this.wr.takeAll();for(var e of t)this._s(e);t.length>0&&this.Br.requestQueue.flush()}_s(t){if(this.ys){if(this.Cs(t.name))return}else this.Ts(t.event);this.Br.sendRequest(t.url,t.event)}Cs(t){var e=this.Br.getConfig();switch(t){case sl:return!1===e.capture_pageview;case ol:return!1===e.capture_pageleave;case hl:return!1===e.capture_performance;case dl:case cl:return!1===e.autocapture;default:return!1}}Ts(t){"object"==typeof t.payload&&null!==t.payload&&(t.payload.$config_pending=!0)}Ss(){void 0!==this.xs&&(clearTimeout(this.xs),this.xs=void 0)}}var zc="vt";class qc{constructor(t){void 0===t&&(t={}),this.version=Ha,this.__loaded=!1,this.As=!1,this.Es=!1,this.Is=[],this.Ms=!1,A().debug("ctor","start"),this._emitter=new M,this.configManager=new Cl(t);var e=this.configManager.getConfig();E(e),this.sessionManager=new Ol(e.storage||"cookie",e.cross_subdomain_cookie),this.userManager=new th(e.persistence||"localStorage+cookie",e.cross_subdomain_cookie),this.rateLimiter=new _c({eventsPerSecond:10,eventsBurstLimit:100,captureWarning:t=>{this.Os.captureInternal(pl,{$$client_ingestion_warning_message:t})}}),this.retryQueue=new wc({sendRequest:t=>this.Ps(t),sendBeacon:t=>this.Rs(t)}),this.requestQueue=new yc(t=>this.Ds(t),{flush_interval_ms:3e3}),this.consentManager=new Nc(this),this.Os=new Rc(this),this.Us=new jc(this),this.js=new Lc(this),this.Bs=new kc(this),this.Ns(),this.Bs.onLoad(t=>{this._emitter.emit(R,{config:t})}),this.Ls(),A().debug("ctor","boot gate installed")}Ns(){this.js.register({name:"HistoryAutocapture",configKey:"capture_pageview",FeatureClass:uh}),this.js.register({name:"Autocapture",configKey:"autocapture",FeatureClass:Yh}),this.js.register({name:"WebVitals",configKey:"capture_performance",FeatureClass:ah}),this.js.register({name:"SessionRecording",configKey:"session_recording",disableKey:"disable_session_recording",remoteConfig:{key:"sessionRecording",map:t=>({enabled:t.enabled,sampleRate:t.sampleRate,minimumDurationMs:t.minimumDurationMs,fullSnapshotIntervalMs:t.fullSnapshotIntervalMs,maskAllInputs:t.maskAllInputs,captureConsole:t.captureConsole,captureCanvas:t.captureCanvas})},FeatureClass:ed}),this.js.register({name:"Chat",configKey:"chat",disableKey:"disable_chat",remoteConfig:{key:"chat",map:t=>({enabled:t.enabled,position:t.widgetPosition,color:t.widgetColor})},FeatureClass:zd}),this.js.register({name:"GoogleTagGateway",configKey:"google_tag",disableKey:"disable_google_tag",remoteConfig:{key:"googleTag",map:t=>t},FeatureClass:lc})}Ls(){var t=this,e=function(e){var n=t[e];t[e]=function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];if(t.Es)return n.apply(t,r);t.Is.push([e,...r])}};for(var n of qc.BOOT_GATED_METHODS)e(n)}$s(){if(!this.Es){for(var t of(this.Es=!0,A().debug("boot","start"),qc.BOOT_GATED_METHODS))delete this[t];A().debug("boot","gate removed"),this.__loaded&&!this.Ms?(A().debug("boot","running _runPostBootInit"),this.zs()):A().debug("boot","skipping _runPostBootInit","loaded?",this.__loaded,"postBootDone?",this.Ms),A().debug("boot","flush pendingCalls",this.Is.length),this._execute_array(this.Is),this.Is=[]}}init(t,e,n){var i;if(n&&n!==zc){var r=null!==(i=Fc[n])&&void 0!==i?i:new qc;return r._init(t,e,n),Fc[n]=r,Fc[zc][n]=r,r}return this._init(t,e,n)}_init(t,e,n){if(void 0===e&&(e={}),this.__loaded)return A().warn("init","already initialized; re-initializing is a no-op"),this;this.configManager.updateConfig(h({},e,{token:t||e.token,name:n}));var r=this.configManager.getConfig();return E(r),this.__loaded=!0,A().debug("init","start","token present?",!!r.token,"name",null!=n?n:"vt"),this.js.createInstances(),this.Es||void 0===i||"interactive"!==i.readyState&&"complete"!==i.readyState||(A().debug("init","self-boot?",i.readyState),this.$s()),this.Es&&!this.Ms&&this.zs(),A().debug("init","postBootInitDone",this.Ms),this}zs(){if(!this.Ms){this.Ms=!0,A().debug("postBoot","start");var t=this.configManager.getConfig();this.sessionManager=new Ol(t.storage||"cookie",t.cross_subdomain_cookie),this.sessionManager.hydrateFromStorage(),A().debug("postBoot","sessionManager hydrated");var e=t.persistence||"localStorage+cookie";this.userManager.updateStorageMethod(e,t.cross_subdomain_cookie),this.userManager.hydrateFromStorage(),A().debug("postBoot","userManager hydrated"),t.require_consent||this.consentManager.hasConsent()||this.consentManager.setDefaultGranted(),!0===this.consentManager.getConsent().advertising&&zl(),this._emitter.on("consent:updated",t=>{var e=t.consent;!0===e.advertising?zl():!1===e.advertising&&void 0!==i&&(i.cookie=Bl+"=; Max-Age=0; path=/",i.cookie=Nl+"=; Max-Age=0; path=/")}),this.qs(),this.userManager.set_initial_person_info(t.mask_personal_data_properties,t.custom_personal_data_properties),this.Fs=new $c({sendRequest:(t,e)=>this.sendRequest(t,e),requestQueue:this.requestQueue,getConfig:()=>this.configManager.getConfig()}),this.js.initAll(),A().debug("postBoot","features inited"),this.Bs.load(),this.Hs(),this.Ws();var n=this.configManager.getConfig();!1!==n.capture_pageview&&this.Os.captureInitialPageview(),this.js.notifyAll(n),this._emitter.emit(O,{config:n}),A().debug("postBoot","done"),A().info("init","SDK ready")}}startAutocapture(){var t=this.js.get("Autocapture");if(!t){var e=Yh.extractConfig(this.configManager.getConfig());t=new Yh(this,e),this.js.set("Autocapture",t)}t.updateConfig({enabled:!0})}stopAutocapture(){var t=this.js.get("Autocapture");t&&t.updateConfig({enabled:!1})}isAutocaptureActive(){var t,e;return null!==(e=null===(t=this.js.get("Autocapture"))||void 0===t?void 0:t.isStarted)&&void 0!==e&&e}getAutocaptureDiagnostics(){var t,e;return null!==(e=null===(t=this.js.get("Autocapture"))||void 0===t?void 0:t.getDiagnostics())&&void 0!==e?e:null}startSessionRecording(){var t=this.js.get("SessionRecording");t||(t=new ed(this),this.js.set("SessionRecording",t)),t.updateConfig({enabled:!0}),t.startIfEnabledOrStop("recording_initialized"),this._emitter.emit(j)}stopSessionRecording(){var t;null===(t=this.js.get("SessionRecording"))||void 0===t||t.stop(),this._emitter.emit(B)}isRecordingActive(){var t;return"active"===(null===(t=this.js.get("SessionRecording"))||void 0===t?void 0:t.status)}getSessionRecordingId(){var t;return(null===(t=this.js.get("SessionRecording"))||void 0===t?void 0:t.sessionId)||null}openChat(){var t=this.js.get("Chat");t?t.open():A().warn("chat","openChat: feature not available")}closeChat(){var t=this.js.get("Chat");t?t.close():A().warn("chat","closeChat: feature not available")}toggleChat(){var t=this.js.get("Chat");t?t.toggle():A().warn("chat","toggleChat: feature not available")}showChat(){var t=this.js.get("Chat");t?t.show():A().warn("chat","showChat: feature not available")}hideChat(){var t=this.js.get("Chat");t?t.hide():A().warn("chat","hideChat: feature not available")}sendChatMessage(t,e){var n=this.js.get("Chat");return n?n.sendMessage(t,e):(A().warn("chat","sendChatMessage: feature not available"),Promise.resolve())}gtag(){for(var t=this.js.get("GoogleTagGateway"),e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];t?t.gtag(...n):this.Is.push(["gtag",...n])}setGoogleUserData(t){var e=this.js.get("GoogleTagGateway");return e?e.setUserData(t):Promise.resolve()}get featureManager(){return this.js}on(t,e){return this._emitter.on(t,e)}once(t,e){return this._emitter.once(t,e)}off(t){this._emitter.off(t)}_is_bot(){var t,e=this.getConfig();return!e.opt_out_useragent_filter&&Tc(n,null!==(t=e.custom_blocked_useragents)&&void 0!==t?t:[])}capture(t,e,n){this.Os.capture(t,e,n),this._emitter.emit(U,{event:t,payload:e})}tryCapturePageleave(t){var e,n=null===(e=this.js.get("Autocapture"))||void 0===e?void 0:e.getMaxScrollDepthPctForPageleave(),i=null!=n?{[kl]:n}:void 0;this.Os.tryCapturePageleave(t,i)}identify(t,e,n){this.Us.identify(t,e,n)}setUserProperties(t,e){this.Us.setUserProperties(t,e)}resetUser(t){this.Us.resetUser(t)}alias(t,e){this.Us.alias(t,e)}setConsent(t){this.consentManager.setConsent(t)}getConsent(){return this.consentManager.getConsent()}getUserIdentity(){return this.Us.getUserIdentity()}getDeviceId(){return this.Us.getDeviceId()}getUserState(){return this.Us.getUserState()}getConfig(){return this.configManager.getConfig()}getRemoteConfig(){return this.Bs.config}getSessionId(){return this.sessionManager.getSessionId()}getDistinctId(){return this.Us.getDistinctId()}getAnonymousId(){return this.Us.getAnonymousId()}toString(){var t,e=null!==(t=this.configManager.getConfig().name)&&void 0!==t?t:zc;return e!==zc&&(e="vt."+e),e}updateConfig(t){var e,n=this.configManager.getConfig();this.configManager.updateConfig(t);var i=this.configManager.getConfig();!n.__remote_config_loaded&&i.__remote_config_loaded&&(null===(e=this.Fs)||void 0===e||e.markConfigReady()),this.js.notifyAll(i),this._emitter.emit(P,{config:i})}buildUrl(){return this.buildEndpointUrl("/api/e")}buildEndpointUrl(t){return c(this.configManager.getConfig(),t)}sendRequest(t,e){this.Js()&&this.requestQueue.enqueue({url:t,event:e})}bufferEvent(t,e,n){t!==vl&&t!==fl?this.Fs.push({name:t,url:e,event:n}):this.sendRequest(e,n)}Js(){return!!this.configManager.getConfig().token||(this.As||(A().warn("config","token is required for tracking"),this.As=!0),!1)}Ds(t){"sendBeacon"!==t.transport?this.retryQueue.retriableRequest(t):this.Rs(t)}Ps(t){return new Promise(e=>{var{url:n,events:i}=t,r=this.configManager.getConfig(),s=1===i.length?i[0]:{events:i},o=r.disable_compression?dc.None:dc.GZipJS;bc({url:n,data:s,method:"POST",transport:"XHR",compression:o,projectToken:r.token,callback:t=>e({statusCode:t.statusCode})})})}Rs(t){var{url:e,events:n}=t,i=this.configManager.getConfig(),r=1===n.length?n[0]:{events:n},s=i.disable_compression?dc.None:dc.GZipJS;bc({url:e,data:r,method:"POST",transport:"sendBeacon",compression:s,projectToken:i.token})}Vs(t){this.sendRequest(t.url,t.event)}Hs(){if(t){var e=()=>{this.Fs.forceFlush(),this.requestQueue.unload(),this.retryQueue.unload()};G(t,"beforeunload",e),G(t,"pagehide",()=>{this.Os.tryCapturePageleave("pagehide"),e()}),i&&G(i,"visibilitychange",()=>{i&&("hidden"===i.visibilityState?this.Os.tryCapturePageleave("visibility_hidden"):"visible"===i.visibilityState&&this.Os.resetPageleaveDedupe())})}}Ws(){this.requestQueue.enable()}qs(){I(()=>{var e,n;if(void 0!==r&&r.search){var i=new URL(r.href),s=i.searchParams.get("vt"),o=i.searchParams.get("vtd");if((null==s?void 0:s.trim())&&(this.Os.setVtPersonId(s.trim()),i.searchParams.delete("vt")),(null==o?void 0:o.trim())&&(this.Ks(o.trim()),i.searchParams.delete("vtd")),(null==s?void 0:s.trim())||(null==o?void 0:o.trim())){var a=i.pathname+(i.search||"")+i.hash;null===(n=null===(e=null==t?void 0:t.history)||void 0===e?void 0:e.replaceState)||void 0===n||n.call(e,{},"",a)}}})}Ks(t){this.vtdOverlay||(this.vtdOverlay=new hc(this),this.vtdOverlay.setDestinationUrl(t))}_execute_array(t){m(t)&&t.forEach(t=>{if(t&&m(t)&&t.length>0){var e=t[0],n=t.slice(1);"function"==typeof this[e]&&I(()=>this[e](...n))}})}_dom_loaded(){this.Ws()}}qc.BOOT_GATED_METHODS=["capture","identify","setUserProperties","resetUser","alias","setConsent","startAutocapture","stopAutocapture","startSessionRecording","stopSessionRecording","openChat","closeChat","toggleChat","showChat","hideChat","sendChatMessage"];var Fc={};var Hc,Wc=["init","capture","identify","setUserProperties","resetUser","getUserIdentity","getDeviceId","getUserState","alias","getConfig","getSessionId","updateConfig","setConsent","on","once","off","startAutocapture","stopAutocapture","startSessionRecording","stopSessionRecording","openChat","closeChat","toggleChat","showChat","hideChat","sendChatMessage","gtag","setGoogleUserData"],Jc=Wc.join(" "),Vc=(Hc=Fc[zc]=new qc,function(){function e(){if(!e.done){e.done=!0,A().debug("dom","handler fired");var t=Object.keys(Fc);A().debug("boot","instance count",t.length),K(Fc,(t,e)=>{A().debug("boot","instance",e),t.$s(),t._dom_loaded()})}}if(i&&"function"==typeof i.addEventListener)return A().debug("dom","readyState",i.readyState),void("complete"===i.readyState||"interactive"===i.readyState?(A().debug("dom","running handler sync"),e()):(A().debug("dom","registered DOMContentLoaded listener"),G(i,"DOMContentLoaded",e,{capture:!1})));t&&A().error("dom","browser doesn't support document.addEventListener")}(),Hc);export{eh as ALL_WEB_VITALS_METRICS,nh as DEFAULT_WEB_VITALS_METRICS,Jc as VTILT_SNIPPET_STUB_METHODS,Wc as VTILT_SNIPPET_STUB_METHOD_NAMES,qc as VTilt,Vc as default,Vc as vt};
|
|
2
|
+
//# sourceMappingURL=module.chat.js.map
|