@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.
Files changed (109) hide show
  1. package/dist/all-external-dependencies.js.map +1 -1
  2. package/dist/array.chat.js +2 -0
  3. package/dist/array.chat.js.map +1 -0
  4. package/dist/array.chat.no-external.js +2 -0
  5. package/dist/array.chat.no-external.js.map +1 -0
  6. package/dist/array.full.chat.js +2 -0
  7. package/dist/array.full.chat.js.map +1 -0
  8. package/dist/array.full.chat.no-external.js +2 -0
  9. package/dist/array.full.chat.no-external.js.map +1 -0
  10. package/dist/array.full.js +1 -1
  11. package/dist/array.full.js.map +1 -1
  12. package/dist/array.full.no-external.js +2 -0
  13. package/dist/array.full.no-external.js.map +1 -0
  14. package/dist/array.js +1 -1
  15. package/dist/array.js.map +1 -1
  16. package/dist/array.no-external.js +1 -1
  17. package/dist/array.no-external.js.map +1 -1
  18. package/dist/chat.js +1 -1
  19. package/dist/chat.js.map +1 -1
  20. package/dist/entrypoints/all-external-dependencies.d.ts +10 -3
  21. package/dist/entrypoints/array.chat.d.ts +10 -0
  22. package/dist/entrypoints/array.chat.no-external.d.ts +6 -0
  23. package/dist/entrypoints/array.full.chat.d.ts +13 -0
  24. package/dist/entrypoints/array.full.chat.no-external.d.ts +7 -0
  25. package/dist/entrypoints/array.full.d.ts +5 -9
  26. package/dist/entrypoints/array.full.no-external.d.ts +12 -0
  27. package/dist/entrypoints/module.chat.es.d.ts +7 -0
  28. package/dist/entrypoints/module.full.chat.es.d.ts +12 -0
  29. package/dist/entrypoints/module.full.es.d.ts +12 -0
  30. package/dist/entrypoints/module.no-external.es.d.ts +1 -0
  31. package/dist/extensions/chat/bubble-drag.d.ts +20 -5
  32. package/dist/extensions/chat/chat-wrapper.d.ts +8 -2
  33. package/dist/extensions/chat/chat.d.ts +21 -351
  34. package/dist/extensions/chat/controller/__tests__/fakes/ably-realtime-fake.d.ts +84 -0
  35. package/dist/extensions/chat/controller/ably-client.d.ts +160 -0
  36. package/dist/extensions/chat/controller/ably-handlers.d.ts +95 -0
  37. package/dist/extensions/chat/controller/ably-token.d.ts +67 -0
  38. package/dist/extensions/chat/controller/chat-controller.d.ts +194 -0
  39. package/dist/extensions/chat/controller/message-delivery-status.d.ts +6 -0
  40. package/dist/extensions/chat/controller/message-order.d.ts +12 -0
  41. package/dist/extensions/chat/controller/message-stream.d.ts +49 -0
  42. package/dist/extensions/chat/lib/bubble-offset.d.ts +18 -0
  43. package/dist/extensions/chat/lib/merge-chat-config.d.ts +3 -0
  44. package/dist/extensions/chat/normalize-send-content.d.ts +2 -0
  45. package/dist/extensions/chat/outbox/message-delivery.d.ts +17 -0
  46. package/dist/extensions/chat/outbox/message-outbox.d.ts +57 -0
  47. package/dist/extensions/chat/store/chat-store.d.ts +122 -0
  48. package/dist/extensions/chat/types.d.ts +1 -19
  49. package/dist/extensions/chat/ui/ChannelItem.d.ts +12 -0
  50. package/dist/extensions/chat/ui/ChannelListView.d.ts +14 -0
  51. package/dist/extensions/chat/ui/ChatBubble.d.ts +14 -0
  52. package/dist/extensions/chat/ui/ChatHeader.d.ts +13 -0
  53. package/dist/extensions/chat/ui/ChatPanel.d.ts +14 -0
  54. package/dist/extensions/chat/ui/ChatRoot.d.ts +31 -0
  55. package/dist/extensions/chat/ui/ClosedBanner.d.ts +7 -0
  56. package/dist/extensions/chat/ui/ConnectionBanner.d.ts +32 -0
  57. package/dist/extensions/chat/ui/ConversationView.d.ts +14 -0
  58. package/dist/extensions/chat/ui/MessageBubble.d.ts +25 -0
  59. package/dist/extensions/chat/ui/MessageInput.d.ts +14 -0
  60. package/dist/extensions/chat/ui/MessageList.d.ts +19 -0
  61. package/dist/extensions/chat/ui/NewMessagesPill.d.ts +13 -0
  62. package/dist/extensions/chat/ui/Skeletons.d.ts +14 -0
  63. package/dist/extensions/chat/ui/TypingBubble.d.ts +23 -0
  64. package/dist/extensions/chat/ui/TypingIndicator.d.ts +12 -0
  65. package/dist/extensions/chat/ui/WidgetSlot.d.ts +20 -0
  66. package/dist/extensions/chat/ui/hooks/use-auto-mark-read.d.ts +18 -0
  67. package/dist/extensions/chat/ui/hooks/use-scroll-preservation.d.ts +33 -0
  68. package/dist/extensions/chat/ui/icons.d.ts +18 -0
  69. package/dist/extensions/chat/ui/message-render.d.ts +18 -0
  70. package/dist/extensions/chat/ui/shadow-styles.d.ts +13 -0
  71. package/dist/extensions/chat/ui/utils/mobile-body-scroll-lock.d.ts +14 -0
  72. package/dist/extensions/chat/widget-registry.d.ts +21 -5
  73. package/dist/extensions/chat/widgets/collect-email.d.ts +4 -2
  74. package/dist/extensions/chat/widgets/escalate-to-human.d.ts +2 -1
  75. package/dist/external-scripts-loader.js +1 -1
  76. package/dist/external-scripts-loader.js.map +1 -1
  77. package/dist/feature.d.ts +1 -0
  78. package/dist/lib/merge-vtilt-config.d.ts +9 -0
  79. package/dist/main.js +1 -1
  80. package/dist/main.js.map +1 -1
  81. package/dist/module.chat.d.ts +1788 -0
  82. package/dist/module.chat.js +2 -0
  83. package/dist/module.chat.js.map +1 -0
  84. package/dist/module.d.ts +48 -3
  85. package/dist/module.full.chat.d.ts +1792 -0
  86. package/dist/module.full.chat.js +2 -0
  87. package/dist/module.full.chat.js.map +1 -0
  88. package/dist/module.full.d.ts +1793 -0
  89. package/dist/module.full.js +2 -0
  90. package/dist/module.full.js.map +1 -0
  91. package/dist/module.js +1 -1
  92. package/dist/module.js.map +1 -1
  93. package/dist/module.no-external.d.ts +48 -3
  94. package/dist/module.no-external.js +1 -1
  95. package/dist/module.no-external.js.map +1 -1
  96. package/dist/recorder.js.map +1 -1
  97. package/dist/snippet-stub-methods.d.ts +14 -0
  98. package/dist/utils/globals.d.ts +53 -27
  99. package/dist/utils/index.d.ts +8 -0
  100. package/dist/vtilt.d.ts +6 -1
  101. package/dist/web-vitals.js.map +1 -1
  102. package/package.json +74 -71
  103. package/dist/extensions/chat/chat-styles.d.ts +0 -27
  104. package/dist/extensions/chat/message-content-styles.d.ts +0 -1
  105. package/dist/extensions/chat/message-html.d.ts +0 -6
  106. package/dist/extensions/chat/message-markdown.d.ts +0 -8
  107. package/dist/extensions/ga4-proxy.d.ts +0 -59
  108. package/dist/utils/type-utils.d.ts +0 -4
  109. package/dist/web-vitals.d.ts +0 -81
@@ -0,0 +1,2 @@
1
+ !function(){"use strict";var e="undefined"!=typeof window?window:void 0,t="undefined"!=typeof globalThis?globalThis:e,n=null==t?void 0:t.navigator,i=null==t?void 0:t.document,r=null==t?void 0:t.location,s=null==t?void 0:t.fetch;e&&i&&i.createElement,null==t||t.XMLHttpRequest,null==t||t.AbortController;var a=null==n?void 0:n.userAgent,o=null!=e?e:{};function l(e,t,n,i,r,s,a){try{var o=e[s](a),l=o.value}catch(e){return void n(e)}o.done?t(l):Promise.resolve(l).then(i,r)}function c(e){return function(){var t=this,n=arguments;return new Promise(function(i,r){var s=e.apply(t,n);function a(e){l(s,i,r,a,o,"next",e)}function o(e){l(s,i,r,a,o,"throw",e)}a(void 0)})}}function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},d.apply(null,arguments)}var u="x-api-key";function h(e,t,n){void 0===n&&(n={});var{api_host:i,token:r}=e,s=""+(i?i.replace(/\/+$/gm,""):"")+t;if(n.includeTokenQuery&&r){var a=s.includes("?")?"&":"?";s=""+s+a+"token="+r}return s}function p(e){return e.token?{[u]:e.token}:{}}function v(e){return"string"==typeof e}function g(e){return void 0===e}function f(e){return null==e}function _(e){return Array.isArray(e)}function m(e){return"function"==typeof e}var y={none:0,error:1,warn:2,info:3,debug:4},b="[vTilt]",w=new Set(["none","error","warn","info","debug"]);function C(){return"undefined"!=typeof console}function S(e){var t=e.length>0&&"string"==typeof e[0]?e[0]:"",n=t?e.slice(1):e;return[t?b+":"+t:b,...n]}var k="warn",x=!1;var T=null;function I(){return T||(T={setLevel(e,t){void 0===t&&(t=!1),k=e,t&&(x=!0)},setLevelFromRemote(e){x||e&&w.has(e)&&(k=e)},getLevel:()=>k,isLockedByInit:()=>x,debug(){if(!(y[k]<y.debug)&&C()){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];console.log(...S(t))}},info(){if(!(y[k]<y.info)&&C()){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];console.log(...S(t))}},warn(){if(!(y[k]<y.warn)&&C()){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];console.warn(...S(t))}},error(){if(!(y[k]<y.error)&&C()){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];console.error(...S(t))}}}),T}function E(e,t){void 0===t&&(t=!0);var n=void 0!==e.log_level||!!e.debug,i=function(e){return e.log_level&&w.has(e.log_level)?e.log_level:e.debug?"debug":"warn"}(e);return I().setLevel(i,t&&n),i}function A(e,t){try{return e()}catch(e){return t}}class O{constructor(){this._events=new Map,this._onceEvents=new Map}on(e,t){return this._events.has(e)||this._events.set(e,new Set),this._events.get(e).add(t),()=>{var n;null===(n=this._events.get(e))||void 0===n||n.delete(t)}}once(e,t){return this._onceEvents.has(e)||this._onceEvents.set(e,new Set),this._onceEvents.get(e).add(t),()=>{var n;null===(n=this._onceEvents.get(e))||void 0===n||n.delete(t)}}emit(e,t){var n,i;null===(n=this._events.get(e))||void 0===n||n.forEach(n=>{try{n(t)}catch(t){I().error("emitter",'error in event listener for "'+e+'":',t)}});var r=this._onceEvents.get(e);r&&(r.forEach(n=>{try{n(t)}catch(t){I().error("emitter",'error in once listener for "'+e+'":',t)}}),this._onceEvents.delete(e)),null===(i=this._events.get("*"))||void 0===i||i.forEach(n=>{try{n({event:e,payload:t})}catch(e){I().error("emitter","error in wildcard listener:",e)}})}off(e){e?(this._events.delete(e),this._onceEvents.delete(e)):(this._events.clear(),this._onceEvents.clear())}listenerCount(e){var t,n,i,r;return(null!==(n=null===(t=this._events.get(e))||void 0===t?void 0:t.size)&&void 0!==n?n:0)+(null!==(r=null===(i=this._onceEvents.get(e))||void 0===i?void 0:i.size)&&void 0!==r?r:0)}hasListeners(e){return this.listenerCount(e)>0}}var M="sdk:initialized",R="sdk:config_updated",P="sdk:remote_config_loaded",L="consent:updated",U="event:captured",D="recording:started",N="recording:stopped",B=0,H=!1,q=!1;function F(e){(B+=1)<2||(H=!0,q||(q=!0,I().warn(e,"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 j(){B=0}function W(){return H}var $="23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function z(e){for(var t=(2<<31-Math.clz32(57))-1,n=Math.ceil(1.6*t*e/57),i="";i.length<e;)for(var r=crypto.getRandomValues(new Uint8Array(n)),s=0;s<n&&i.length<e;s++){var a=r[s]&t;a<57&&(i+=$[a])}return i}var V=1048576;function G(e,t,n){if(e)if(Array.isArray(e))e.forEach((e,i)=>{t.call(n,e,i)});else for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(n,e[i],i)}function K(e,t,n,i){var{capture:r=!1,passive:s=!0}=null!=i?i:{};null==e||e.addEventListener(t,n,{capture:r,passive:s})}function J(e,t){if(!t)return e;for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}function Q(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];for(var r of n)for(var s of r)e.push(s);return e}function X(e){var t={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var i=e[n];null!=i&&""!==i&&(t[n]=i)}return t}var Y="/api/chat/widget/channels",Z=e=>"/api/chat/widget/channels/"+e+"/messages",ee=e=>"/api/chat/widget/channels/"+e+"/read",te="/api/chat/token/widget";function ne(e,t,n){return ie.apply(this,arguments)}function ie(){return(ie=c(function*(e,t,n){void 0===n&&(n={});var i=e.getConfig(),r=h(i,t);try{var s=yield fetch(r,d({},n,{headers:d({"Content-Type":"application/json"},p(i),n.headers)}));if(!s.ok)throw new Error("API error: "+s.status);return yield s.json()}catch(e){return I().error("chat","API request failed:",e),null}})).apply(this,arguments)}var re="rich_format",se="markdown",ae=/^[a-zA-Z0-9_-]{1,64}$/;function oe(e){return"user"===e.sender_type?function(e){var t;return"html"===e.content_type||(null===(t=e.metadata)||void 0===t?void 0:t[re])===se}(e):"ai"===e.sender_type||"agent"===e.sender_type}function le(e,t){var n,i=function(e){return"string"==typeof e?{raw:e,format:"text"}:"markdown"in e?{raw:e.markdown,format:"markdown"}:"html"in e?{raw:e.html,format:"html"}:"text"in e?{raw:e.text,format:"text"}:null}(e);if(!i)return null;var r="string"==typeof e?null!==(n=null==t?void 0:t.format)&&void 0!==n?n:"text":i.format,s=i.raw.trim();if(!s)return null;var a={};if(null==t?void 0:t.source){var o=function(e){var t=e.trim();if(ae.test(t))return t}(t.source);o&&(a.message_source=o)}return"html"===r?{content:s,content_type:"html",metadata:a}:"markdown"===r?(a[re]=se,{content:s,content_type:"text",metadata:a}):{content:s,content_type:"text",metadata:a}}var ce="$channel_message";class de{constructor(){this._widgets=new Map}register(e){this._widgets.has(e.type)||this._widgets.set(e.type,e)}get(e){return this._widgets.get(e)}getAll(){return Array.from(this._widgets.values())}getToolDefinitions(){var e={};for(var t of this._widgets.values())e[t.type]={description:t.toolDescription,parameters:t.parameters};return e}}var ue,he,pe,ve,ge,fe,_e,me,ye,be,we,Ce,Se,ke,xe,Te={},Ie=[],Ee=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ae=Array.isArray;function Oe(e,t){for(var n in t)e[n]=t[n];return e}function Me(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Re(e,t,n){var i,r,s,a={};for(s in t)"key"==s?i=t[s]:"ref"==s?r=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?ue.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return Pe(e,a,i,r,null)}function Pe(e,t,n,i,r){var s={type:e,props:t,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++pe:r,__i:-1,__u:0};return null==r&&null!=he.vnode&&he.vnode(s),s}function Le(e){return e.children}function Ue(e,t){this.props=e,this.context=t}function De(e,t){if(null==t)return e.__?De(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?De(e):null}function Ne(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,i=[],r=[],s=Oe({},t);s.__v=t.__v+1,he.vnode&&he.vnode(s),Ke(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,i,null==n?De(t):n,!!(32&t.__u),r),s.__v=t.__v,s.__.__k[s.__i]=s,Qe(i,s,r),t.__e=t.__=null,s.__e!=n&&Be(s)}}function Be(e){if(null!=(e=e.__)&&null!=e.__c)return e.__e=e.__c.base=null,e.__k.some(function(t){if(null!=t&&null!=t.__e)return e.__e=e.__c.base=t.__e}),Be(e)}function He(e){(!e.__d&&(e.__d=!0)&&ge.push(e)&&!qe.__r++||fe!=he.debounceRendering)&&((fe=he.debounceRendering)||_e)(qe)}function qe(){try{for(var e,t=1;ge.length;)ge.length>t&&ge.sort(me),e=ge.shift(),t=ge.length,Ne(e)}finally{ge.length=qe.__r=0}}function Fe(e,t,n,i,r,s,a,o,l,c,d){var u,h,p,v,g,f,_,m=i&&i.__k||Ie,y=t.length;for(l=function(e,t,n,i,r){var s,a,o,l,c,d=n.length,u=d,h=0;for(e.__k=new Array(r),s=0;s<r;s++)null!=(a=t[s])&&"boolean"!=typeof a&&"function"!=typeof a?("string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?a=e.__k[s]=Pe(null,a,null,null,null):Ae(a)?a=e.__k[s]=Pe(Le,{children:a},null,null,null):void 0===a.constructor&&a.__b>0?a=e.__k[s]=Pe(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[s]=a,l=s+h,a.__=e,a.__b=e.__b+1,o=null,-1!=(c=a.__i=$e(a,n,l,u))&&(u--,(o=n[c])&&(o.__u|=2)),null==o||null==o.__v?(-1==c&&(r>d?h--:r<d&&h++),"function"!=typeof a.type&&(a.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,a.__u|=4))):e.__k[s]=null;if(u)for(s=0;s<d;s++)null!=(o=n[s])&&!(2&o.__u)&&(o.__e==i&&(i=De(o)),et(o,o));return i}(n,t,m,l,y),u=0;u<y;u++)null!=(p=n.__k[u])&&(h=-1!=p.__i&&m[p.__i]||Te,p.__i=u,f=Ke(e,p,h,r,s,a,o,l,c,d),v=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&Ze(h.ref,null,p),d.push(p.ref,p.__c||v,p)),null==g&&null!=v&&(g=v),(_=!!(4&p.__u))||h.__k===p.__k?(l=je(p,l,e,_),_&&h.__e&&(h.__e=null)):"function"==typeof p.type&&void 0!==f?l=f:v&&(l=v.nextSibling),p.__u&=-7);return n.__e=g,l}function je(e,t,n,i){var r,s;if("function"==typeof e.type){for(r=e.__k,s=0;r&&s<r.length;s++)r[s]&&(r[s].__=e,t=je(r[s],t,n,i));return t}e.__e!=t&&(i&&(t&&e.type&&!t.parentNode&&(t=De(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function We(e,t){return t=t||[],null==e||"boolean"==typeof e||(Ae(e)?e.some(function(e){We(e,t)}):t.push(e)),t}function $e(e,t,n,i){var r,s,a,o=e.key,l=e.type,c=t[n],d=null!=c&&!(2&c.__u);if(null===c&&null==o||d&&o==c.key&&l==c.type)return n;if(i>(d?1:0))for(r=n-1,s=n+1;r>=0||s<t.length;)if(null!=(c=t[a=r>=0?r--:s++])&&!(2&c.__u)&&o==c.key&&l==c.type)return a;return-1}function ze(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||Ee.test(t)?n:n+"px"}function Ve(e,t,n,i,r){var s,a;e:if("style"==t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof i&&(e.style.cssText=i=""),i)for(t in i)n&&t in n||ze(e.style,t,"");if(n)for(t in n)i&&n[t]==i[t]||ze(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])s=t!=(t=t.replace(Ce,"$1")),a=t.toLowerCase(),t=a in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?i?n[we]=i[we]:(n[we]=Se,e.addEventListener(t,s?xe:ke,s)):e.removeEventListener(t,s?xe:ke,s);else{if("http://www.w3.org/2000/svg"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function Ge(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t[be])t[be]=Se++;else if(t[be]<n[we])return;return n(he.event?he.event(t):t)}}}function Ke(e,t,n,i,r,s,a,o,l,c){var d,u,h,p,v,g,f,_,m,y,b,w,C,S,k,x=t.type;if(void 0!==t.constructor)return null;128&n.__u&&(l=!!(32&n.__u),s=[o=t.__e=n.__e]),(d=he.__b)&&d(t);e:if("function"==typeof x)try{if(_=t.props,m=x.prototype&&x.prototype.render,y=(d=x.contextType)&&i[d.__c],b=d?y?y.props.value:d.__:i,n.__c?f=(u=t.__c=n.__c).__=u.__E:(m?t.__c=u=new x(_,b):(t.__c=u=new Ue(_,b),u.constructor=x,u.render=tt),y&&y.sub(u),u.state||(u.state={}),u.__n=i,h=u.__d=!0,u.__h=[],u._sb=[]),m&&null==u.__s&&(u.__s=u.state),m&&null!=x.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=Oe({},u.__s)),Oe(u.__s,x.getDerivedStateFromProps(_,u.__s))),p=u.props,v=u.state,u.__v=t,h)m&&null==x.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),m&&null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(m&&null==x.getDerivedStateFromProps&&_!==p&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(_,b),t.__v==n.__v||!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(_,u.__s,b)){t.__v!=n.__v&&(u.props=_,u.state=u.__s,u.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(e){e&&(e.__=t)}),Ie.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&a.push(u);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(_,u.__s,b),m&&null!=u.componentDidUpdate&&u.__h.push(function(){u.componentDidUpdate(p,v,g)})}if(u.context=b,u.props=_,u.__P=e,u.__e=!1,w=he.__r,C=0,m)u.state=u.__s,u.__d=!1,w&&w(t),d=u.render(u.props,u.state,u.context),Ie.push.apply(u.__h,u._sb),u._sb=[];else do{u.__d=!1,w&&w(t),d=u.render(u.props,u.state,u.context),u.state=u.__s}while(u.__d&&++C<25);u.state=u.__s,null!=u.getChildContext&&(i=Oe(Oe({},i),u.getChildContext())),m&&!h&&null!=u.getSnapshotBeforeUpdate&&(g=u.getSnapshotBeforeUpdate(p,v)),S=null!=d&&d.type===Le&&null==d.key?Xe(d.props.children):d,o=Fe(e,Ae(S)?S:[S],t,n,i,r,s,a,o,l,c),u.base=t.__e,t.__u&=-161,u.__h.length&&a.push(u),f&&(u.__E=u.__=null)}catch(e){if(t.__v=null,l||null!=s)if(e.then){for(t.__u|=l?160:128;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;s[s.indexOf(o)]=null,t.__e=o}else{for(k=s.length;k--;)Me(s[k]);Je(t)}else t.__e=n.__e,t.__k=n.__k,e.then||Je(t);he.__e(e,t,n)}else null==s&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):o=t.__e=Ye(n.__e,t,n,i,r,s,a,l,c);return(d=he.diffed)&&d(t),128&t.__u?void 0:o}function Je(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Je))}function Qe(e,t,n){for(var i=0;i<n.length;i++)Ze(n[i],n[++i],n[++i]);he.__c&&he.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){he.__e(e,t.__v)}})}function Xe(e){return"object"!=typeof e||null==e||e.__b>0?e:Ae(e)?e.map(Xe):void 0!==e.constructor?null:Oe({},e)}function Ye(e,t,n,i,r,s,a,o,l){var c,d,u,h,p,v,g,f=n.props||Te,_=t.props,m=t.type;if("svg"==m?r="http://www.w3.org/2000/svg":"math"==m?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=s)for(c=0;c<s.length;c++)if((p=s[c])&&"setAttribute"in p==!!m&&(m?p.localName==m:3==p.nodeType)){e=p,s[c]=null;break}if(null==e){if(null==m)return document.createTextNode(_);e=document.createElementNS(r,m,_.is&&_),o&&(he.__m&&he.__m(t,s),o=!1),s=null}if(null==m)f===_||o&&e.data==_||(e.data=_);else{if(s="textarea"==m&&null!=_.defaultValue?null:s&&ue.call(e.childNodes),!o&&null!=s)for(f={},c=0;c<e.attributes.length;c++)f[(p=e.attributes[c]).name]=p.value;for(c in f)p=f[c],"dangerouslySetInnerHTML"==c?u=p:"children"==c||c in _||"value"==c&&"defaultValue"in _||"checked"==c&&"defaultChecked"in _||Ve(e,c,null,p,r);for(c in _)p=_[c],"children"==c?h=p:"dangerouslySetInnerHTML"==c?d=p:"value"==c?v=p:"checked"==c?g=p:o&&"function"!=typeof p||f[c]===p||Ve(e,c,p,f[c],r);if(d)o||u&&(d.__html==u.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(u&&(e.innerHTML=""),Fe("template"==t.type?e.content:e,Ae(h)?h:[h],t,n,i,"foreignObject"==m?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:n.__k&&De(n,0),o,l),null!=s)for(c=s.length;c--;)Me(s[c]);o&&"textarea"!=m||(c="value","progress"==m&&null==v?e.removeAttribute("value"):null!=v&&(v!==e[c]||"progress"==m&&!v||"option"==m&&v!=f[c])&&Ve(e,c,v,f[c],r),c="checked",null!=g&&g!=e[c]&&Ve(e,c,g,f[c],r))}return e}function Ze(e,t,n){try{if("function"==typeof e){var i="function"==typeof e.__u;i&&e.__u(),i&&null==t||(e.__u=e(t))}else e.current=t}catch(e){he.__e(e,n)}}function et(e,t,n){var i,r;if(he.unmount&&he.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||Ze(i,null,t)),null!=(i=e.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(e){he.__e(e,t)}i.base=i.__P=null}if(i=e.__k)for(r=0;r<i.length;r++)i[r]&&et(i[r],t,n||"function"!=typeof e.type);n||Me(e.__e),e.__c=e.__=e.__e=void 0}function tt(e,t,n){return this.constructor(e,n)}function nt(e,t,n){var i,r,s;t==document&&(t=document.documentElement),he.__&&he.__(e,t),i=!1?null:t.__k,r=[],s=[],Ke(t,e=t.__k=Re(Le,null,[e]),i||Te,Te,t.namespaceURI,i?null:t.firstChild?ue.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,s),Qe(r,e,s)}ue=Ie.slice,he={__e:function(e,t,n,i){for(var r,s,a;t=t.__;)if((r=t.__c)&&!r.__)try{if((s=r.constructor)&&null!=s.getDerivedStateFromError&&(r.setState(s.getDerivedStateFromError(e)),a=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(e,i||{}),a=r.__d),a)return r.__E=r}catch(t){e=t}throw e}},pe=0,ve=function(e){return null!=e&&void 0===e.constructor},Ue.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=Oe({},this.state),"function"==typeof e&&(e=e(Oe({},n),this.props)),e&&Oe(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),He(this))},Ue.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),He(this))},Ue.prototype.render=Le,ge=[],_e="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,me=function(e,t){return e.__v.__b-t.__v.__b},qe.__r=0,ye=Math.random().toString(8),be="__d"+ye,we="__a"+ye,Ce=/(PointerCapture)$|Capture$/i,Se=0,ke=Ge(!1),xe=Ge(!0);var it=0;function rt(e,t,n,i,r,s){t||(t={});var a,o,l=t;if("ref"in l)for(o in l={},t)"ref"==o?a=t[o]:l[o]=t[o];var c={type:e,props:l,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--it,__i:-1,__u:0,__source:r,__self:s};if("function"==typeof e&&(a=e.defaultProps))for(o in a)void 0===l[o]&&(l[o]=a[o]);return he.vnode&&he.vnode(c),c}var st,at,ot,lt,ct=0,dt=[],ut=he,ht=ut.__b,pt=ut.__r,vt=ut.diffed,gt=ut.__c,ft=ut.unmount,_t=ut.__;function mt(e,t){ut.__h&&ut.__h(at,e,ct||t),ct=0;var n=at.__H||(at.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function yt(e){return ct=1,function(e,t,n){var i=mt(st++,2);if(i.t=e,!i.__c&&(i.__=[n?n(t):Ot(void 0,t),function(e){var t=i.__N?i.__N[0]:i.__[0],n=i.t(t,e);t!==n&&(i.__N=[n,i.__[1]],i.__c.setState({}))}],i.__c=at,!at.__f)){var r=function(e,t,n){if(!i.__c.__H)return!0;var r=i.__c.__H.__.filter(function(e){return e.__c});if(r.every(function(e){return!e.__N}))return!s||s.call(this,e,t,n);var a=i.__c.props!==e;return r.some(function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(a=!0)}}),s&&s.call(this,e,t,n)||a};at.__f=!0;var s=at.shouldComponentUpdate,a=at.componentWillUpdate;at.componentWillUpdate=function(e,t,n){if(this.__e){var i=s;s=void 0,r(e,t,n),s=i}a&&a.call(this,e,t,n)},at.shouldComponentUpdate=r}return i.__N||i.__}(Ot,e)}function bt(e,t){var n=mt(st++,3);!ut.__s&&At(n.__H,t)&&(n.__=e,n.u=t,at.__H.__h.push(n))}function wt(e){return ct=5,Ct(function(){return{current:e}},[])}function Ct(e,t){var n=mt(st++,7);return At(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function St(e,t){return ct=8,Ct(function(){return e},t)}function kt(){for(var e;e=dt.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(It),t.__h.some(Et),t.__h=[]}catch(n){t.__h=[],ut.__e(n,e.__v)}}}ut.__b=function(e){at=null,ht&&ht(e)},ut.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),_t&&_t(e,t)},ut.__r=function(e){pt&&pt(e),st=0;var t=(at=e.__c).__H;t&&(ot===at?(t.__h=[],at.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.some(It),t.__h.some(Et),t.__h=[],st=0)),ot=at},ut.diffed=function(e){vt&&vt(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==dt.push(t)&&lt===ut.requestAnimationFrame||((lt=ut.requestAnimationFrame)||Tt)(kt)),t.__H.__.some(function(e){e.u&&(e.__H=e.u),e.u=void 0})),ot=at=null},ut.__c=function(e,t){t.some(function(e){try{e.__h.some(It),e.__h=e.__h.filter(function(e){return!e.__||Et(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],ut.__e(n,e.__v)}}),gt&&gt(e,t)},ut.unmount=function(e){ft&&ft(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(e){try{It(e)}catch(e){t=e}}),n.__H=void 0,t&&ut.__e(t,n.__v))};var xt="function"==typeof requestAnimationFrame;function Tt(e){var t,n=function(){clearTimeout(i),xt&&cancelAnimationFrame(t),setTimeout(e)},i=setTimeout(n,35);xt&&(t=requestAnimationFrame(n))}function It(e){var t=at,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),at=t}function Et(e){var t=at;e.__c=e.__(),at=t}function At(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Ot(e,t){return"function"==typeof t?t(e):t}var Mt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function Rt(e){var{prompt:t,ctx:n}=e,[i,r]=yt(""),[s,a]=yt(""),[o,l]=yt(!1),d=Mt.test(s.trim())&&!o,u=function(){var e=c(function*(){if(d){l(!0);try{yield n.dispatch("submit",{email:s.trim(),name:i.trim()})}finally{l(!1)}}});return function(){return e.apply(this,arguments)}}();return rt("div",{class:"vt-widget",children:[rt("p",{children:t}),rt("div",{style:"display: flex; flex-direction: column; gap: 8px;",children:[rt("input",{type:"text",class:"vt-widget-input",placeholder:"Your name",value:i,onInput:e=>r(e.currentTarget.value),disabled:o}),rt("div",{style:"display: flex; gap: 8px; align-items: center;",children:[rt("input",{type:"email",class:"vt-widget-input",style:"flex: 1; min-width: 0; margin: 0;",placeholder:"your@email.com",value:s,onInput:e=>a(e.currentTarget.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),u())},disabled:o}),rt("button",{type:"button",class:"vt-widget-btn","data-style":"outline",onClick:()=>{u()},disabled:!d,children:"Submit"})]})]})]})}var Pt={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:(e,t)=>rt(Rt,{prompt:"string"==typeof e.prompt?e.prompt:"What's your name and email?",ctx:t}),onAction:(e,t,n)=>c(function*(){if("submit"!==e)return{};var i="string"==typeof t.email?t.email.trim():"";if(!i||!Mt.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 a=yield fetch(r,{method:"POST",headers:s,body:JSON.stringify({widget_type:"collect_email",action:"submit",data:{email:i,name:"string"==typeof t.name?t.name.trim():""},channel_id:n.channelId,distinct_id:n.distinctId,message_id:n.messageId})});return{success:!!(yield a.json()).success}}catch(e){return{}}})()},Lt={fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function Ut(e){return rt("svg",d({width:24,height:24,viewBox:"0 0 24 24"},Lt,e,{children:rt("path",{d:"M18 6L6 18M6 6l12 12"})}))}function Dt(e){return rt("svg",d({width:24,height:24,viewBox:"0 0 24 24"},Lt,e,{children:rt("path",{d:"M15 18l-6-6 6-6"})}))}function Nt(e){return rt("svg",d({width:16,height:16,viewBox:"0 0 24 24",fill:"currentColor"},e,{children:rt("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}))}function Bt(e){return rt("svg",d({width:28,height:28,viewBox:"0 0 28 28",fill:"white"},e,{children:rt("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 Ht(e){return rt("svg",d({width:22,height:22,viewBox:"0 0 24 24",fill:"currentColor"},e,{children:rt("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 qt(e){return rt("svg",d({width:22,height:22,viewBox:"0 0 24 24",fill:"currentColor"},e,{children:rt("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 Ft(e){return rt("svg",d({width:36,height:36,viewBox:"0 0 24 24",fill:"white"},e,{children:rt("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 jt(e){return rt("svg",d({width:16,height:16,viewBox:"0 0 24 24"},Lt,e,{children:[rt("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),rt("circle",{cx:"12",cy:"7",r:"4"})]}))}function Wt(e){var{prompt:t,ctx:n}=e,[i,r]=yt(!1),s=function(){var e=c(function*(){if(!i){r(!0);try{yield n.dispatch("escalate",{})}finally{r(!1)}}});return function(){return e.apply(this,arguments)}}();return rt("div",{class:"vt-widget",children:[rt("p",{children:t}),rt("button",{type:"button",class:"vt-widget-btn","data-style":"outline",onClick:()=>{s()},disabled:i,children:[rt(jt,{}),"Connect with a person"]})]})}var $t={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:(e,t)=>rt(Wt,{prompt:"string"==typeof e.prompt?e.prompt:"Would you like me to connect you with a team member?",ctx:t}),onAction:(e,t,n)=>c(function*(){if("escalate"!==e)return{};var t=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(t,{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(e){return{}}})()},zt=Symbol.for("preact-signals");function Vt(){if(Xt>1)Xt--;else{var e,t=!1;for(!function(){var e=Zt;for(Zt=void 0;void 0!==e;)e.S.v===e.v&&(e.S.i=e.i),e=e.o}();void 0!==Qt;){var n=Qt;for(Qt=void 0,Yt++;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){t||(e=n,t=!0)}n=i}}if(Yt=0,Xt--,t)throw e}}var Gt=void 0;function Kt(e){var t=Gt;Gt=void 0;try{return e()}finally{Gt=t}}var Jt,Qt=void 0,Xt=0,Yt=0,Zt=void 0,en=0;function tn(e){if(void 0!==Gt){var t=e.n;if(void 0===t||t.t!==Gt)return t={i:0,S:e,p:Gt.s,n:void 0,t:Gt,e:void 0,x:void 0,r:t},void 0!==Gt.s&&(Gt.s.n=t),Gt.s=t,e.n=t,32&Gt.f&&e.S(t),t;if(-1===t.i)return t.i=0,void 0!==t.n&&(t.n.p=t.p,void 0!==t.p&&(t.p.n=t.n),t.p=Gt.s,t.n=void 0,Gt.s.n=t,Gt.s=t),t}}function nn(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=null==t?void 0:t.watched,this.Z=null==t?void 0:t.unwatched,this.name=null==t?void 0:t.name}function rn(e,t){return new nn(e,t)}function sn(e){for(var t=e.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function an(e){for(var t=e.s;void 0!==t;t=t.n){var n=t.S.n;if(void 0!==n&&(t.r=n),t.S.n=t,t.i=-1,void 0===t.n){e.s=t;break}}}function on(e){for(var t=e.s,n=void 0;void 0!==t;){var i=t.p;-1===t.i?(t.S.U(t),void 0!==i&&(i.n=t.n),void 0!==t.n&&(t.n.p=i)):n=t,t.S.n=t.r,void 0!==t.r&&(t.r=void 0),t=i}e.s=n}function ln(e,t){nn.call(this,void 0),this.x=e,this.s=void 0,this.g=en-1,this.f=4,this.W=null==t?void 0:t.watched,this.Z=null==t?void 0:t.unwatched,this.name=null==t?void 0:t.name}function cn(e,t){return new ln(e,t)}function dn(e){var t=e.m;if(e.m=void 0,"function"==typeof t){Xt++;var n=Gt;Gt=void 0;try{t()}catch(t){throw e.f&=-2,e.f|=8,un(e),t}finally{Gt=n,Vt()}}}function un(e){for(var t=e.s;void 0!==t;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,dn(e)}function hn(e){if(Gt!==this)throw new Error("Out-of-order effect");on(this),Gt=e,this.f&=-2,8&this.f&&un(this),Vt()}function pn(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=null==t?void 0:t.name}function vn(e,t){var n=new pn(e,t);try{n.c()}catch(e){throw n.d(),e}var i=n.d.bind(n);return i[Symbol.dispose]=i,i}function gn(e,t){he[e]=t.bind(null,he[e]||function(){})}function fn(e){if(Jt){var t=Jt;Jt=void 0,t()}Jt=e&&e.S()}function _n(e){var t=this,n=e.data,i=function(e){return Ct(function(){return rn(e)},[])}(n);i.value=n;var r=Ct(function(){for(var e=t.__v;e=e.__;)if(e.__c){e.__c.__$f|=4;break}return t.__$u.c=function(){var e,n=t.__$u.S(),i=r.value;n(),ve(i)||3!==(null==(e=t.base)?void 0:e.nodeType)?(t.__$f|=1,t.setState({})):t.base.data=i},cn(function(){var e=i.value.value;return 0===e?0:!0===e?"":e||""})},[]);return r.value}function mn(e,t,n,i){var r=t in e&&void 0===e.ownerSVGElement,s=rn(n);return{o:function(e,t){s.value=e,i=t},d:vn(function(){var n=s.value.value;i[t]!==n&&(i[t]=n,r?e[t]=n:n?e.setAttribute(t,n):e.removeAttribute(t))})}}nn.prototype.brand=zt,nn.prototype.h=function(){return!0},nn.prototype.S=function(e){var t=this,n=this.t;n!==e&&void 0===e.e&&(e.x=n,this.t=e,void 0!==n?n.e=e:Kt(function(){var e;null==(e=t.W)||e.call(t)}))},nn.prototype.U=function(e){var t=this;if(void 0!==this.t){var n=e.e,i=e.x;void 0!==n&&(n.x=i,e.e=void 0),void 0!==i&&(i.e=n,e.x=void 0),e===this.t&&(this.t=i,void 0===i&&Kt(function(){var e;null==(e=t.Z)||e.call(t)}))}},nn.prototype.subscribe=function(e){var t=this;return vn(function(){var n=t.value,i=Gt;Gt=void 0;try{e(n)}finally{Gt=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 e=this;return Kt(function(){return e.value})},Object.defineProperty(nn.prototype,"value",{get:function(){var e=tn(this);return void 0!==e&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(Yt>100)throw new Error("Cycle detected");!function(e){0!==Xt&&0===Yt&&0!==e.l&&(e.l=0,Zt={S:e,v:e.v,i:e.i,o:Zt})}(this),this.v=e,this.i++,en++,Xt++;try{for(var t=this.t;void 0!==t;t=t.x)t.t.N()}finally{Vt()}}}}),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===en)return!0;if(this.g=en,this.f|=1,this.i>0&&!sn(this))return this.f&=-2,!0;var e=Gt;try{an(this),Gt=this;var t=this.x();(16&this.f||this.v!==t||0===this.i)&&(this.v=t,this.f&=-17,this.i++)}catch(e){this.v=e,this.f|=16,this.i++}return Gt=e,on(this),this.f&=-2,!0},ln.prototype.S=function(e){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t)}nn.prototype.S.call(this,e)},ln.prototype.U=function(e){if(void 0!==this.t&&(nn.prototype.U.call(this,e),void 0===this.t)){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t)}},ln.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;void 0!==e;e=e.x)e.t.N()}},Object.defineProperty(ln.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=tn(this);if(this.h(),void 0!==e&&(e.i=this.i),16&this.f)throw this.v;return this.v}}),pn.prototype.c=function(){var e=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();"function"==typeof t&&(this.m=t)}finally{e()}},pn.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,dn(this),an(this),Xt++;var e=Gt;return Gt=this,hn.bind(this,e)},pn.prototype.N=function(){2&this.f||(this.f|=2,this.u=Qt,Qt=this)},pn.prototype.d=function(){this.f|=8,1&this.f||un(this)},pn.prototype.dispose=function(){this.d()},_n.displayName="_st",Object.defineProperties(nn.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:_n},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),gn("__b",function(e,t){if("string"==typeof t.type){var n,i=t.props;for(var r in i)if("children"!==r){var s=i[r];s instanceof nn&&(n||(t.__np=n={}),n[r]=s,i[r]=s.peek())}}e(t)}),gn("__r",function(e,t){e(t),fn();var n,i=t.__c;i&&(i.__$f&=-2,void 0===(n=i.__$u)&&(i.__$u=n=function(){var e;return vn(function(){e=this}),e.c=function(){i.__$f|=1,i.setState({})},e}())),fn(n)}),gn("__e",function(e,t,n,i){fn(),e(t,n,i)}),gn("diffed",function(e,t){var n;if(fn(),"string"==typeof t.type&&(n=t.__e)){var i=t.__np,r=t.props;if(i){var s=n.U;if(s)for(var a in s){var o=s[a];void 0===o||a in i||(o.d(),s[a]=void 0)}else n.U=s={};for(var l in i){var c=s[l],d=i[l];void 0===c?(c=mn(n,l,d,r),s[l]=c):c.o(d,r)}}}e(t)}),gn("unmount",function(e,t){if("string"==typeof t.type){var n=t.__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 a=t.__c;if(a){var o=a.__$u;o&&(a.__$u=void 0,o.d())}}e(t)}),gn("__h",function(e,t,n,i){(i<3||9===i)&&(t.__$f|=2),e(t,n,i)}),Ue.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,i=n&&void 0!==n.s;for(var r in t)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 e)if("__source"!==s&&e[s]!==this.props[s])return!0;for(var a in this.props)if(!(a in e))return!0;return!1};var yn={primaryColor:"#7B68EE",fontFamily:"'Inter var', 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",borderRadius:"12px"};class bn{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(d({},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._messagesCache=new Map,this.isConnected=cn(()=>"connected"===this.connectionState.value),this.polledUnreadTotal=rn(null),this.unreadCount=cn(()=>this.isOpen.value||null===this.polledUnreadTotal.value?this.channels.value.reduce((e,t)=>e+(t.unread_count||0),0):this.polledUnreadTotal.value),this.connectionBanner=cn(()=>{var e=this.connectionState.value;return"suspended"===e?"reconnecting":"failed"===e?"failed":"none"}),this.realtimeReady=cn(()=>{var e=this.channel.value;return!!e&&("connected"===this.connectionState.value&&this.realtimeAttached.value&&this.realtimeChannelId.value===e.id)})}setMessages(e){this.messages.value=e}patchChannelSummary(e,t){var n=this.channels.value.findIndex(t=>t.id===e);if(-1!==n){var i=[...this.channels.value];i[n]=d({},i[n],t),i.sort((e,t)=>{var n=e.last_message_at||e.created_at,i=t.last_message_at||t.created_at;return new Date(i).getTime()-new Date(n).getTime()}),this.channels.value=i}}prependChannelSummary(e){this.channels.value.some(t=>t.id===e.id)||(this.channels.value=[e,...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(e,t){if(e){var n=t.filter(e=>!e.id.startsWith("temp-"));for(this._messagesCache.delete(e),this._messagesCache.set(e,n);this._messagesCache.size>bn.MESSAGES_CACHE_LIMIT;){var i=this._messagesCache.keys().next().value;if(void 0===i)break;this._messagesCache.delete(i)}}}getCachedMessages(e){if(!e)return null;var t=this._messagesCache.get(e);return t?(this._messagesCache.delete(e),this._messagesCache.set(e,t),t):null}clearMessagesCache(){this._messagesCache.clear()}}bn.MESSAGES_CACHE_LIMIT=10;var wn={bottom:20,right:20,left:20};function Cn(e,t){return void 0!==e&&Number.isFinite(e)?Math.max(0,e):t}function Sn(e){return null===e?d({},wn):{bottom:Cn(null==e?void 0:e.bottom,wn.bottom),right:Cn(null==e?void 0:e.right,wn.right),left:Cn(null==e?void 0:e.left,wn.left)}}function kn(e,t,n){e.style.bottom=n.bottom+"px","bottom-right"===t?(e.style.right=n.right+"px",e.style.left=""):(e.style.left=n.left+"px",e.style.right="")}var xn="vtilt-bubble-pos";function Tn(e){try{localStorage.setItem(xn,JSON.stringify(e))}catch(e){}}function In(e,t,n){var i=e.getBoundingClientRect(),r=i.left-t,s=i.top-n,a=window.innerWidth-e.offsetWidth-r,o=-r,l=window.innerHeight-e.offsetHeight-s,c=-s;return{x:Math.min(Math.max(t,o),a),y:Math.min(Math.max(n,c),l)}}function En(e,t,n){e.style.transform="translate3d("+t+"px, "+n+"px, 0)"}function An(e,t){var n,i=null!==(n=null==t?void 0:t.handle)&&void 0!==n?n:e,r=null==t?void 0:t.onPositionChange,s=0,a=0,o=0,l=0,c=0,d=0,u=!1,h=!1,p=function(){try{var e=localStorage.getItem(xn);if(!e)return null;var t=JSON.parse(e);if("number"==typeof t.x&&"number"==typeof t.y)return t}catch(e){}return null}();if(p){s=p.x,a=p.y;var v=e.style.transition;e.style.transition="none",En(e,s,a);var g=In(e,s,a);s=g.x,a=g.y,En(e,s,a),e.offsetHeight,e.style.transition=v}i.style.cursor="grab",i.style.touchAction="none";var f=t=>{0===t.button&&(u=!0,h=!1,o=t.clientX,l=t.clientY,c=s,d=a,i.setPointerCapture(t.pointerId),i.style.cursor="grabbing",e.style.transition="none")},_=t=>{if(u){var n=t.clientX-o,i=t.clientY-l;if(!(!h&&Math.abs(n)<5&&Math.abs(i)<5)){h=!0;var p={x:c+n,y:d+i},v=In(e,p.x,p.y);s=v.x,a=v.y,En(e,s,a),null==r||r()}}},m=()=>{u&&(u=!1,i.style.cursor="grab",e.style.transition="",h&&(Tn({x:s,y:a}),null==r||r()))},y=e=>{h&&(e.stopPropagation(),e.preventDefault(),h=!1)},b=()=>{var t=s,n=a,i=In(e,s,a);s=i.x,a=i.y,En(e,s,a),t===s&&n===a||Tn({x:s,y:a}),null==r||r()};return i.addEventListener("pointerdown",f),i.addEventListener("pointermove",_),i.addEventListener("pointerup",m),i.addEventListener("pointercancel",m),i.addEventListener("click",y,!0),window.addEventListener("resize",b),{destroy(){i.removeEventListener("pointerdown",f),i.removeEventListener("pointermove",_),i.removeEventListener("pointerup",m),i.removeEventListener("pointercancel",m),i.removeEventListener("click",y,!0),window.removeEventListener("resize",b)}}}function On(e){var{store:t,controller:n,bubbleRef:i}=e,r=t.unreadCount.value;return rt("button",{type:"button",class:"vt-bubble",ref:i,onClick:()=>n.toggle(),"aria-label":"Open chat",children:[rt(Bt,{}),rt("span",{class:"vt-bubble-badge","data-visible":r>0?"true":"false",children:r>99?"99+":r})]})}function Mn(e){var{channel:t,onSelect:n}=e,i=t.unread_count>0,r=function(e){var t=new Date(e),n=Date.now()-t.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 t.toLocaleDateString()}(t.last_message_at||t.created_at),s=t.last_message_preview||"No messages yet",a="user"===t.last_message_sender?"You: ":"",o="closed"===t.status?" · Closed":"";return rt("button",{type:"button",class:"vt-channel-item","data-channel-id":t.id,onClick:()=>n(t.id),children:[rt("div",{class:"vt-channel-avatar","data-mode":t.ai_mode?"ai":"support",children:t.ai_mode?rt(Ht,{width:24,height:24}):rt(qt,{width:24,height:24})}),rt("div",{class:"vt-channel-body",children:[rt("div",{class:"vt-channel-row",children:[rt("div",{class:"vt-channel-name","data-unread":i?"true":"false",children:t.ai_mode?"AI Assistant":"Support"}),rt("div",{class:"vt-channel-time",children:r})]}),rt("div",{class:"vt-channel-row",children:[rt("div",{class:"vt-channel-preview","data-unread":i?"true":"false",children:[a,s,o]}),i&&rt("div",{class:"vt-channel-unread",children:t.unread_count>99?"99+":t.unread_count})]})]})]})}function Rn(){return rt("div",{style:"flex: 1; overflow: hidden;",children:[rt(Pn,{}),rt(Pn,{}),rt(Pn,{}),rt(Pn,{})]})}function Pn(){return rt("div",{style:"padding: 14px 16px; display: flex; align-items: center; gap: 12px; border-bottom: 1px solid var(--vtilt-border-light); background: white;",children:[rt("div",{class:"vt-skeleton-circle",style:"width: 48px; height: 48px; flex-shrink: 0;"}),rt("div",{style:"flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8px;",children:[rt("div",{class:"vt-skeleton",style:"height: 12px; width: 40%;"}),rt("div",{class:"vt-skeleton",style:"height: 10px; width: 80%;"})]})]})}function Ln(){return rt(Le,{children:[rt(Un,{direction:"in",widthPct:62,metaPx:92,height:40}),rt(Un,{direction:"out",widthPct:42,metaPx:56,height:40}),rt(Un,{direction:"in",widthPct:78,metaPx:76,height:60})]})}function Un(e){var{direction:t,widthPct:n,metaPx:i,height:r}=e;return rt("div","in"===t?{style:"display: flex; gap: 10px; align-items: flex-end;",children:[rt("div",{class:"vt-skeleton-circle",style:"width: 32px; height: 32px; flex-shrink: 0;"}),rt("div",{style:"display: flex; flex-direction: column; align-items: flex-start; min-width: 0; max-width: 85%;",children:[rt("div",{class:"vt-skeleton",style:"width: "+n+"%; min-width: 96px; height: "+r+"px; border-radius: 20px 20px 20px 4px;"}),rt("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:[rt("div",{class:"vt-skeleton",style:"width: "+n+"%; min-width: 80px; max-width: 80%; height: "+r+"px; border-radius: 20px 20px 4px 20px;"}),rt("div",{class:"vt-skeleton",style:"height: 10px; width: "+i+"px; margin-top: 8px; margin-right: 6px; border-radius: 4px;"})]})}function Dn(e){var{store:t,controller:n}=e,i=t.channels.value,r=t.isLoading.value;return 0===i.length&&r?rt(Rn,{}):0===i.length?rt(Nn,{controller:n}):rt(Le,{children:[rt("div",{class:"vt-list-root",children:i.map(e=>rt(Mn,{channel:e,onSelect:e=>{n.selectChannel(e)}},e.id))}),rt("div",{class:"vt-list-footer",children:rt("button",{type:"button",class:"vt-new-channel-btn",onClick:()=>{n.createChannel()},children:["Send us a message",rt(Nt,{width:18,height:18})]})})]})}function Nn(e){var{controller:t}=e,n=t.config.greeting||"Hi! How can we help you today?";return rt("div",{class:"vt-list-empty",children:[rt("div",{class:"vt-list-empty-icon",children:rt(Ft,{})}),rt("div",{class:"vt-list-empty-title",children:n}),rt("div",{class:"vt-list-empty-subtitle",children:"Start a conversation with us"}),rt("button",{type:"button",class:"vt-new-channel-btn",style:"width: auto; padding: 14px 28px;",onClick:()=>{t.createChannel()},children:["Send us a message",rt(Nt,{width:18,height:18})]})]})}function Bn(e){var t,n,i,{store:r,controller:s}=e;if("list"===r.currentView.value)return rt("div",{class:"vt-header","data-view":"list",children:[rt("div",{class:"vt-header-title",children:"Messages"}),rt("button",{type:"button",class:"vt-iconbtn vt-header-close",onClick:()=>s.close(),"aria-label":"Close",children:rt(Ut,{})})]});var a=null===(i=null!==(n=null===(t=r.channel.value)||void 0===t?void 0:t.ai_mode)&&void 0!==n?n:s.config.aiMode)||void 0===i||i;return rt("div",{class:"vt-header","data-view":"conversation",children:[rt("button",{type:"button",class:"vt-iconbtn vt-header-back",onClick:()=>s.goToChannelList(),"aria-label":"Back",children:rt(Dt,{})}),rt("div",{class:"vt-header-avatar","data-mode":a?"ai":"support",children:rt(a?Ht:qt,{})}),rt("div",{class:"vt-header-info",children:[rt("div",{class:"vt-header-name",children:a?"AI Assistant":"Support"}),rt("div",{class:"vt-header-status",children:"Online"})]}),rt("button",{type:"button",class:"vt-iconbtn vt-header-close",onClick:()=>s.close(),"aria-label":"Close",children:rt(Ut,{})})]})}function Hn(){return rt("div",{class:"vt-closed-banner",children:"This conversation has been closed."})}function qn(e){var{store:t}=e,n=t.connectionBanner.value,i=function(e,t){var[n,i]=yt(!1);return bt(()=>{if(e){var n=setTimeout(()=>i(!0),t);return()=>clearTimeout(n)}i(!1)},[e,t]),n}("reconnecting"===n,2500),r=St(()=>{"undefined"!=typeof window&&window.location.reload()},[]);return"failed"===n?rt("div",{class:"vt-conn-banner","data-kind":"failed",role:"alert",children:[rt("span",{class:"vt-conn-banner-icon","aria-hidden":"true",children:rt("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[rt("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"}),rt("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),rt("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}),rt("span",{class:"vt-conn-banner-text",children:"Connection lost"}),rt("button",{type:"button",class:"vt-conn-banner-action",onClick:r,children:"Retry"})]}):i?rt("div",{class:"vt-conn-banner","data-kind":"reconnecting",role:"status",children:[rt("span",{class:"vt-conn-banner-dot","aria-hidden":"true"}),rt("span",{class:"vt-conn-banner-text",children:"Reconnecting"})]}):null}function Fn(e){var{store:t,controller:n}=e,[i,r]=yt(""),s=wt(null),a=null==t.channel.value,o=()=>{var e=i.trim();e&&(n.stopUserTyping(),n.sendMessage(e),r(""),s.current&&(s.current.style.height="",s.current.focus()))};return bt(()=>{s.current&&function(e){e.style.height="auto";var t=120,n=60;e.style.height=Math.min(Math.max(e.scrollHeight,n),t)+"px"}(s.current)},[i]),rt("div",{class:"vt-input-container","data-pending":a?"true":"false",children:rt("div",{class:"vt-input-box",children:[rt("textarea",{class:"vt-input-textarea",ref:s,rows:1,placeholder:a?"Starting conversation…":"Message...",autocomplete:"off",autocorrect:"on",autocapitalize:"sentences",disabled:a,value:i,onInput:e=>{var t=e.currentTarget.value;r(t),n.notifyUserTyping()},onBlur:()=>{n.stopUserTyping()},onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o())}}),rt("button",{type:"button",class:"vt-input-send","data-active":i.trim().length>0?"true":"false",disabled:0===i.trim().length||a,onClick:o,"aria-label":"Send message",children:rt(Nt,{})})]})})}function jn(e,t){for(var n in e)if("__source"!==n&&!(n in t))return!0;for(var i in t)if("__source"!==i&&e[i]!==t[i])return!0;return!1}function Wn(e,t){this.props=e,this.context=t}function $n(e,t){function n(e){var n=this.props.ref;return n!=e.ref&&n&&("function"==typeof n?n(null):n.current=null),t?!t(this.props,e)||n!=e.ref:jn(this.props,e)}function i(t){return this.shouldComponentUpdate=n,Re(e,t)}return i.displayName="Memo("+(e.displayName||e.name)+")",i.__f=i.prototype.isReactComponent=!0,i.type=e,i}(Wn.prototype=new Ue).isPureReactComponent=!0,Wn.prototype.shouldComponentUpdate=function(e,t){return jn(this.props,e)||jn(this.state,t)};var zn=he.__b;he.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),zn&&zn(e)};var Vn=he.__e;he.__e=function(e,t,n,i){if(e.then)for(var r,s=t;s=s.__;)if((r=s.__c)&&r.__c)return null==t.__e&&(t.__e=n.__e,t.__k=n.__k),r.__c(e,t);Vn(e,t,n,i)};var Gn=he.unmount;function Kn(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(e){"function"==typeof e.__c&&e.__c()}),e.__c.__H=null),null!=(e=function(e,t){for(var n in t)e[n]=t[n];return e}({},e)).__c&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(e){return Kn(e,t,n)})),e}function Jn(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(e){return Jn(e,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function Qn(){this.__u=0,this.o=null,this.__b=null}function Xn(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Yn(){this.i=null,this.l=null}he.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Gn&&Gn(e)},(Qn.prototype=new Ue).__c=function(e,t){var n=t.__c,i=this;null==i.o&&(i.o=[]),i.o.push(n);var r=Xn(i.__v),s=!1,a=function(){s||i.__z||(s=!0,n.__R=null,r?r(l):l())};n.__R=a;var o=n.__P;n.__P=null;var l=function(){if(! --i.__u){if(i.state.__a){var e=i.state.__a;i.__v.__k[0]=Jn(e,e.__c.__P,e.__c.__O)}var t;for(i.setState({__a:i.__b=null});t=i.o.pop();)t.__P=o,t.forceUpdate()}};i.__u++||32&t.__u||i.setState({__a:i.__b=i.__v.__k[0]}),e.then(a,a)},Qn.prototype.componentWillUnmount=function(){this.o=[]},Qn.prototype.render=function(e,t){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=t.__a&&Re(Le,null,e.fallback);return r&&(r.__u&=-33),[Re(Le,null,t.__a?null:e.children),r]};var Zn=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&("t"!==e.props.revealOrder[0]||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};(Yn.prototype=new Ue).__a=function(e){var t=this,n=Xn(t.__v),i=t.l.get(e);return i[0]++,function(r){var s=function(){t.props.revealOrder?(i.push(r),Zn(t,e,i)):r()};n?n(s):s()}},Yn.prototype.render=function(e){this.i=null,this.l=new Map;var t=We(e.children);e.revealOrder&&"b"===e.revealOrder[0]&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},Yn.prototype.componentDidUpdate=Yn.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Zn(e,n,t)})};var ei="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,ti=/^(?: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(e){return("undefined"!=typeof Symbol&&"symbol"==typeof Symbol()?/fil|che|rad/:/fil|che|ra/).test(e)};Ue.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(Ue.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var ai=he.event;he.event=function(e){return ai&&(e=ai(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var oi={configurable:!0,get:function(){return this.class}},li=he.vnode;he.vnode=function(e){"string"==typeof e.type&&function(e){var t=e.props,n=e.type,i={},r=-1==n.indexOf("-");for(var s in t){var a=t[s];if(!("value"===s&&"defaultValue"in t&&null==a||ri&&"children"===s&&"noscript"===n||"class"===s||"className"===s)){var o=s.toLowerCase();"defaultValue"===s&&"value"in t&&null==t.value?s="value":"download"===s&&!0===a?a="":"translate"===o&&"no"===a?a=!1:"o"===o[0]&&"n"===o[1]?"ondoubleclick"===o?s="ondblclick":"onchange"!==o||"input"!==n&&"textarea"!==n||si(t.type)?"onfocus"===o?s="onfocusin":"onblur"===o?s="onfocusout":ni.test(s)&&(s=o):o=s="oninput":r&&ti.test(s)?s=s.replace(ii,"-$&").toLowerCase():null===a&&(a=void 0),"oninput"===o&&i[s=o]&&(s="oninputCapture"),i[s]=a}}"select"==n&&(i.multiple&&Array.isArray(i.value)&&(i.value=We(t.children).forEach(function(e){e.props.selected=-1!=i.value.indexOf(e.props.value)})),null!=i.defaultValue&&(i.value=We(t.children).forEach(function(e){e.props.selected=i.multiple?-1!=i.defaultValue.indexOf(e.props.value):i.defaultValue==e.props.value}))),t.class&&!t.className?(i.class=t.class,Object.defineProperty(i,"className",oi)):t.className&&(i.class=i.className=t.className),e.props=i}(e),e.$$typeof=ei,li&&li(e)};var ci=he.__r;he.__r=function(e){ci&&ci(e),e.__c};var di=he.diffed;function ui(e,t){var n=Date.parse(e.created_at),i=Date.parse(t.created_at);return n!==i?n-i:e.id.localeCompare(t.id)}function hi(e,t){return function(e){return e.length<2?e:[...e].sort(ui)}([...e,t])}he.diffed=function(e){di&&di(e);var t=e.props,n=e.__e;null!=n&&"textarea"===e.type&&"value"in t&&t.value!==n.value&&(n.value=null==t.value?"":t.value)};var pi="chat.stream",vi=/<!--vtilt:widget:([\s\S]*?)-->/g;function gi(e){for(var t,n,i=[],r=new RegExp(vi.source,"g");null!==(n=r.exec(e));)try{var s=JSON.parse(n[1]);s.type&&i.push({type:s.type,params:null!==(t=s.params)&&void 0!==t?t:{}})}catch(e){}return i}function fi(e){return _i.apply(this,arguments)}function _i(){return _i=c(function*(e){var t,n,i,{store:r,response:s,channelId:a,tempId:o,signal:l,isActive:c,onStreamStart:u,onComplete:h}=e,p=()=>{var e;return!(null==l?void 0:l.aborted)&&(null===(e=null==c?void 0:c())||void 0===e||e)},v=s.headers.get("X-Vtilt-Message-Id"),g=s.headers.get("X-Vtilt-Message-Created-At"),f=null!==(t=null!=o?o:v)&&void 0!==t?t:"temp-ai-"+Date.now();if(p()&&(null==u||u(f),p())){var _={id:f,channel_id:a,sender_type:"ai",sender_id:null,sender_name:"AI Assistant",sender_avatar_url:null,content:"",content_type:"text",metadata:{},created_at:null!=g?g:(new Date).toISOString()};r.setMessages(hi(r.messages.value,_));var m=null===(n=s.body)||void 0===n?void 0:n.getReader();if(!m)return I().error(pi,"no response body reader available"),void mi(r,f);var y=new TextDecoder,b="",w=null,C=!0,S=()=>{if(p()){var e=r.messages.value.findIndex(e=>e.id===f);if(-1!==e){var t=[...r.messages.value];t[e]=d({},t[e],{content:b.replace(/<[^>]*$/,"")}),r.setMessages(t)}}else mi(r,f)},k=()=>{null===w&&(w=requestAnimationFrame(()=>{S(),w=null}))};try{for(;;){if(!p())return void mi(r,f);var{done:x,value:T}=yield m.read();if(x)break;var E=y.decode(T,{stream:!0});b+=E,C?(C=!1,S()):k()}if(!p())return void mi(r,f);null!==w&&(cancelAnimationFrame(w),w=null),S();var A=r.messages.value.findIndex(e=>e.id===f);if(-1!==A){var O=gi(b),M=[...r.messages.value],R=d({},null!==(i=M[A].metadata)&&void 0!==i?i:{});O.length>0&&(R._widgets=O),M[A]=d({},M[A],{content:b,metadata:R}),r.setMessages(M)}null==h||h(f)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return void mi(r,f);I().error(pi,"failed to handle streaming response:",e),mi(r,f)}finally{m.releaseLock(),null!==w&&cancelAnimationFrame(w)}}}),_i.apply(this,arguments)}function mi(e,t){var n=e.messages.value.filter(e=>e.id!==t);n.length!==e.messages.value.length&&e.setMessages(n)}var yi=/<(?:p|ul|ol|li|h[1-6]|br|div|pre|blockquote)\b/i,bi=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 wi(e){var t=e;return t=(t=(t=(t=(t=(t=t.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 Ci(e,t){for(var n=Array.from(e.children),i=0;i<n.length;){var r=n[i];if("LI"!==r.tagName)Ci(r,t),i++;else{for(var s=[],a=i;a<n.length&&"LI"===n[a].tagName;)s.push(n[a]),a++;var o=t.createElement("ul");for(var l of(e.insertBefore(o,s[0]),s))o.appendChild(l);i=a}}}function Si(e,t){if(void 0===t&&(t="text"),!e)return"";var n=e.trim();if(!n)return"";if("undefined"==typeof document)return n;var i,r,s=function(e,t){return"html"!==e&&!yi.test(t)}(t,n)?function(e){if(!e||yi.test(e))return e;for(var t=e.split("\n"),n=[],i=0;i<t.length;){var r=t[i],s=r.match(/^(#{1,6})\s+(.+)$/);if(s){var a=s[1].length;n.push("<h"+a+">"+wi(s[2])+"</h"+a+">"),i++}else if(/^[-*]\s+/.test(r)){for(var o=[];i<t.length&&/^[-*]\s+/.test(t[i]);)o.push("<li>"+wi(t[i].replace(/^[-*]\s+/,""))+"</li>"),i++;n.push("<ul>"+o.join("")+"</ul>")}else if(/^\d+\.\s+/.test(r)){for(var l=[];i<t.length&&/^\d+\.\s+/.test(t[i]);)l.push("<li>"+wi(t[i].replace(/^\d+\.\s+/,""))+"</li>"),i++;n.push("<ol>"+l.join("")+"</ol>")}else if(""!==r.trim()){for(var c=[];i<t.length&&""!==t[i].trim()&&!/^#{1,6}\s/.test(t[i])&&!/^[-*]\s+/.test(t[i])&&!/^\d+\.\s+/.test(t[i]);)c.push(wi(t[i])),i++;n.push("<p>"+c.join("<br>")+"</p>")}else i++}return n.join("")}(n):n,a=document.createElement("div");return a.innerHTML=s,i=document,(r=e=>{for(var t of Array.from(e.children))if(bi.has(t.tagName)){for(var n of Array.from(t.attributes))"A"===t.tagName&&"href"===n.name||t.removeAttribute(n.name);"A"===t.tagName&&(t.setAttribute("target","_blank"),t.setAttribute("rel","noopener noreferrer")),r(t)}else t.replaceWith(i.createTextNode(t.textContent||""))})(a),Ci(a,document),a.innerHTML}var ki=$n(function(e){var{message:t,controller:n}=e,i=function(e){var t,n=null!==(t=e.metadata)&&void 0!==t?t:{},i=n._widgets;i&&0!==i.length||(i=n.widgets);i&&0!==i.length||!e.content||(i=gi(e.content));return null!=i?i:[]}(t);return 0===i.length?null:rt(Le,{children:i.map((e,i)=>{if(e.submitted)return rt(xi,{widget:e},i);var r=n.widgets.get(e.type);if(!r)return null;var s=n.getWidgetContext(t.id,e.type);return rt("div",{children:r.render(e.params,s)},i)})})},(e,t)=>e.message===t.message&&e.controller===t.controller);function xi(e){var t,n,{widget:i}=e;if("collect_email"===i.type){var r=null!==(t=i.submittedEmail)&&void 0!==t?t:"",s=null!==(n=i.submittedName)&&void 0!==n?n:"";return rt("div",{class:"vt-widget",children:rt("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?rt("div",{class:"vt-widget",children:rt("p",{class:"vt-widget-thanks",children:"✓ A team member has been notified. They'll join shortly."})}):rt("div",{class:"vt-widget",children:rt("p",{class:"vt-widget-thanks",children:"✓ Done"})})}var Ti=$n(function(e){var{message:t,controller:n,isReadByAgent:i}=e,r="user"===t.sender_type?"out":"in",s=Ct(()=>function(e){if("user"===e.sender_type)return"";if("ai"===e.sender_type)return"AI Assistant";return e.sender_name||"Agent"}(t),[t.sender_type,t.sender_name]);return rt("div",{class:"vt-message","data-direction":r,children:[rt("div",{class:"vt-message-row",children:["in"===r&&rt(Ei,{senderType:t.sender_type}),rt(Ii,{message:t})]}),rt(ki,{message:t,controller:n}),rt("div",{class:"vt-message-meta",children:[s?rt("span",{children:s}):null,s?rt("span",{children:" · "}):null,rt("time",{children:Oi(t.created_at)}),"out"===r?rt(Ai,{message:t,controller:n}):null,"out"===r&&i?rt("span",{children:" · Read"}):null]})]})},(e,t)=>e.message===t.message&&e.message.delivery_status===t.message.delivery_status&&e.controller===t.controller&&e.isReadByAgent===t.isReadByAgent);function Ii(e){var t,{message:n}=e,i=(null!==(t=n.content)&&void 0!==t?t:"").replace(vi,"").trim();if(!i)return rt("div",{class:"vt-message-bubble"});if(!oe(n))return rt("div",{class:"vt-message-bubble",children:i});var r=Si(i,n.content_type);return rt("div",{class:"vt-message-bubble",children:rt("div",{class:"vt-md"+("user"===n.sender_type?" vt-user-md":""),dangerouslySetInnerHTML:{__html:r}})})}function Ei(e){var{senderType:t}=e,n="ai"===t;return rt("div",{class:"vt-message-avatar","data-mode":n?"ai":"support",children:rt(n?Ht:qt,{width:16,height:16})})}function Ai(e){var{message:t,controller:n}=e,i=t.delivery_status;return i?rt("span","pending"===i||"sending"===i?{children:" · Sending…"}:{children:[" · ",rt("button",{type:"button",class:"vt-message-retry",onClick:()=>n.retryFailedMessage(t.id),children:"Failed — tap to retry"})]}):null}function Oi(e){if(!e)return"";var t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Mi(e){var{senderType:t,senderName:n}=e,i="ai"===t,r=i?"AI Assistant":n||"Agent";return rt("div",{class:"vt-message","data-direction":"in","data-typing":"true",children:[rt("div",{class:"vt-message-row",children:[rt("div",{class:"vt-message-avatar","data-mode":i?"ai":"support",children:rt(i?Ht:qt,{width:16,height:16})}),rt("div",{class:"vt-message-bubble","data-typing":"true","aria-label":r+" is typing",children:[rt("span",{class:"vt-typing-dot"}),rt("span",{class:"vt-typing-dot"}),rt("span",{class:"vt-typing-dot"})]})]}),rt("div",{class:"vt-message-meta",children:rt("span",{children:r})})]})}function Ri(e){var{count:t,visible:n,onJump:i}=e;return rt("button",{type:"button",class:"vt-new-pill","data-visible":n&&t>0?"true":"false","aria-label":"Jump to latest messages",onClick:i,children:rt("span",{children:t>1?"↓ "+t+" new messages":"↓ 1 new message"})})}function Pi(e){var{store:t,scrollRef:n,messages:i,typingActive:r=!1}=e,s=wt(null),a=wt(0);return bt(()=>{var e=n.current;if(e){var i=()=>{e.scrollHeight-e.scrollTop-e.clientHeight<80?t.userScrolledUp.value&&(t.userScrolledUp.value=!1,t.unreadNewMessagesCount.value=0):t.userScrolledUp.value||(t.userScrolledUp.value=!0)};return e.addEventListener("scroll",i,{passive:!0}),()=>e.removeEventListener("scroll",i)}},[n.current]),bt(()=>{var e,r,o,l=n.current;if(l){var c=null!==(e=i[i.length-1])&&void 0!==e?e:null;if(c){var d=c.id,u=null!==(o=null===(r=c.content)||void 0===r?void 0:r.length)&&void 0!==o?o:0,h=d!==s.current,p=!h&&"ai"===c.sender_type&&u>a.current;if(h||p)if(s.current=d,a.current=u,h){if("user"===c.sender_type)return l.scrollTop=l.scrollHeight,t.userScrolledUp.value=!1,void(t.unreadNewMessagesCount.value=0);var v=l.scrollHeight-l.scrollTop-l.clientHeight<80;!t.userScrolledUp.value||v?l.scrollTop=l.scrollHeight:"agent"!==c.sender_type&&"ai"!==c.sender_type||(t.unreadNewMessagesCount.value=t.unreadNewMessagesCount.value+1)}else(e=>{var n=e.scrollHeight-e.scrollTop-e.clientHeight<80;t.userScrolledUp.value&&!n||(e.scrollTop=e.scrollHeight)})(l)}}},[i,n.current]),bt(()=>{if(r){var e=n.current;if(e){var i=e.scrollHeight-e.scrollTop-e.clientHeight<80;t.userScrolledUp.value&&!i||(e.scrollTop=e.scrollHeight)}}},[r,n.current]),{jumpToBottom:()=>{var e=n.current;e&&(e.scrollTop=e.scrollHeight,t.userScrolledUp.value=!1,t.unreadNewMessagesCount.value=0)}}}function Li(e){var{store:t,controller:n}=e,i=wt(null),r=t.messages.value,s=t.channel.value,a=t.agentLastReadAt.value,o=t.isTyping.value,l=t.typingSenderType.value,c=t.typingSender.value,{jumpToBottom:d}=Pi({store:t,scrollRef:i,messages:r,typingActive:o});!function(e){var t,n,i,{store:r,controller:s,messages:a}=e;bt(()=>{if(r.isOpen.value&&"conversation"===r.currentView.value&&r.channel.value){var e=setTimeout(()=>s.markAsRead(),80);return()=>clearTimeout(e)}},[null!==(n=null===(t=a[a.length-1])||void 0===t?void 0:t.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:t,controller:n,messages:r});var u=!s&&t.isLoading.value&&0===r.length,h=!!s&&t.isLoading.value&&0===r.length,p=o&&("ai"===l||"agent"===l);return rt("div",{class:"vt-messages-wrapper",children:[rt("div",{class:"vt-messages",ref:i,children:u?rt(Mi,{senderType:!1===n.config.aiMode?"agent":"ai"}):h?rt(Ln,{}):rt(Le,{children:[r.map(e=>{return rt(Ti,{message:e,controller:n,isReadByAgent:(t=e.created_at,!!a&&new Date(t)<=new Date(a))},e.id);var t}),p&&rt(Mi,{senderType:l,senderName:c})]})}),rt(Ri,{count:t.unreadNewMessagesCount.value,visible:t.userScrolledUp.value,onJump:d})]})}function Ui(e){var t,{store:n,controller:i}=e,r="closed"===(null===(t=n.channel.value)||void 0===t?void 0:t.status);return rt(Le,{children:[rt(Li,{store:n,controller:i}),rt(qn,{store:n}),r?rt(Hn,{}):rt(Fn,{store:n,controller:i})]})}function Di(e){var{store:t,controller:n}=e,i=t.currentView.value;return rt("div",{class:"vt-panel vt-opening",children:[rt(Bn,{store:t,controller:n}),rt("div",{class:"vt-content",children:rt("list"===i?Dn:Ui,{store:t,controller:n})})]})}var Ni="vtilt-chat-font";function Bi(e){!function(){if("undefined"!=typeof document&&!document.getElementById(Ni)){var e=document.createElement("link");e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="anonymous",document.head.appendChild(e);var t=document.createElement("link");t.id=Ni,t.rel="stylesheet",t.href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap",document.head.appendChild(t)}}();var t=document.createElement("div");t.id="vtilt-chat-host",t.style.cssText="all: initial; position: fixed; inset: auto; z-index: 999999; pointer-events: none;",document.body.appendChild(t);var n=t.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(e,t){var n=()=>{var n=t.theme.value;e.style.setProperty("--vtilt-primary",n.primaryColor),e.style.setProperty("--vtilt-primary-shadow",n.primaryColor+"66"),e.style.setProperty("--vtilt-font",n.fontFamily),e.style.setProperty("--vtilt-radius",n.borderRadius)};n(),t.theme.subscribe(n)}(t,e.store),nt(rt(Hi,{store:e.store,controller:e.controller,position:e.position,bubbleDraggable:e.bubbleDraggable}),r),{host:t,destroy(){nt(null,r),t.remove()}}}function Hi(e){var{store:t,controller:n,position:i,bubbleDraggable:r}=e,s=wt(null),a=wt(null),o=wt(null),l=function(e,t){return St(()=>{var n=t.current;if(n&&"undefined"!=typeof window&&!e.isOpen.value){var i=n.getBoundingClientRect();if(0!==i.width&&0!==i.height){var r=window.innerWidth,s=window.innerHeight,a=(i.left+i.right)/2>r/2?"right":"left",o=(i.top+i.bottom)/2>s/2?"bottom":"top",l=o+"-"+a;n.setAttribute("data-panel-anchor",l),n.style.setProperty("--vt-panel-origin",o+" "+a);var c="right"===a?i.right:r-i.left,d="bottom"===o?i.bottom:s-i.top;n.style.setProperty("--vt-panel-max-w",Math.max(0,c-20)+"px"),n.style.setProperty("--vt-panel-max-h",Math.max(0,d-20)+"px")}}},[e,t])}(t,s);return function(e,t){var n=mt(st++,4);!ut.__s&&At(n.__H,t)&&(n.__=e,n.u=t,at.__h.push(n))}(()=>{if(r&&s.current&&a.current)return o.current=An(s.current,{handle:a.current,onPositionChange:l}),()=>{var e;null===(e=o.current)||void 0===e||e.destroy(),o.current=null}},[r,l]),bt(()=>{l();var e=()=>l();window.addEventListener("resize",e);var n=t.isOpen.subscribe(e=>{e||l()});return()=>{window.removeEventListener("resize",e),n()}},[t,l]),function(e){bt(()=>{var t=e.isOpen.value,n=e.isOpen.subscribe(e=>{var n,i;if("undefined"!=typeof document){var r=function(e,t,n){return n?t&&!e?{nextWasOpen:!0,shouldLock:!0,shouldUnlock:!1}:!t&&e?{nextWasOpen:!1,shouldLock:!1,shouldUnlock:!0}:{nextWasOpen:t,shouldLock:!1,shouldUnlock:!1}:{nextWasOpen:t,shouldLock:!1,shouldUnlock:!1}}(t,e,"undefined"!=typeof window&&window.innerWidth<=480);t=r.nextWasOpen;var s=document.documentElement,a=document.body;if(r.shouldLock){var o=null!==(n=null===window||void 0===window?void 0:window.scrollY)&&void 0!==n?n:0;s.style.setProperty("overflow","hidden","important"),a.style.setProperty("overflow","hidden","important"),a.style.setProperty("position","fixed","important"),a.style.setProperty("width","100%","important"),a.style.top="-"+o+"px",a.dataset.vtScrollY=String(o)}else if(r.shouldUnlock){var l=Number(null!==(i=a.dataset.vtScrollY)&&void 0!==i?i:0);s.style.removeProperty("overflow"),a.style.removeProperty("overflow"),a.style.removeProperty("position"),a.style.removeProperty("width"),a.style.top="",delete a.dataset.vtScrollY,null===window||void 0===window||window.scrollTo(0,l)}}else t=e});return n},[e])}(t),rt("div",{ref:s,class:"vt-container","data-position":i,"data-draggable":r?"true":"false","data-hidden":t.isVisible.value?"false":"true","data-open":t.isOpen.value?"true":"false",children:[rt(On,{store:t,controller:n,bubbleRef:a}),rt(Di,{store:t,controller:n})]})}var qi=Object.defineProperty,Fi=Object.defineProperties,ji=Object.getOwnPropertyDescriptors,Wi=Object.getOwnPropertySymbols,$i=Object.prototype.hasOwnProperty,zi=Object.prototype.propertyIsEnumerable,Vi=(e,t,n)=>t in e?qi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Gi=(e,t)=>{for(var n in t||(t={}))$i.call(t,n)&&Vi(e,n,t[n]);if(Wi)for(var n of Wi(t))zi.call(t,n)&&Vi(e,n,t[n]);return e},Ki=(e,t)=>Fi(e,ji(t)),Ji=function(e,t){this[0]=e,this[1]=t},Qi=class{},Xi="undefined"!=typeof global?global:"undefined"!=typeof window?window:self;function Yi(e,t){return(""+e).padStart(t?3:2,"0")}function Zi(e){return Qi.Config.logTimestamps?function(t){var n=new Date;e(Yi(n.getHours())+":"+Yi(n.getMinutes())+":"+Yi(n.getSeconds())+"."+Yi(n.getMilliseconds(),1)+" "+t)}:function(t){e(t)}}var er=class e{constructor(){this.deprecated=(e,t)=>{this.deprecationWarning(e+" is deprecated and will be removed in a future version. "+t)},this.shouldLog=e=>e<=this.logLevel,this.setLog=(e,t)=>{void 0!==e&&(this.logLevel=e),void 0!==t&&(this.logHandler=this.logErrorHandler=t)},this.logLevel=e.defaultLogLevel,this.logHandler=e.defaultLogHandler,this.logErrorHandler=e.defaultLogErrorHandler}static initLogHandlers(){var t,n,i,[r,s]=("function"==typeof(null==(t=null==Xi?void 0:Xi.console)?void 0:t.log)?(n=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];console.log.apply(console,t)},i=console.warn?function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];console.warn.apply(console,t)}:n):n=i=function(){},[n,i].map(Zi));this.defaultLogHandler=r,this.defaultLogErrorHandler=s,this.defaultLogger=new e}static logActionNoStrip(e,t,n,i){e.logAction(t,n,i)}logAction(e,t,n){this.shouldLog(e)&&(1===e?this.logErrorHandler:this.logHandler)("Ably: "+t+": "+n,e)}renamedClientOption(e,t){this.deprecationWarning("The `"+e+"` client option has been renamed to `"+t+"`. Please update your code to use `"+t+"` instead. `"+e+"` will be removed in a future version.")}renamedMethod(e,t,n){this.deprecationWarning("`"+e+"`’s `"+t+"` method has been renamed to `"+n+"`. Please update your code to use `"+n+"` instead. `"+t+"` will be removed in a future version.")}deprecationWarning(e){this.shouldLog(1)&&this.logErrorHandler("Ably: Deprecation warning - "+e,1)}};er.defaultLogLevel=1,er.LOG_NONE=0,er.LOG_ERROR=1,er.LOG_MAJOR=2,er.LOG_MINOR=3,er.LOG_MICRO=4,er.logAction=(e,t,n,i)=>{er.logActionNoStrip(e,t,n,i)};var tr=er,nr={};function ir(e){var t="["+e.constructor.name;return e.message&&(t+=": "+e.message),e.statusCode&&(t+="; statusCode="+e.statusCode),e.code&&(t+="; code="+e.code),e.cause&&(t+="; cause="+Mr(e.cause)),!e.href||e.message&&e.message.indexOf("help.ably.io")>-1||(t+="; see "+e.href+" "),t+="]"}((e,t)=>{for(var n in t)qi(e,n,{get:t[n],enumerable:!0})})(nr,{Format:()=>xr,allSame:()=>kr,allToLowerCase:()=>qr,allToUpperCase:()=>Fr,arrChooseN:()=>Dr,arrDeleteValue:()=>yr,arrEquals:()=>Jr,arrIntersect:()=>_r,arrIntersectOb:()=>mr,arrPopRandomElement:()=>Tr,arrWithoutValue:()=>br,cheapRandStr:()=>Lr,containsValue:()=>gr,copy:()=>or,createMissingPluginError:()=>Qr,dataSizeBytes:()=>Pr,decodeBody:()=>Br,encodeBody:()=>Hr,ensureArray:()=>lr,forInOwnNonNullProperties:()=>Sr,getBackoffCoefficient:()=>jr,getGlobalObject:()=>zr,getJitterCoefficient:()=>Wr,getRetryTime:()=>$r,inherits:()=>vr,inspectBody:()=>Rr,inspectError:()=>Mr,intersect:()=>fr,isEmpty:()=>dr,isErrorInfoOrPartialErrorInfo:()=>Or,isNil:()=>ur,isObject:()=>cr,keysArray:()=>wr,listenerToAsyncIterator:()=>es,matchDerivedChannel:()=>Gr,mixin:()=>ar,parseQueryString:()=>Ar,prototypicalClone:()=>pr,randomString:()=>Ur,shallowClone:()=>hr,shallowEquals:()=>Vr,stringifyValues:()=>Er,throwMissingPluginError:()=>Xr,toBase64:()=>Kr,toQueryString:()=>Ir,valuesArray:()=>Cr,whenPromiseSettles:()=>Nr,withTimeoutAsync:()=>Yr});var rr=class e extends Error{constructor(t,n,i,r){super(t),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,e.prototype),this.code=n,this.statusCode=i,this.cause=r}toString(){return ir(this)}static fromValues(t){var{message:n,code:i,statusCode:r}=t;if("string"!=typeof n||"number"!=typeof i||"number"!=typeof r)throw new Error("ErrorInfo.fromValues(): invalid values: "+Qi.Config.inspect(t));var s=Object.assign(new e(n,i,r),t);return s.code&&!s.href&&(s.href="https://help.ably.io/error/"+s.code),s}},sr=class e extends Error{constructor(t,n,i,r){super(t),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,e.prototype),this.code=n,this.statusCode=i,this.cause=r}toString(){return ir(this)}static fromValues(t){var{message:n,code:i,statusCode:r}=t;if("string"!=typeof n||!ur(i)&&"number"!=typeof i||!ur(r)&&"number"!=typeof r)throw new Error("PartialErrorInfo.fromValues(): invalid values: "+Qi.Config.inspect(t));var s=Object.assign(new e(n,i,r),t);return s.code&&!s.href&&(s.href="https://help.ably.io/error/"+s.code),s}};function ar(e){for(var t=0;t<(arguments.length<=1?0:arguments.length-1);t++){var n=t+1<1||arguments.length<=t+1?void 0:arguments[t+1];if(!n)break;for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e}function or(e){return ar({},e)}function lr(e){return ur(e)?[]:Array.isArray(e)?e:[e]}function cr(e){return"[object Object]"==Object.prototype.toString.call(e)}function dr(e){for(var t in e)return!1;return!0}function ur(e){return null==e}function hr(e){var t=new Object;for(var n in e)t[n]=e[n];return t}function pr(e,t){class n{}n.prototype=e;var i=new n;return t&&ar(i,t),i}var vr=function(e,t){Qi.Config.inherits?Qi.Config.inherits(e,t):(e.super_=t,e.prototype=pr(t.prototype,{constructor:e}))};function gr(e,t){for(var n in e)if(e[n]==t)return!0;return!1}function fr(e,t){return Array.isArray(t)?_r(e,t):mr(e,t)}function _r(e,t){for(var n=[],i=0;i<e.length;i++){var r=e[i];-1!=t.indexOf(r)&&n.push(r)}return n}function mr(e,t){for(var n=[],i=0;i<e.length;i++){var r=e[i];r in t&&n.push(r)}return n}function yr(e,t){var n=e.indexOf(t),i=-1!=n;return i&&e.splice(n,1),i}function br(e,t){var n=e.slice();return yr(n,t),n}function wr(e,t){var n=[];for(var i in e)t&&!Object.prototype.hasOwnProperty.call(e,i)||n.push(i);return n}function Cr(e,t){var n=[];for(var i in e)t&&!Object.prototype.hasOwnProperty.call(e,i)||n.push(e[i]);return n}function Sr(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&t(n)}function kr(e,t){if(0===e.length)return!0;var n=e[0][t];return e.every(function(e){return e[t]===n})}var xr=(e=>(e.msgpack="msgpack",e.json="json",e))(xr||{});function Tr(e){return e.splice((t=e,Math.floor(Math.random()*t.length)),1)[0];var t}function Ir(e){var t=[];if(e)for(var n in e)t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.length?"?"+t.join("&"):""}function Er(e){return Object.fromEntries(Object.entries(e).map(e=>{var[t,n]=e;return[t,String(n)]}))}function Ar(e){for(var t,n=/([^?&=]+)=?([^&]*)/g,i={};t=n.exec(e);)i[decodeURIComponent(t[1])]=decodeURIComponent(t[2]);return i}function Or(e){return"object"==typeof e&&null!==e&&(e instanceof rr||e instanceof sr)}function Mr(e){var t,n;return e instanceof Error||"ErrorInfo"===(null==(t=null==e?void 0:e.constructor)?void 0:t.name)||"PartialErrorInfo"===(null==(n=null==e?void 0:e.constructor)?void 0:n.name)?e.toString():Qi.Config.inspect(e)}function Rr(e){return Qi.BufferUtils.isBuffer(e)?e.toString():"string"==typeof e?e:Qi.Config.inspect(e)}function Pr(e){if(Qi.BufferUtils.isBuffer(e))return Qi.BufferUtils.byteLength(e);if("string"==typeof e)return Qi.Config.stringByteSize(e);if("number"==typeof e)return 8;if("boolean"==typeof e)return 1;throw new Error("Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: "+typeof e)}function Lr(){return String(Math.random()).substr(2)}var Ur=function(){var e=c(function*(e){var t=yield Qi.Config.getRandomArrayBuffer(e);return Qi.BufferUtils.base64Encode(t)});return function(t){return e.apply(this,arguments)}}();function Dr(e,t){for(var n=Math.min(t,e.length),i=e.slice(),r=[],s=0;s<n;s++)r.push(Tr(i));return r}function Nr(e,t){e.then(e=>{null==t||t(null,e)}).catch(e=>{null==t||t(e)})}function Br(e,t,n){return"msgpack"==n?(t||Xr("MsgPack"),t.decode(e)):JSON.parse(String(e))}function Hr(e,t,n){return"msgpack"==n?(t||Xr("MsgPack"),t.encode(e,!0)):JSON.stringify(e)}function qr(e){return e.map(function(e){return e&&e.toLowerCase()})}function Fr(e){return e.map(function(e){return e&&e.toUpperCase()})}function jr(e){return Math.min((e+2)/3,2)}function Wr(){return 1-.2*Math.random()}function $r(e,t){return e*jr(t)*Wr()}function zr(){return"undefined"!=typeof global?global:"undefined"!=typeof window?window:self}function Vr(e,t){return Object.keys(e).every(n=>e[n]===t[n])&&Object.keys(t).every(n=>t[n]===e[n])}function Gr(e){var t=e.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!t||!t.length||t.length<5)throw new rr("regex match failed",400,40010);if(t[2])throw new rr("cannot use a derived option with a "+t[2]+" channel",400,40010);return{qualifierParam:t[3]||"",channelName:t[4]}}function Kr(e){var t=Qi.BufferUtils,n=t.utf8Encode(e);return t.base64Encode(n)}function Jr(e,t){return e.length===t.length&&e.every(function(e,n){return e===t[n]})}function Qr(e){return new rr(e+" plugin not provided",40019,400)}function Xr(e){throw Qr(e)}function Yr(e,t,n){return Zr.apply(this,arguments)}function Zr(){return Zr=c(function*(e,t,n){void 0===t&&(t=5e3),void 0===n&&(n="Timeout expired");var i=new rr(n,5e4,500);return Promise.race([e,new Promise((e,n)=>setTimeout(()=>n(i),t))])}),Zr.apply(this,arguments)}function es(e){return n=(e,i,r,s)=>{try{var a=t[e](i),o=(i=a.value)instanceof Ji,l=a.done;Promise.resolve(o?i[0]:i).then(t=>o?n("return"===e?e:"next",i[1]?{done:t.done,value:t.value}:t,r,s):r({value:t,done:l})).catch(e=>n("throw",e,r,s))}catch(e){s(e)}},i=e=>r[e]=t=>new Promise((i,r)=>n(e,t,i,r)),r={},t=(t=function*(){var t=[],n=null,i=e(e=>{if(n){var i=n;n=null,i(e)}else t.push(e)});try{for(;;)if(t.length>0)yield t.shift();else{if(n)throw new rr("Concurrent next() calls are not supported",4e4,400);var r=yield new Ji(new Promise(e=>{n=e}));yield r}}finally{i()}}).apply(this,null),r[Symbol.asyncIterator]=()=>r,i("next"),i("throw"),i("return"),r;var t,n,i,r}var ts="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:ts,protocolVersion:5,agent:"ably-js/"+ts,getPort:function(e,t){return t||e.tls?e.tlsPort:e.port},getHttpScheme:function(e){return e.tls?"https://":"http://"},getPrimaryDomainFromEndpoint:rs,getEndpointFallbackHosts:ss,getFallbackHosts:os,getHosts:function(e){return[e.primaryDomain].concat(os(e))},checkHost:ls,objectifyOptions:function(e,t,n,i,r){if(void 0===e){var s=t?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 tr.logAction(i,tr.LOG_ERROR,n+"()",s),new Error(s)}var a;if("string"==typeof e)if(-1==e.indexOf(":")){if(!t){var o=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 tr.logAction(i,tr.LOG_ERROR,n+"()",o),new Error(o)}a={token:e}}else{if(!t){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 tr.logAction(i,tr.LOG_ERROR,n+"()",l),new Error(l)}a={key:e}}else a=e;r&&(a=Ki(Gi({},a),{plugins:Gi(Gi({},r),a.plugins)}));return a},normaliseOptions:function(e,t,n){var i=null!=n?n:tr.defaultLogger;e.environment&&i.deprecated("The `environment` client option","Use the `endpoint` client option instead.");e.restHost&&i.deprecated("The `restHost` client option","Use the `endpoint` client option instead.");e.realtimeHost&&i.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead.");ds(e),"function"==typeof e.recover&&!0===e.closeOnUnload&&(tr.logAction(i,tr.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),e.recover=void 0);"closeOnUnload"in e||(e.closeOnUnload=!e.recover);"queueMessages"in e||(e.queueMessages=!0);var r=e.endpoint||ns.ENDPOINT;e.fallbackHosts||e.restHost||e.realtimeHost||e.port||e.tlsPort||(e.fallbackHosts=ss(e.environment||r));var s=e.environment&&e.environment+".realtime.ably.net",a=e.restHost||e.realtimeHost||s||rs(r);(e.fallbackHosts||[]).concat(a).forEach(ls),e.port=e.port||ns.PORT,e.tlsPort=e.tlsPort||ns.TLS_PORT,"tls"in e||(e.tls=!0);var o=function(e){var t={};for(var n in ns.TIMEOUTS)t[n]=e[n]||ns.TIMEOUTS[n];return t}(e);e.useBinaryProtocol=!!t&&("useBinaryProtocol"in e?Qi.Config.supportsBinary&&e.useBinaryProtocol:Qi.Config.preferBinary);var l={};e.clientId&&(l["X-Ably-ClientId"]=Qi.BufferUtils.base64Encode(Qi.BufferUtils.utf8Encode(e.clientId)));"idempotentRestPublishing"in e||(e.idempotentRestPublishing=!0);var c=null,d=e.connectivityCheckUrl;if(e.connectivityCheckUrl){var[u,h]=e.connectivityCheckUrl.split("?");c=h?Ar(h):{},-1===u.indexOf("://")&&(u="https://"+u),d=u}var p=e.wsConnectivityCheckUrl;p&&-1===p.indexOf("://")&&(p="wss://"+p);return Ki(Gi({},e),{primaryDomain:a,maxMessageSize:e.maxMessageSize||ns.maxMessageSize,timeouts:o,connectivityCheckParams:c,connectivityCheckUrl:d,wsConnectivityCheckUrl:p,headers:l})},defaultGetHeaders:function(e,t){var{format:n,protocolVersion:i=ps.protocolVersion}=void 0===t?{}:t;return{accept:hs[null!=n?n:e.useBinaryProtocol?"msgpack":"json"],"X-Ably-Version":i.toString(),"Ably-Agent":cs(e)}},defaultPostHeaders:function(e,t){var{format:n,protocolVersion:i=ps.protocolVersion}=void 0===t?{}:t,r=hs[null!=n?n:e.useBinaryProtocol?"msgpack":"json"];return{accept:r,"content-type":r,"X-Ably-Version":i.toString(),"Ably-Agent":cs(e)}}};function is(e){return e.includes(".")||e.includes("::")||"localhost"===e}function rs(e){return is(e)?e:e.startsWith("nonprod:")?e.replace("nonprod:","")+".realtime.ably-nonprod.net":e+".realtime.ably.net"}function ss(e){return is(e)?[]:e.startsWith("nonprod:")?as(e.replace("nonprod:",""),"ably-realtime-nonprod.com"):as(e,"ably-realtime.com")}function as(e,t){return["a","b","c","d","e"].map(n=>e+"."+n+".fallback."+t)}function os(e){var t=e.fallbackHosts,n=void 0!==e.httpMaxRetryCount?e.httpMaxRetryCount:ns.httpMaxRetryCount;return t?Dr(t,n):[]}function ls(e){if("string"!=typeof e)throw new rr("host must be a string; was a "+typeof e,4e4,400);if(!e.length)throw new rr("host must not be zero-length",4e4,400)}function cs(e){var t=ns.agent;if(e.agents)for(var n in e.agents)t+=" "+n+"/"+e.agents[n];return t}function ds(e){if(e.endpoint&&(e.environment||e.restHost||e.realtimeHost))throw new rr("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(e.environment&&(e.restHost||e.realtimeHost))throw new rr("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function us(e,t,n){var i=n||{};if(i.cipher){e||Xr("Crypto");var r=e.getCipher(i.cipher,t);i.cipher=r.cipherParams,i.channelCipher=r.cipher}else"cipher"in i&&(i.cipher=void 0,i.channelCipher=null);return i}var hs={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},ps={protocolVersion:ns.protocolVersion};var vs=ns;var gs=class e{constructor(e,t){this.logger=e,this.members=t||[]}call(e,t){for(var n of this.members)if(n)try{n(e,t)}catch(e){tr.logAction(this.logger,tr.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+e+"; stack = "+e.stack)}}push(){this.members.push(...arguments)}createPromise(){return new Promise((e,t)=>{this.push((n,i)=>{n?t(n):e(i)})})}resolveAll(e){this.call(null,e)}rejectAll(e){this.call(e)}static create(t,n){var i=new e(t,n);return Object.assign((e,t)=>i.call(e,t),{push:e=>i.push(e),createPromise:()=>i.createPromise(),resolveAll:e=>i.resolveAll(e),rejectAll:e=>i.rejectAll(e)})}},fs=(e=>(e.Get="get",e.Delete="delete",e.Post="post",e.Put="put",e.Patch="patch",e))(fs||{}),_s=fs,ms=(e=>(e[e.Success=200]="Success",e[e.NoContent=204]="NoContent",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.Forbidden=403]="Forbidden",e[e.RequestTimeout=408]="RequestTimeout",e[e.InternalServerError=500]="InternalServerError",e))(ms||{});var ys=ms,bs=Math.pow(2,17);function ws(e){return Or(e)?(e.code||(403===e.statusCode?e.code=40300:(e.code=40170,e.statusCode=401)),e):new rr(Mr(e),e.code||40170,e.statusCode||401)}function Cs(e){if(!e)return"";"string"==typeof e&&(e=JSON.parse(e));var t=Object.create(null),n=wr(e,!0);if(!n)return"";n.sort();for(var i=0;i<n.length;i++)t[n[i]]=e[n[i]].sort();return JSON.stringify(t)}function Ss(e,t){if(e.authCallback);else if(e.authUrl);else if(e.key);else if(!e.tokenDetails){var n="authOptions must include valid authentication parameters";throw tr.logAction(t,tr.LOG_ERROR,"Auth()",n),new Error(n)}}var ks=0;var xs=class{constructor(e,t){if(this.authOptions={},this.client=e,this.tokenParams=t.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,function(e){return e.useTokenAuth||!function(e){return"useTokenAuth"in e&&!e.useTokenAuth}(e)&&(e.authCallback||e.authUrl||e.token||e.tokenDetails)}(t))(function(e){return!e.key&&!e.authCallback&&!e.authUrl})(t)&&tr.logAction(this.logger,tr.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._saveTokenOptions(t.defaultTokenParams,t),Ss(this.authOptions,this.logger);else{if(!t.key){var n="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw tr.logAction(this.logger,tr.LOG_ERROR,"Auth()",n),new rr(n,40160,401)}this._saveBasicOptions(t)}}get logger(){return this.client.logger}authorize(e,t){var n=this;return c(function*(){if(t&&t.key&&n.authOptions.key!==t.key)throw new rr("Unable to update auth options with incompatible key",40102,401);try{var i=yield n._forceNewToken(null!=e?e:null,null!=t?t:null);return n.client.connection?new Promise((e,t)=>{n.client.connection.connectionManager.onAuthUpdated(i,(n,i)=>n?t(n):e(i))}):i}catch(e){throw n.client.connection&&e.statusCode===ys.Forbidden&&n.client.connection.connectionManager.actOnErrorFromAuthorize(e),e}})()}_forceNewToken(e,t){var n=this;return c(function*(){n.tokenDetails=null,n._saveTokenOptions(e,t),Ss(n.authOptions,n.logger);try{return n._ensureValidAuthCredentials(!0)}finally{delete n.tokenParams.timestamp,delete n.authOptions.queryTime}})()}requestToken(e,t){var n=this;return c(function*(){var i,r=t||n.authOptions,s=e||or(n.tokenParams),a=n.client;if(r.authCallback)i=r.authCallback;else if(r.authUrl)i=(e,t)=>{var i,s=ar({accept:"application/json, text/plain"},r.authHeaders),a=r.authMethod&&"post"===r.authMethod.toLowerCase(),o=r.authUrl.indexOf("?");o>-1&&(i=Ar(r.authUrl.slice(o)),r.authUrl=r.authUrl.slice(0,o),a||(r.authParams=ar(i,r.authParams)));var l=ar({},r.authParams||{},e),c=e=>{var n,i,r=null!=(n=e.body)?n:null,s=null;if(e.error);else{var a=null!=(i=e.headers["content-type"])?i:null;s=Array.isArray(a)?a.join(", "):a}if(e.error)t(e.error,null);else if(e.unpacked)t(null,r);else if(Qi.BufferUtils.isBuffer(r)&&(r=r.toString()),s){var o=s.indexOf("application/json")>-1,l=s.indexOf("text/plain")>-1||s.indexOf("application/jwt")>-1;if(o||l){if(o){if(r.length>bs)return void t(new rr("authUrl response exceeded max permitted length",40170,401),null);try{r=JSON.parse(r)}catch(e){return void t(new rr("Unexpected error processing authURL response; err = "+e.message,40170,401),null)}}t(null,r,s)}else t(new rr("authUrl responded with unacceptable content-type "+s+", should be either text/plain, application/jwt or application/json",40170,401),null)}else t(new rr("authUrl response is missing a content-type header",40170,401),null)};if(a){var d=s||{};d["content-type"]="application/x-www-form-urlencoded";var u=Ir(l).slice(1);Nr(n.client.http.doUri(_s.Post,r.authUrl,d,u,i),(e,t)=>c(e||t))}else Nr(n.client.http.doUri(_s.Get,r.authUrl,s||{},null,l),(e,t)=>c(e||t))};else{if(!r.key){throw tr.logAction(n.logger,tr.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=(e,t)=>{Nr(n.createTokenRequest(e,r),(e,n)=>t(e,null!=n?n:null))}}"capability"in s&&(s.capability=Cs(s.capability));return new Promise((e,t)=>{var o=!1,l=n.client.options.timeouts.realtimeRequestTimeout,c=setTimeout(()=>{o=!0;var e="Token request callback timed out after "+l/1e3+" seconds";tr.logAction(n.logger,tr.LOG_ERROR,"Auth.requestToken()",e),t(new rr(e,40170,401))},l);i(s,(i,s,l)=>{if(!o){if(clearTimeout(c),i)return tr.logAction(n.logger,tr.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+Mr(i)),void t(ws(i));if("string"!=typeof s){if("object"!=typeof s||null===s){var d="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof s;return tr.logAction(n.logger,tr.LOG_ERROR,"Auth.requestToken()",d),void t(new rr(d,40170,401))}var u=JSON.stringify(s).length;if(u>bs&&!r.suppressMaxLengthCheck)t(new rr("Token request/details object exceeded max permitted stringified size (was "+u+" bytes)",40170,401));else if("issued"in s)e(s);else{if(!("keyName"in s)){var h="Expected token request callback to call back with a token string, token request object, or token details object";return tr.logAction(n.logger,tr.LOG_ERROR,"Auth.requestToken()",h),void t(new rr(h,40170,401))}var p,v,g,f;v=(i,r,s)=>{if(i)return tr.logAction(n.logger,tr.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+Mr(i)),void t(ws(i));s||(r=JSON.parse(r)),e(r)},g="/keys/"+(p=s).keyName+"/requestToken",f=vs.defaultPostHeaders(n.client.options,{format:"json"}),r.requestHeaders&&ar(f,r.requestHeaders),Nr(n.client.http.do(_s.Post,function(e){return a.baseUri(e)+g},f,JSON.stringify(p),null),(e,t)=>e?v(e):v(t.error,t.body,t.unpacked))}}else 0===s.length?t(new rr("Token string is empty",40170,401)):s.length>bs?t(new rr("Token string exceeded max permitted length (was "+s.length+" bytes)",40170,401)):"undefined"===s||"null"===s?t(new rr("Token string was literal null/undefined",40170,401)):"{"!==s[0]||l&&l.indexOf("application/jwt")>-1?e({token:s}):t(new rr("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401))}})})})()}createTokenRequest(e,t){var n=this;return c(function*(){t=t||n.authOptions,e=e||or(n.tokenParams);var i=t.key;if(!i)throw new rr("No key specified",40101,403);var r=i.split(":"),s=r[0],a=r[1];if(!a)throw new rr("Invalid key specified",40101,403);if(""===e.clientId)throw new rr("clientId can’t be an empty string",40012,400);"capability"in e&&(e.capability=Cs(e.capability));var o=ar({keyName:s},e),l=e.clientId||"",c=e.ttl||"",d=e.capability||"";o.timestamp||(o.timestamp=yield n._getTimestamp(t&&t.queryTime));var u=o.nonce||(o.nonce=("000000"+Math.floor(1e16*Math.random())).slice(-16)),h=o.timestamp,p=o.keyName+"\n"+c+"\n"+d+"\n"+l+"\n"+h+"\n"+u+"\n";return o.mac=o.mac||((e,t)=>{var n=Qi.BufferUtils,i=n.utf8Encode(e),r=n.utf8Encode(t),s=n.hmacSha256(i,r);return n.base64Encode(s)})(p,a),o})()}getAuthParams(){var e=this;return c(function*(){if("basic"==e.method)return{key:e.key};var t=yield e._ensureValidAuthCredentials(!1);if(!t)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:t.token}})()}getAuthHeaders(){var e=this;return c(function*(){if("basic"==e.method)return{authorization:"Basic "+e.basicKey};var t=yield e._ensureValidAuthCredentials(!1);if(!t)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+Kr(t.token)}})()}_saveBasicOptions(e){this.method="basic",this.key=e.key,this.basicKey=Kr(e.key),this.authOptions=e||{},"clientId"in e&&this._userSetClientId(e.clientId)}_saveTokenOptions(e,t){this.method="token",e&&(this.tokenParams=e),t&&(t.token&&(t.tokenDetails="string"==typeof t.token?{token:t.token}:t.token),t.tokenDetails&&(this.tokenDetails=t.tokenDetails),"clientId"in t&&this._userSetClientId(t.clientId),this.authOptions=t)}_ensureValidAuthCredentials(e){var t=this;return c(function*(){var n=t.tokenDetails;if(n){if(t._tokenClientIdMismatch(n.clientId))throw new rr("Mismatch between clientId in token ("+n.clientId+") and current clientId ("+t.clientId+")",40102,403);if(!t.client.isTimeOffsetSet()||!n.expires||n.expires>=t.client.getTimestampUsingOffset())return n;t.tokenDetails=null}var i=(t.waitingForTokenRequest||(t.waitingForTokenRequest=gs.create(t.logger))).createPromise();if(null!==t.currentTokenRequestId&&!e)return i;var r,s=t.currentTokenRequestId=ks++,a=null;try{r=yield t.requestToken(t.tokenParams,t.authOptions)}catch(e){a=e}if(t.currentTokenRequestId>s)return i;t.currentTokenRequestId=null;var o=t.waitingForTokenRequest;return t.waitingForTokenRequest=null,a?(null==o||o.rejectAll(a),i):(null==o||o.resolveAll(t.tokenDetails=r),i)})()}_userSetClientId(e){if("string"!=typeof e&&null!==e)throw new rr("clientId must be either a string or null",40012,400);if("*"===e)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 t=this._uncheckedSetClientId(e);if(t)throw t}_uncheckedSetClientId(e){if(this._tokenClientIdMismatch(e)){var t="Unexpected clientId mismatch: client has "+this.clientId+", requested "+e,n=new rr(t,40102,401);return tr.logAction(this.logger,tr.LOG_ERROR,"Auth._uncheckedSetClientId()",t),n}return this.clientId=this.tokenParams.clientId=e,null}_tokenClientIdMismatch(e){return!(!this.clientId||"*"===this.clientId||!e||"*"===e||this.clientId===e)}static isTokenErr(e){return e.code&&e.code>=40140&&e.code<40150}revokeTokens(e,t){return this.client.rest.revokeTokens(e,t)}_getTimestamp(e){var t=this;return c(function*(){return t.client.getTimestamp(e||!!t.authOptions.queryTime)})()}};function Ts(e){var t=[];if(e)for(var n in e)t.push(n+"="+e[n]);return t.join("&")}function Is(e,t){return e+(t?"?":"")+Ts(t)}var Es=class{constructor(e){this.client=e,this.platformHttp=new Qi.Http(e),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var e,t;return null!=(t=null==(e=this.client)?void 0:e.logger)?t:tr.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(e){var t=e.connection,n=t&&t.connectionManager.host;return n?[n].concat(vs.getFallbackHosts(e.options)):vs.getHosts(e.options)}do(e,t,n,i,r){var s=this;return c(function*(){try{var a=s.client;if(!a)return{error:new rr("http.do called without client",5e4,500)};var o="function"==typeof t?t:function(e){return a.baseUri(e)+t},l=a._currentFallback;if(l){if(l.validUntil>Date.now()){var d=yield s.doUri(e,o(l.host),n,i,r);return d.error&&s.platformHttp.shouldFallback(d.error)?(a._currentFallback=null,s.do(e,t,n,i,r)):d}a._currentFallback=null}var u=s._getHosts(a);if(1===u.length)return s.doUri(e,o(u[0]),n,i,r);var h=null,p=function(){var t=c(function*(t,l){var c=t.shift();h=null!=h?h:new Date;var d=yield s.doUri(e,o(c),n,i,r);return d.error&&s.platformHttp.shouldFallback(d.error)&&t.length?Date.now()-h.getTime()>a.options.timeouts.httpMaxRetryDuration?{error:new rr("Timeout for trying fallback hosts retries. Total elapsed time exceeded the "+a.options.timeouts.httpMaxRetryDuration+"ms limit",50003,500)}:p(t,!0):(l&&(a._currentFallback={host:c,validUntil:Date.now()+a.options.timeouts.fallbackRetryTimeout}),d)});return function(e,n){return t.apply(this,arguments)}}();return p(u)}catch(e){return{error:new rr("Unexpected error in Http.do: "+Mr(e),500,5e4)}}})()}doUri(e,t,n,i,r){var s=this;return c(function*(){try{!function(e,t,n,i,r){r.shouldLog(tr.LOG_MICRO)&&tr.logActionNoStrip(r,tr.LOG_MICRO,"Http."+e+"()","Sending; "+Is(t,i)+"; Body"+(Qi.BufferUtils.isBuffer(n)?" (Base64): "+Qi.BufferUtils.base64Encode(n):": "+n))}(e,t,i,r,s.logger);var a=yield s.platformHttp.doUri(e,t,n,i,r);return s.logger.shouldLog(tr.LOG_MICRO)&&function(e,t,n,i,r){e.error?tr.logActionNoStrip(r,tr.LOG_MICRO,"Http."+t+"()","Received Error; "+Is(n,i)+"; Error: "+Mr(e.error)):tr.logActionNoStrip(r,tr.LOG_MICRO,"Http."+t+"()","Received; "+Is(n,i)+"; Headers: "+Ts(e.headers)+"; StatusCode: "+e.statusCode+"; Body"+(Qi.BufferUtils.isBuffer(e.body)?" (Base64): "+Qi.BufferUtils.base64Encode(e.body):": "+e.body))}(a,e,t,r,s.logger),a}catch(e){return{error:new rr("Unexpected error in Http.doUri: "+Mr(e),500,5e4)}}})()}};function As(e,t,n){for(var i,r,s,a=0;a<e.length;a++)if(i=e[a],n&&(i=i[n]),Array.isArray(i)){for(;-1!==(r=i.indexOf(t));)i.splice(r,1);n&&0===i.length&&delete e[a][n]}else if(cr(i))for(s in i)Object.prototype.hasOwnProperty.call(i,s)&&Array.isArray(i[s])&&As([i],t,s)}var Os=class{constructor(e){this.logger=e,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];if(1===t.length){var i=t[0];if("function"!=typeof i)throw new Error("EventListener.on(): Invalid arguments: "+Qi.Config.inspect(t));this.any.push(i)}if(2===t.length){var[r,s]=t;if("function"!=typeof s)throw new Error("EventListener.on(): Invalid arguments: "+Qi.Config.inspect(t));if(ur(r))this.any.push(s);else if(Array.isArray(r))r.forEach(e=>{this.on(e,s)});else{if("string"!=typeof r)throw new Error("EventListener.on(): Invalid arguments: "+Qi.Config.inspect(t));(this.events[r]||(this.events[r]=[])).push(s)}}}off(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];if(0==t.length||ur(t[0])&&ur(t[1]))return this.any=[],this.events=Object.create(null),this.anyOnce=[],void(this.eventsOnce=Object.create(null));var[i,r]=t,s=null,a=null;if(1!==t.length&&r){if("function"!=typeof r)throw new Error("EventEmitter.off(): invalid arguments:"+Qi.Config.inspect(t));[a,s]=[i,r]}else"function"==typeof i?s=i:a=i;if(s&&ur(a))As([this.any,this.events,this.anyOnce,this.eventsOnce],s);else if(Array.isArray(a))a.forEach(e=>{this.off(e,s)});else{if("string"!=typeof a)throw new Error("EventEmitter.off(): invalid arguments:"+Qi.Config.inspect(t));s?As([this.events,this.eventsOnce],s,a):(delete this.events[a],delete this.eventsOnce[a])}}listeners(e){if(e){var t=this.events[e]||[];return this.eventsOnce[e]&&Array.prototype.push.apply(t,this.eventsOnce[e]),t.length?t:null}return this.any.length?this.any:null}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];var r={event:e},s=[];this.anyOnce.length&&(Array.prototype.push.apply(s,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(s,this.any);var a=this.eventsOnce[e];a&&(Array.prototype.push.apply(s,a),delete this.eventsOnce[e]);var o=this.events[e];o&&Array.prototype.push.apply(s,o),s.forEach(e=>{!function(e,t,n,i){try{n.apply(t,i)}catch(t){tr.logAction(e,tr.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+t+"; stack = "+(t&&t.stack))}}(this.logger,r,e,n)})}once(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var i=t.length;if(0===i||1===i&&"function"!=typeof t[0]){var r=t[0];return new Promise(e=>{this.once(r,e)})}var[s,a]=t;if(1===t.length&&"function"==typeof s)this.anyOnce.push(s);else if(ur(s)){if("function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+Qi.Config.inspect(t));this.anyOnce.push(a)}else if(Array.isArray(s)){var o=this,l=function(){var e=Array.prototype.slice.call(arguments);if(s.forEach(function(e){o.off(e,l)}),"function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+Qi.Config.inspect(t));a.apply(this,e)};s.forEach(function(e){o.on(e,l)})}else{if("string"!=typeof s)throw new Error("EventEmitter.once(): Invalid arguments:"+Qi.Config.inspect(t));var c=this.eventsOnce[s]||(this.eventsOnce[s]=[]);if(a){if("function"!=typeof a)throw new Error("EventEmitter.once(): Invalid arguments:"+Qi.Config.inspect(t));c.push(a)}}}whenState(e,t){var n=this;return c(function*(){if("string"!=typeof e||"string"!=typeof t)throw new Error("whenState requires a valid state String argument");return e===t?null:n.once(e)})()}},Ms={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},Rs=[];Object.keys(Ms).forEach(function(e){Rs[Ms[e]]=e});var Ps={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},Ls=Object.keys(Ps);Ps.MODE_ALL=Ps.PRESENCE|Ps.PUBLISH|Ps.SUBSCRIBE|Ps.PRESENCE_SUBSCRIBE|Ps.ANNOTATION_PUBLISH|Ps.ANNOTATION_SUBSCRIBE|Ps.OBJECT_SUBSCRIBE|Ps.OBJECT_PUBLISH;var Us=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function Ds(){return(Ds=c(function*(e,t){var{data:n,encoding:i}=yield Ns(e.data,e.encoding,t);return e.data=n,e.encoding=i,e})).apply(this,arguments)}function Ns(e,t,n){return Bs.apply(this,arguments)}function Bs(){return(Bs=c(function*(e,t,n){var i=n.channelCipher,r=e,s=t?t+"/":"";return Qi.BufferUtils.isBuffer(r)||(r=Qi.BufferUtils.utf8Encode(String(r)),s+="utf-8/"),{data:yield i.encrypt(r),encoding:s=s+"cipher+"+i.algorithm}})).apply(this,arguments)}function Hs(){return Hs=c(function*(e,t){var{data:n,encoding:i}=qs(e.data,e.encoding);return e.data=n,e.encoding=i,null!=t&&t.cipher?function(e,t){return Ds.apply(this,arguments)}(e,t):e}),Hs.apply(this,arguments)}function qs(e,t){if("string"==typeof e||Qi.BufferUtils.isBuffer(e)||null==e)return{data:e,encoding:t};if(cr(e)||Array.isArray(e))return{data:JSON.stringify(e),encoding:t?t+"/json":"json"};throw new rr("Data type is unsupported",40013,400)}function Fs(){return(Fs=c(function*(e,t){var{data:n,encoding:i,error:r}=yield js(e.data,e.encoding,t);if(e.data=n,e.encoding=i,r)throw r})).apply(this,arguments)}function js(e,t,n){return Ws.apply(this,arguments)}function Ws(){return Ws=c(function*(e,t,n){var i,r=function(e){return e&&e.channelOptions?e:{channelOptions:e,plugins:{},baseEncodedPreviousPayload:void 0}}(n),s=e,a=e,o=t;if(t){var l,c=t.split("/"),d=c.length,u="";try{for(;(l=d)>0;){var h=c[--d].match(/([-\w]+)(\+([\w-]+))?/);if(!h)break;switch(u=h[1]){case"base64":a=Qi.BufferUtils.base64Decode(String(a)),l==c.length&&(s=a);continue;case"utf-8":a=Qi.BufferUtils.utf8Decode(a);continue;case"json":a=JSON.parse(a);continue;case"cipher":if(null!=r.channelOptions&&r.channelOptions.cipher&&r.channelOptions.channelCipher){var p=h[3],v=r.channelOptions.channelCipher;if(p!=v.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");a=yield v.decrypt(a);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 g=r.baseEncodedPreviousPayload;"string"==typeof g&&(g=Qi.BufferUtils.utf8Encode(g));var f=Qi.BufferUtils.toBuffer(g);a=Qi.BufferUtils.toBuffer(a),s=a=Qi.BufferUtils.arrayBufferViewToBuffer(r.plugins.vcdiff.decode(a,f))}catch(e){throw new rr("Vcdiff delta decode failed with "+e,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(e){var _=e;i=new rr("Error processing the "+u+" encoding, decoder returned ‘"+_.message+"’",_.code||40013,400)}finally{o=l<=0?null:c.slice(0,l).join("/")}}return i?{error:i,data:a,encoding:o}:(r.baseEncodedPreviousPayload=s,{data:a,encoding:o})}),Ws.apply(this,arguments)}function $s(){var e=arguments.length>0?"json":"msgpack",{data:t,encoding:n}=zs(this.data,this.encoding,e);return Object.assign({},this,{encoding:n,data:t})}function zs(e,t,n){return e&&Qi.BufferUtils.isBuffer(e)?"msgpack"===n?{data:Qi.BufferUtils.toBuffer(e),encoding:t}:{data:Qi.BufferUtils.base64Encode(e),encoding:t?t+"/base64":"base64"}:{data:e,encoding:t}}var Vs={encryptData:Ns,encodeData:qs,encodeDataForWire:zs,decodeData:js};function Gs(e){var t,{id:n,connectionId:i,timestamp:r}=e;switch(e.action){case Ms.MESSAGE:t=e.messages;break;case Ms.PRESENCE:case Ms.SYNC:t=e.presence;break;case Ms.ANNOTATION:t=e.annotations;break;case Ms.OBJECT:case Ms.OBJECT_SYNC:t=e.state;break;default:throw new rr("Unexpected action "+e.action,4e4,400)}for(var s=0;s<t.length;s++){var a=t[s];a.connectionId||(a.connectionId=i),a.timestamp||(a.timestamp=r),n&&!a.id&&(a.id=n+":"+s)}}function Ks(e,t){var n="["+t;for(var i in e)"data"===i?"string"==typeof e.data?n+="; data="+e.data:Qi.BufferUtils.isBuffer(e.data)?n+="; data (buffer)="+Qi.BufferUtils.base64Encode(e.data):void 0!==e.data&&(n+="; data (json)="+JSON.stringify(e.data)):!i||"extras"!==i&&"operation"!==i?"version"===i?n+="; version="+JSON.stringify(e[i]):"annotations"===i?n+="; annotations="+JSON.stringify(e[i]):void 0!==e[i]&&(n+="; "+i+"="+e[i]):n+="; "+i+"="+JSON.stringify(e[i]);return n+="]"}var Js=class{},Qs=class{constructor(e){var t,n,i,r,s,a,o,l,c,d;this.Platform=Qi,this.ErrorInfo=rr,this.Logger=tr,this.Defaults=vs,this.Utils=nr,this.EventEmitter=Os,this.MessageEncoding=Vs,this._additionalHTTPRequestImplementations=null!=(t=e.plugins)?t:null,this.logger=new tr,this.logger.setLog(e.logLevel,e.logHandler),this._MsgPack=null!=(i=null==(n=e.plugins)?void 0:n.MsgPack)?i:null;var u=this.options=vs.normaliseOptions(e,this._MsgPack,this.logger);if(u.key){var h=u.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!h){var p="invalid key parameter";throw tr.logAction(this.logger,tr.LOG_ERROR,"BaseClient()",p),new rr(p,40400,404)}u.keyName=h[1],u.keySecret=h[2]}if("clientId"in u){if("string"!=typeof u.clientId&&null!==u.clientId)throw new rr("clientId must be either a string or null",40012,400);if("*"===u.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._currentFallback=null,this.serverTimeOffset=null,this.http=new Es(this),this.auth=new xs(this,u),this._rest=(null==(r=e.plugins)?void 0:r.Rest)?new e.plugins.Rest(this):null,this._Crypto=null!=(a=null==(s=e.plugins)?void 0:s.Crypto)?a:null,this.__FilteredSubscriptions=null!=(l=null==(o=e.plugins)?void 0:o.MessageInteractions)?l:null,this._Annotations=null!=(d=null==(c=e.plugins)?void 0:c.Annotations)?d:null}get rest(){return this._rest||Xr("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||Xr("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var e;return(null==(e=this.options.plugins)?void 0:e.Push)&&this.push.LocalDevice||Xr("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(e){return vs.getHttpScheme(this.options)+e+":"+vs.getPort(this.options,!1)}stats(e){var t=this;return c(function*(){return t.rest.stats(e)})()}time(e){var t=this;return c(function*(){return t.rest.time(e)})()}request(e,t,n,i,r,s){var a=this;return c(function*(){return a.rest.request(e,t,n,i,r,s)})()}batchPublish(e){return this.rest.batchPublish(e)}batchPresence(e){return this.rest.batchPresence(e)}setLog(e){this.logger.setLog(e.level,e.handler)}getTimestamp(e){var t=this;return c(function*(){return!t.isTimeOffsetSet()&&e?t.time():t.getTimestampUsingOffset()})()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return null!==this.serverTimeOffset}};Qs.Platform=Qi;var Xs=Qs,Ys=["message.create","message.update","message.delete","meta","message.summary","message.append"];function Zs(e){var t=0;return e.name&&(t+=e.name.length),e.clientId&&(t+=e.clientId.length),e.extras&&(t+=JSON.stringify(e.extras).length),e.data&&(t+=Pr(e.data)),t}function ea(){return(ea=c(function*(e,t){return Promise.all(e.map(e=>e.encode(t)))})).apply(this,arguments)}var ta=class e extends Js{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[e,t]of Object.entries(this.annotations.summary))if(e.endsWith(":distinct.v1")||e.endsWith(":unique.v1")||e.endsWith(":multiple.v1"))for(var[,n]of Object.entries(t))n.clipped||(n.clipped=!1);else e.endsWith(":flag.v1")&&(t.clipped||(t.clipped=!1))}encode(e){var t=this;return c(function*(){return function(e,t){return Hs.apply(this,arguments)}(Object.assign(new na,t,{action:Ys.indexOf(t.action||"message.create")}),e)})()}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}toString(){return Ks(this,"Message")}},na=class e extends Js{toJSON(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return $s.call(this,...t)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}decodeWithErr(e,t){var n=this;return c(function*(){var i,r,s=Object.assign(new ta,Ki(Gi({},n),{action:(i=n.action,Ys[i||0]||"unknown")}));try{yield function(e,t){return Fs.apply(this,arguments)}(s,e)}catch(e){tr.logAction(t,tr.LOG_ERROR,"WireMessage.decode()",Mr(e)),r=e}return s.expandFields(),{decoded:s,err:r}})()}decode(e,t){var n=this;return c(function*(){var{decoded:i}=yield n.decodeWithErr(e,t);return i})()}toString(){return Ks(this,"WireMessage")}},ia=ta,ra=class{constructor(e,t,n,i,r){this.previous=e,this.current=t,"attached"===t&&(this.resumed=n,this.hasBacklog=i),r&&(this.reason=r)}},sa=function(){};function aa(e){var t=e||{},{agent:n}=t;return((e,t)=>{var n={};for(var i in e)$i.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&Wi)for(var i of Wi(e))t.indexOf(i)<0&&zi.call(e,i)&&(n[i]=e[i]);return n})(t,["agent"])}var oa=class e extends Os{constructor(e,t,n){var i,r,s;super(e.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=function(){var e=c(function*(e){var t=this.client.rest.channelMixin;if(e&&e.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 e.untilAttach,e.from_serial=this.properties.attachSerial}return t.history(this,e)});return function(t){return e.apply(this,arguments)}}(),this.whenState=e=>Os.prototype.whenState.call(this,e,this.state),this.name=t,this.channelOptions=us(null!=(i=e._Crypto)?i:null,this.logger,n),this.client=e,this._presence=e._RealtimePresence?new e._RealtimePresence.RealtimePresence(this):null,e._Annotations&&(this._annotations=new e._Annotations.RealtimeAnnotations(this)),this.connectionManager=e.connection.connectionManager,this.state="initialized",this.subscriptions=new Os(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(n),this.errorReason=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:e.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._allChannelChanges=new Os(this.logger),(null==(r=e.options.plugins)?void 0:r.Push)&&(this._push=new e.options.plugins.Push.PushChannel(this)),(null==(s=e.options.plugins)?void 0:s.LiveObjects)&&(this._object=new e.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this._presence||Xr("RealtimePresence"),this._presence}get annotations(){return this._annotations||Xr("Annotations"),this._annotations}get push(){return this._push||Xr("Push"),this._push}get object(){return this._object||Xr("LiveObjects"),this._object}invalidStateError(){return new rr("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(e){return"function"==typeof(e=Array.prototype.slice.call(e))[0]&&e.unshift(null),e}setOptions(e){var t=this;return c(function*(){var n,i=t.channelOptions,r=function(e){if(e&&"params"in e&&!cr(e.params))return new rr("options.params must be an object",4e4,400);if(e&&"modes"in e){if(!Array.isArray(e.modes))return new rr("options.modes must be an array",4e4,400);for(var t=0;t<e.modes.length;t++){var n=e.modes[t];if(!n||"string"!=typeof n||!Us.includes(String.prototype.toUpperCase.call(n)))return new rr("Invalid channel mode: "+n,4e4,400)}}}(e);if(r)throw r;if(t.channelOptions=us(null!=(n=t.client._Crypto)?n:null,t.logger,e),t._decodingContext&&(t._decodingContext.channelOptions=t.channelOptions),t._shouldReattachToSetOptions(e,i))return t.attachImpl(),new Promise((e,n)=>{t._allChannelChanges.once(["attached","update","detached","failed"],function(t){switch(this.event){case"update":case"attached":e();break;default:n(t.reason)}})})})()}_shouldReattachToSetOptions(e,t){if("attached"!==this.state&&"attaching"!==this.state)return!1;if(null==e?void 0:e.params){var n=aa(e.params),i=aa(t.params);if(Object.keys(n).length!==Object.keys(i).length)return!0;if(!Vr(i,n))return!0}return!(!(null==e?void 0:e.modes)||t.modes&&Jr(e.modes,t.modes))}publish(){var e=arguments,t=this;return c(function*(){var n,i,r=e.length<=0?void 0:e[0],s=e.length<=1?void 0:e[1];if("string"==typeof r||null==r)n=[ia.fromValues({name:r,data:s})],i=e.length<=2?void 0:e[2];else if(cr(r))n=[ia.fromValues(r)],i=e.length<=1?void 0:e[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=ia.fromValuesArray(r),i=e.length<=1?void 0:e[1]}var a=t.client.options.maxMessageSize,o=yield function(e,t){return ea.apply(this,arguments)}(n,t.channelOptions),l=function(e){for(var t,n=0,i=0;i<e.length;i++)n+=(t=e[i]).size||(t.size=Zs(t));return n}(o);if(l>a)throw new rr("Maximum size of messages that can be published at once exceeded (was "+l+" bytes; limit is "+a+" bytes)",40009,400);t.throwIfUnpublishableState();var c=ua({action:Ms.MESSAGE,channel:t.name,messages:o,params:i?Er(i):void 0});return(yield t.sendMessage(c))||{serials:[]}})()}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if("failed"===this.state||"suspended"===this.state)throw this.invalidStateError()}onEvent(e){for(var t=this.subscriptions,n=0;n<e.length;n++){var i=e[n];t.emit(i.name,i)}}attach(){var e=this;return c(function*(){return"attached"===e.state?null:new Promise((t,n)=>{e._attach(!1,null,(e,i)=>e?n(e):t(i))})})()}_attach(e,t,n){n||(n=e=>{e&&tr.logAction(this.logger,tr.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+e.toString())});var i=this.connectionManager;i.activeState()?(("attaching"!==this.state||e)&&this.requestState("attaching",t),this.once(function(e){switch(this.event){case"attached":null==n||n(null,e);break;case"detached":case"suspended":case"failed":null==n||n(e.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 e=ua({action:Ms.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&e.encodeModesToFlags(Fr(this.channelOptions.modes)),this._attachResume&&e.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(e.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(e).catch(sa)}detach(){var e=this;return c(function*(){var t=e.connectionManager;switch(e.state){case"suspended":return void e.notifyState("detached");case"detached":return;case"failed":throw new rr("Unable to detach; channel state = failed",90001,400);default:if("connected"!==t.state.state)return void e.notifyState("detached");e.requestState("detaching");case"detaching":return new Promise((n,i)=>{e.once(function(e){switch(this.event){case"detached":n();break;case"attached":case"suspended":case"failed":i(e.reason||t.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 e=ua({action:Ms.DETACH,channel:this.name});this.sendMessage(e).catch(sa)}subscribe(){var t=arguments,n=this;return c(function*(){for(var i=t.length,r=new Array(i),s=0;s<i;s++)r[s]=t[s];var[a,o]=e.processListenerArgs(r);if("failed"===n.state)throw rr.fromValues(n.invalidStateError());return a&&"object"==typeof a&&!Array.isArray(a)?n.client._FilteredSubscriptions.subscribeFilter(n,a,o):n.subscriptions.on(a,o),!1!==n.channelOptions.attachOnSubscribe?n.attach():null})()}unsubscribe(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];var[s,a]=e.processListenerArgs(i);"object"==typeof s&&!a||(null==(t=this.filteredSubscriptions)?void 0:t.has(a))?this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,s,a).forEach(e=>this.subscriptions.off(e)):this.subscriptions.off(s,a)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new sr("Unable to sync to channel; not attached",4e4)}var e=this.connectionManager;if(!e.activeState())throw e.getError();var t=ua({action:Ms.SYNC,channel:this.name});this.syncChannelSerial&&(t.channelSerial=this.syncChannelSerial),e.send(t)}sendMessage(e){var t=this;return c(function*(){return new Promise((n,i)=>{t.connectionManager.send(e,t.client.options.queueMessages,(e,t)=>{e?i(e):n(t)})})})()}sendPresence(e){var t=this;return c(function*(){var n=ua({action:Ms.PRESENCE,channel:t.name,presence:e});yield t.sendMessage(n)})()}sendState(e){var t=this;return c(function*(){var n=ua({action:Ms.OBJECT,channel:t.name,state:e});yield t.sendMessage(n)})()}processMessage(e){var t=this;return c(function*(){e.action!==Ms.ATTACHED&&e.action!==Ms.MESSAGE&&e.action!==Ms.PRESENCE&&e.action!==Ms.OBJECT&&e.action!==Ms.ANNOTATION||t.setChannelSerial(e.channelSerial);var n,i=!1;switch(e.action){case Ms.ATTACHED:t.properties.attachSerial=e.channelSerial,t._mode=e.getMode(),t.params=e.params||{};var r=e.decodeModesFromFlags();t.modes=r&&qr(r)||void 0;var s=e.hasFlag("RESUMED"),a=e.hasFlag("HAS_PRESENCE"),o=e.hasFlag("HAS_BACKLOG"),l=e.hasFlag("HAS_OBJECTS");if("attached"===t.state){s||(t._presence&&t._presence.onAttached(a),t._object&&t._object.onAttached(l));var c=new ra(t.state,t.state,s,o,e.error);t._allChannelChanges.emit("update",c),s&&!t.channelOptions.updateOnAttached||t.emit("update",c)}else"detaching"===t.state?t.checkPendingState():t.notifyState("attached",e.error,s,a,o,l);break;case Ms.DETACHED:var d=e.error?rr.fromValues(e.error):new rr("Channel detached",90001,404);"detaching"===t.state?t.notifyState("detached",d):"attaching"===t.state?t.notifyState("suspended",d):"attached"!==t.state&&"suspended"!==t.state||t.requestState("attaching",d);break;case Ms.SYNC:if(i=!0,n=t.syncChannelSerial=e.channelSerial,!e.presence)break;case Ms.PRESENCE:if(!e.presence)break;Gs(e);var u=t.channelOptions;if(t._presence){var h=yield Promise.all(e.presence.map(e=>e.decode(u,t.logger)));t._presence.setPresence(h,i,n)}break;case Ms.OBJECT:case Ms.OBJECT_SYNC:if(!t._object||!e.state)return;Gs(e);var p=t.client.connection.connectionManager.getActiveTransportFormat(),v=e.state.map(e=>e.decode(t.client,p));e.action===Ms.OBJECT?t._object.handleObjectMessages(v):t._object.handleObjectSyncMessages(v,e.channelSerial);break;case Ms.MESSAGE:if("attached"!==t.state)return;Gs(e);var g=e.messages,f=g[0],_=g[g.length-1];if(f.extras&&f.extras.delta&&f.extras.delta.from!==t._lastPayload.messageId){var m='Delta message decode failure - previous message not available for message "'+e.id+'" on this channel "'+t.name+'".';tr.logAction(t.logger,tr.LOG_ERROR,"RealtimeChannel.processMessage()",m),t._startDecodeFailureRecovery(new rr(m,40018,400));break}for(var y=[],b=0;b<g.length;b++){var{decoded:w,err:C}=yield g[b].decodeWithErr(t._decodingContext,t.logger);if(y[b]=w,C)switch(C.code){case 40018:return void t._startDecodeFailureRecovery(C);case 40019:case 40021:return void t.notifyState("failed",C)}}t._lastPayload.messageId=_.id,t._lastPayload.protocolMessageChannelSerial=e.channelSerial,t.onEvent(y);break;case Ms.ANNOTATION:Gs(e);var S=t.channelOptions;if(t._annotations){var k=yield Promise.all((e.annotations||[]).map(e=>e.decode(S,t.logger)));t._annotations._processIncoming(k)}break;case Ms.ERROR:var x=e.error;x&&80016==x.code?t.checkPendingState():t.notifyState("failed",rr.fromValues(x))}})()}_startDecodeFailureRecovery(e){this._lastPayload.decodeFailureRecoveryInProgress||(this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,e,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){}notifyState(e,t,n,i,r,s){if(this.clearStateTimer(),["detached","suspended","failed"].includes(e)&&(this.properties.channelSerial=null),e!==this.state){this._presence&&this._presence.actOnChannelState(e,i,t),this._object&&this._object.actOnChannelState(e,s),"suspended"===e&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),t&&(this.errorReason=t);var a=new ra(this.state,e,n,r,t),o='Channel state for channel "'+this.name+'"',l=e+(t?"; reason: "+t:"");"failed"===e&&tr.logAction(this.logger,tr.LOG_ERROR,o,l),"attaching"!==e&&"suspended"!==e&&(this.retryCount=0),"attached"===e&&this.onAttached(),"attached"===e?this._attachResume=!0:"detaching"!==e&&"failed"!==e||(this._attachResume=!1),this.state=e,this._allChannelChanges.emit(e,a),this.emit(e,a)}}requestState(e,t){this.notifyState(e,t),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 e=new rr("Channel attach timed out",90007,408);this.notifyState("suspended",e);break;case"detaching":var t=new rr("Channel detach timed out",90007,408);this.notifyState("attached",t);break;default:this.checkPendingState()}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){var e=this.stateTimer;e&&(clearTimeout(e),this.stateTimer=null)}startRetryTimer(){if(!this.retryTimer){this.retryCount++;var e=$r(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{"suspended"===this.state&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,this.requestState("attaching"))},e)}}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){var e=this.state;return"initialized"===e||"detached"===e||"failed"===e?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 "+e,90001,400)}setChannelSerial(e){e&&(this.properties.channelSerial=e)}status(){var e=this;return c(function*(){return e.client.rest.channelMixin.status(e)})()}getMessage(e){var t=this;return c(function*(){return t.client.rest.channelMixin.getMessage(t,e)})()}updateMessage(e,t,n){var i=this;return c(function*(){return i.sendUpdate(e,"message.update",t,n)})()}deleteMessage(e,t,n){var i=this;return c(function*(){return i.sendUpdate(e,"message.delete",t,n)})()}appendMessage(e,t,n){var i=this;return c(function*(){return i.sendUpdate(e,"message.append",t,n)})()}sendUpdate(e,t,n,i){var r=this;return c(function*(){var s,a;if(!e.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 o=ia.fromValues(Ki(Gi({},e),{action:t,version:n})),l=yield o.encode(r.channelOptions),c=ua({action:Ms.MESSAGE,channel:r.name,messages:[l],params:i?Er(i):void 0}),d=yield r.sendMessage(c);return{versionSerial:null!=(a=null==(s=null==d?void 0:d.serials)?void 0:s[0])?a:null}})()}getMessageVersions(e,t){var n=this;return c(function*(){return n.client.rest.channelMixin.getMessageVersions(n,e,t)})()}ensureAttached(){var e=this;return c(function*(){switch(e.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":yield e.attach();break;default:throw rr.fromValues(e.invalidStateError())}})()}},la=Hr;function ca(e){var t=[];if(e)for(var n=0;n<e.length;n++)t.push(e[n].toString());return"[ "+t.join(", ")+" ]"}function da(e,t,n,i,r,s){return function(e,t,n,i){var r,s,a,o,l;e.error&&(r=rr.fromValues(e.error));e.messages&&(s=na.fromValuesArray(e.messages));t&&e.presence&&(a=t.WirePresenceMessage.fromValuesArray(e.presence));n&&e.annotations&&(o=n.WireAnnotation.fromValuesArray(e.annotations));i&&e.state&&(l=i.WireObjectMessage.fromValuesArray(e.state,nr,Vs));return Object.assign(new pa,Ki(Gi({},e),{presence:a,messages:s,annotations:o,state:l,error:r}))}(Br(e,t,s),n,i,r)}function ua(e){return Object.assign(new pa,e)}function ha(e,t,n,i){var r="[ProtocolMessage";void 0!==e.action&&(r+="; action="+Rs[e.action]||e.action);for(var s,a=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"],o=0;o<a.length;o++)void 0!==e[s=a[o]]&&(r+="; "+s+"="+e[s]);if(e.messages&&(r+="; messages="+ca(na.fromValuesArray(e.messages))),e.presence&&t&&(r+="; presence="+ca(t.WirePresenceMessage.fromValuesArray(e.presence))),e.annotations&&n&&(r+="; annotations="+ca(n.WireAnnotation.fromValuesArray(e.annotations))),e.state&&i&&(r+="; state="+ca(i.WireObjectMessage.fromValuesArray(e.state,nr,Vs))),e.error&&(r+="; error="+rr.fromValues(e.error).toString()),e.auth&&e.auth.accessToken&&(r+="; token="+e.auth.accessToken),e.flags&&(r+="; flags="+Ls.filter(e.hasFlag).join(",")),e.params){var l="";Sr(e.params,function(t){l.length>0&&(l+="; "),l+=t+"="+e.params[t]}),l.length>0&&(r+="; params=["+l+"]")}return r+="]"}var pa=class{constructor(){this.hasFlag=e=>(this.flags&Ps[e])>0}setFlag(e){return this.flags=this.flags|Ps[e]}getMode(){return(this.flags||0)&Ps.MODE_ALL}encodeModesToFlags(e){e.forEach(e=>this.setFlag(e))}decodeModesFromFlags(){var e=[];return Us.forEach(t=>{this.hasFlag(t)&&e.push(t)}),e.length>0?e:void 0}},va=class extends Os{constructor(e){super(e),this.messages=[]}count(){return this.messages.length}push(e){this.messages.push(e)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(e){this.messages.push.apply(this.messages,e)}prepend(e){this.messages.unshift.apply(this.messages,e)}completeMessages(e,t,n){t=t||null;var i=this.messages;if(0===i.length)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");var r=[];if("all"===e)r=i.splice(0);else{var s=i[0];if(s){var a=s.message.msgSerial,o=e.serial+e.count;o>a&&(r=i.splice(0,o-a))}}for(var l=0;l<r.length;l++){var c=r[l],d=null==n?void 0:n[l];c.callback(t,d)}0==i.length&&this.emit("idle")}completeAllMessages(e){this.completeMessages("all",e)}resetSendAttempted(){for(var e of this.messages)e.sendAttempted=!1}clear(){this.messages=[],this.emit("idle")}},ga=class{constructor(e,t){this.message=e,this.callback=t,this.merged=!1;var n=e.action;this.sendAttempted=!1,this.ackRequired="number"==typeof n&&[Ms.MESSAGE,Ms.PRESENCE,Ms.ANNOTATION,Ms.OBJECT].includes(n)}},fa=class extends Os{constructor(e){super(e.logger),this.transport=e,this.messageQueue=new va(this.logger),e.on("ack",(e,t,n)=>{this.onAck(e,t,n)}),e.on("nack",(e,t,n)=>{this.onNack(e,t,n)})}onAck(e,t,n){this.messageQueue.completeMessages({serial:e,count:t},null,n)}onNack(e,t,n){tr.logAction(this.logger,tr.LOG_ERROR,"Protocol.onNack()","serial = "+e+"; count = "+t+"; err = "+Mr(n)),n||(n=new rr("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:e,count:t},n)}onceIdle(e){var t=this.messageQueue;0!==t.count()?t.once("idle",e):e()}send(e){e.ackRequired&&this.messageQueue.push(e),this.logger.shouldLog(tr.LOG_MICRO)&&tr.logActionNoStrip(this.logger,tr.LOG_MICRO,"Protocol.send()","sending msg; "+ha(e.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._liveObjectsPlugin)),e.sendAttempted=!0,this.transport.send(e.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){var e=this.transport;this.onceIdle(function(){e.disconnect()})}},_a=class{constructor(e,t,n,i){this.previous=e,this.current=t,n&&(this.retryIn=n),i&&(this.reason=i)}},ma={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001};var ya,ba,wa={disconnected:()=>rr.fromValues({statusCode:400,code:ma.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>rr.fromValues({statusCode:400,code:ma.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>rr.fromValues({statusCode:400,code:ma.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>rr.fromValues({statusCode:400,code:ma.CLOSING,message:"Connection closing"}),closed:()=>rr.fromValues({statusCode:400,code:ma.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>rr.fromValues({statusCode:500,code:ma.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>rr.fromValues({statusCode:500,code:ma.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})},Ca=ua({action:Ms.CLOSE}),Sa=ua({action:Ms.DISCONNECT}),ka=class extends Os{constructor(e,t,n,i){super(e.logger),i&&(n.format=void 0,n.heartbeats=!0),this.connectionManager=e,this.auth=t,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",wa.closed())}disconnect(e){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",e||wa.disconnected())}fail(e){this.isConnected&&this.requestDisconnect(),this.finish("failed",e||wa.failed())}finish(e,t){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(e,t),this.dispose())}onProtocolMessage(e){switch(this.logger.shouldLog(tr.LOG_MICRO)&&tr.logActionNoStrip(this.logger,tr.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+ha(e,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),e.action){case Ms.HEARTBEAT:tr.logActionNoStrip(this.logger,tr.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",e.id);break;case Ms.CONNECTED:this.onConnect(e),this.emit("connected",e.error,e.connectionId,e.connectionDetails,e);break;case Ms.CLOSED:this.onClose(e);break;case Ms.DISCONNECTED:this.onDisconnect(e);break;case Ms.ACK:this.emit("ack",e.msgSerial,e.count,e.res);break;case Ms.NACK:this.emit("nack",e.msgSerial,e.count,e.error);break;case Ms.SYNC:this.connectionManager.onChannelMessage(e,this);break;case Ms.ACTIVATE:break;case Ms.AUTH:Nr(this.auth.authorize(),e=>{e&&tr.logAction(this.logger,tr.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+Mr(e))});break;case Ms.ERROR:if(void 0===e.channel){this.onFatalError(e);break}this.connectionManager.onChannelMessage(e,this);break;default:this.connectionManager.onChannelMessage(e,this)}}onConnect(e){if(this.isConnected=!0,!e.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");var t=e.connectionDetails.maxIdleInterval;t&&(this.maxIdleInterval=t+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(e){var t=e&&e.error;this.finish("disconnected",t)}onFatalError(e){var t=e&&e.error;this.finish("failed",t)}onClose(e){var t=e&&e.error;this.finish("closed",t)}requestClose(){this.send(Ca)}requestDisconnect(){this.send(Sa)}ping(e){var t={action:Ms.HEARTBEAT};e&&(t.id=e),this.send(ua(t))}dispose(){this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=Date.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(e){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},e))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;var e=Date.now()-this.lastActivity,t=this.maxIdleInterval-e;if(t<=0){var n="No activity seen from realtime in "+e+"ms; assuming connection has dropped";tr.logAction(this.logger,tr.LOG_ERROR,"Transport.onIdleTimerExpire()",n),this.disconnect(new rr(n,80003,408))}else this.setIdleTimer(t+100)}static tryConnect(e,t,n,i,r){var s,a=new e(t,n,i),o=function(e){clearTimeout(s),r({event:this.event,error:e})},l=t.options.timeouts.realtimeRequestTimeout;return s=setTimeout(()=>{a.off(["preconnect","disconnected","failed"]),a.dispose(),o.call({event:"disconnected"},new rr("Timeout waiting for transport to indicate itself viable",5e4,500))},l),a.on(["failed","disconnected"],o),a.on("preconnect",function(){clearTimeout(s),a.off(["failed","disconnected"],o),r(null,a)}),a.connect(),a}static isAvailable(){throw new rr("isAvailable not implemented for transport",5e4,500)}};(ba=ya||(ya={})).WebSocket="web_socket",ba.Comet="comet",ba.XhrPolling="xhr_polling";var xa="undefined"!=typeof global?global:"undefined"!=typeof window?window:self,Ta=()=>{var e;return void 0!==Qi.WebStorage&&(null==(e=Qi.WebStorage)?void 0:e.localSupported)},Ia=()=>{var e;return void 0!==Qi.WebStorage&&(null==(e=Qi.WebStorage)?void 0:e.sessionSupported)},Ea=function(){},Aa="ably-transport-preference";function Oa(e){try{return JSON.parse(e)}catch(e){return null}}var Ma=class{constructor(e,t,n,i){this.options=e,this.host=t,this.mode=n,this.connectionKey=i,this.format=e.useBinaryProtocol?"msgpack":"json"}getConnectParams(e){var t=e?or(e):{},n=this.options;switch(this.mode){case"resume":t.resume=this.connectionKey;break;case"recover":var i=Oa(n.recover);i&&(t.recover=i.connectionKey)}return void 0!==n.clientId&&(t.clientId=n.clientId),!1===n.echoMessages&&(t.echo="false"),void 0!==this.format&&(t.format=this.format),void 0!==this.stream&&(t.stream=this.stream),void 0!==this.heartbeats&&(t.heartbeats=this.heartbeats),t.v=vs.protocolVersion,t.agent=cs(this.options),void 0!==n.transportParams&&ar(t,n.transportParams),t}toString(){var e="[mode="+this.mode;return this.host&&(e+=",host="+this.host),this.connectionKey&&(e+=",connectionKey="+this.connectionKey),this.format&&(e+=",format="+this.format),e+="]"}},Ra=class e extends Os{constructor(e,t){super(e.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=e,this.initTransports(),this.options=t;var n=t.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 va(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=fr(t.transports||vs.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(ya.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(ya.XhrPolling)?this.baseTransport=ya.XhrPolling:this.transports.includes(ya.Comet)&&(this.baseTransport=ya.Comet),this.domains=vs.getHosts(t),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 tr.logAction(this.logger,tr.LOG_ERROR,"realtime.ConnectionManager()",r),new Error(r)}var s=Qi.Config.addEventListener;s&&(Ia()&&"function"==typeof t.recover&&s("beforeunload",this.persistConnection.bind(this)),!0===t.closeOnUnload&&s("beforeunload",()=>{this.requestState({state:"closing"})}),s("online",()=>{var e;this.state==this.states.disconnected||this.state==this.states.suspended?this.requestState({state:"connecting"}):this.state==this.states.connecting&&(null==(e=this.pendingTransport)||e.off(),this.disconnectAllTransports(),this.startConnect())}),s("offline",()=>{this.state==this.states.connected&&this.disconnectAllTransports()}))}static supportedTransports(e){var t={supportedTransports:{}};return this.initTransports(e,t),t.supportedTransports}static initTransports(e,t){var n=Gi(Gi({},Qi.Transports.bundledImplementations),e);[ya.WebSocket,...Qi.Transports.order].forEach(e=>{var i=n[e];i&&i.isAvailable()&&(t.supportedTransports[e]=i)})}initTransports(){e.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(e,t){return new Ma(this.options,e,t,this.connectionKey)}getTransportParams(e){(e=>{if(this.connectionKey)e("resume");else if("string"!=typeof this.options.recover){var t=this.options.recover,n=this.getSessionRecoverData();this.sessionRecoveryName(),n&&"function"==typeof t?t(n,t=>{t?(this.options.recover=n.recoveryKey,e("recover")):e("clean")}):e("clean")}else e("recover")})(t=>{var n=this.createTransportParams(null,t);if("recover"===t){var i=Oa(this.options.recover);i&&(this.msgSerial=i.msgSerial)}e(n)})}tryATransport(e,t,n){this.proposedTransport=ka.tryConnect(this.supportedTransports[t],this,this.realtime.auth,e,(i,r)=>{var s,a=this.state;if(a==this.states.closing||a==this.states.closed||a==this.states.failed)return r&&r.close(),void n(!0);i?!xs.isTokenErr(i.error)||this.errorReason&&xs.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(ma).includes(s.code)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:i.error}),n(!0))):(this.errorReason=i.error,Nr(this.realtime.auth._forceNewToken(null,null),i=>{i?this.actOnErrorFromAuthorize(i):this.tryATransport(e,t,n)})):(this.setTransportPending(r,e),n(null,r))})}setTransportPending(e,t){var n=t.mode;this.pendingTransport=e,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),e.once("connected",(t,i,r)=>{this.activateTransport(t,e,i,r),"recover"===n&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});var i=this;e.on(["disconnected","closed","failed"],function(t){i.deactivateTransport(e,this.event,t)}),this.emit("transport.pending",e)}activateTransport(e,t,n,i){e&&tr.logAction(this.logger,tr.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+e),this.persistTransportPreference(t);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 t.disconnect(),!1;if(delete this.pendingTransport,!t.isConnected)return!1;var a=this.activeProtocol;this.activeProtocol=new fa(t),this.host=t.params.host;var o=i.connectionKey;if(o&&this.connectionKey!=o&&this.setConnection(n,i,!!e),this.onConnectionDetailsUpdate(i,t),Qi.Config.nextTick(()=>{t.on("connected",(e,n,i)=>{this.onConnectionDetailsUpdate(i,t),this.emit("update",new _a(s,s,null,e))})}),r.state===this.states.connected.state?e&&(this.errorReason=this.realtime.connection.errorReason=e,this.emit("update",new _a(s,s,null,e))):(this.notifyState({state:"connected",error:e}),this.errorReason=this.realtime.connection.errorReason=e||null),this.emit("transport.active",t),a)if(a.messageQueue.count()>0&&tr.logAction(this.logger,tr.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+a.transport.shortName+", new one is "+t.shortName+") finishing with "+a.messageQueue.count()+" messages still pending"),a.transport===t){var l="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+t.shortName+"; stack = "+(new Error).stack;tr.logAction(this.logger,tr.LOG_ERROR,"ConnectionManager.activateTransport()",l)}else a.finish();return!0}deactivateTransport(e,t,n){var i=this.activeProtocol,r=i&&i.getTransport()===e,s=e===this.pendingTransport,a=this.noTransportsScheduledForActivation();if(n&&n.message,r&&(this.queuePendingMessages(i.getPendingMessages()),i.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",e),r&&a||r&&"failed"===t||"closed"===t||null===i&&s){if("disconnected"===t&&n&&n.statusCode>500&&this.domains.length>1)return this.unpersistTransportPreference(),this.forceFallbackHost=!0,void this.notifyState({state:t,error:n,retryImmediately:!0});var o="failed"===t&&xs.isTokenErr(n)?"disconnected":t;this.notifyState({state:o,error:n})}else;}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(e,t,n){var i=this.connectionId;(i&&i!==e||!i&&n)&&(this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId,this.realtime.connection.id=this.connectionId=e,this.realtime.connection.key=this.connectionKey=t.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(Ia()){var e=this.createRecoveryKey();e&&this.setSessionRecoverData({recoveryKey:e,disconnectedAt:Date.now(),location:xa.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var e;return null==(e=this.activeProtocol)?void 0:e.getTransport().format}getError(){if(this.errorReason){var e=sr.fromValues(this.errorReason);return e.cause=this.errorReason,e}return this.getStateError()}getStateError(){var e,t;return null==(t=(e=wa)[this.state.state])?void 0:t.call(e)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(e){var t=e.current+(e.reason?"; reason: "+e.reason:"");"failed"===e.current&&tr.logAction(this.logger,tr.LOG_ERROR,"Connection state",t);var n=this.state=this.states[e.current];e.reason&&(this.errorReason=e.reason,this.realtime.connection.errorReason=e.reason),(n.terminal||"suspended"===n.state)&&this.clearConnection(),this.emit("connectionstate",e)}startTransitionTimer(e){this.transitionTimer&&clearTimeout(this.transitionTimer),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,this.notifyState({state:e.failState}))},e.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(e){"disconnected"!==e&&"suspended"!==e&&"connecting"!==e&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(e){this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.requestState({state:"connecting"})},e)}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&&Nr(this.realtime.http.checkConnectivity(),(e,t)=>{!e&&t||(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(e){this.webSocketGiveUpTimer=setTimeout(()=>{var t,n;this.wsCheckResult||this.baseTransport&&(this.abandonedWebSocket=!0,null==(t=this.proposedTransport)||t.dispose(),null==(n=this.pendingTransport)||n.dispose(),this.connectBase(e,++this.connectCounter))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(e){var t,n,i=e.state,r="disconnected"===i&&(this.state===this.states.connected||e.retryImmediately||this.state===this.states.connecting&&e.error&&xs.isTokenErr(e.error)&&!(this.errorReason&&xs.isTokenErr(this.errorReason)));if(i!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(e.state),"suspended"!==i&&"connected"!==i||(this.disconnectedRetryCount=0),!this.state.terminal)){var s=this.states[e.state],a=s.retryDelay;"disconnected"===s.state&&(this.disconnectedRetryCount++,a=$r(s.retryDelay,this.disconnectedRetryCount));var o=new _a(this.state.state,s.state,a,e.error||(null==(n=(t=wa)[s.state])?void 0:n.call(t)));if(r){var l=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},c=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;c&&c<1e3?setTimeout(l,1e3-c):Qi.Config.nextTick(l)}else"disconnected"!==i&&"suspended"!==i||this.startRetryTimer(a);("disconnected"===i&&!r||"suspended"===i||s.terminal)&&Qi.Config.nextTick(()=>{this.disconnectAllTransports()}),"connected"!=i||this.activeProtocol||tr.logAction(this.logger,tr.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(o),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(i,o.reason),this.failQueuedMessages(o.reason))}}requestState(e){var t,n,i=e.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 _a(this.state.state,r.state,null,e.error||(null==(n=(t=wa)[r.state])?void 0:n.call(t)));this.enactStateChange(s),"connecting"==i&&Qi.Config.nextTick(()=>{this.startConnect()}),"closing"==i&&this.closeImpl()}}startConnect(){if(this.state===this.states.connecting){var e=this.realtime.auth,t=++this.connectCounter,n=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(e=>{if("recover"===e.mode&&e.options.recover){var n=Oa(e.options.recover);n&&this.realtime.channels.recoverChannels(n.channelSerials)}t===this.connectCounter&&this.connectImpl(e,t)})};if(this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),"basic"===e.method)n();else{var i=e=>{t===this.connectCounter&&(e?this.actOnErrorFromAuthorize(e):n())};this.errorReason&&xs.isTokenErr(this.errorReason)?Nr(e._forceNewToken(null,null),i):Nr(e._ensureValidAuthCredentials(!1),i)}}}connectImpl(e,t){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(e,++this.connectCounter))}).catch(Ea),n&&n===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(e,t):this.connectWs(e,t)}}connectWs(e,t){this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(e),this.tryTransportWithFallbacks("web_socket",e,!0,t,()=>!1!==this.wsCheckResult&&!this.abandonedWebSocket)}connectBase(e,t){this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,e,!1,t,()=>!0):this.notifyState({state:"disconnected",error:new rr("No transports left to try",8e4,404)})}tryTransportWithFallbacks(e,t,n,i,r){var s=e=>{this.notifyState({state:this.states.connecting.failState,error:e})},a=this.domains.slice(),o=(e,t)=>{i===this.connectCounter&&(r()?t||e||c():t&&t.dispose())},l=a.shift();if(l){t.host=l;var c=()=>{a.length?this.realtime.http.checkConnectivity?Nr(this.realtime.http.checkConnectivity(),(n,l)=>{i===this.connectCounter&&r()&&(n?s(n):l?(t.host=Tr(a),this.tryATransport(t,e,o)):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&&a.length)return this.forceFallbackHost=!1,void c();this.tryATransport(t,e,o)}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(e,t){var n;switch(this.state.state){case"connected":var i=null==(n=this.activeProtocol)?void 0:n.getTransport();i&&i.onAuthUpdated&&i.onAuthUpdated(e);var r=ua({action:Ms.AUTH,auth:{accessToken:e.token}});this.send(r);var s=()=>{this.off(a),t(null,e)},a=e=>{"failed"===e.current&&(this.off(s),this.off(a),t(e.reason||this.getStateError()))};this.once("connectiondetails",s),this.on("connectionstate",a);break;case"connecting":this.disconnectAllTransports();default:var o=n=>{switch(n.current){case"connected":this.off(o),t(null,e);break;case"failed":case"closed":case"suspended":this.off(o),t(n.reason||this.getStateError())}};this.on("connectionstate",o),"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(e,t,n){n=n||Ea;var i=this.state;if(i.sendEvents)this.sendImpl(new ga(e,n));else if(t&&i.queueEvents)this.logger.shouldLog(tr.LOG_MICRO),this.queue(e,n);else{var r="rejecting event, queueEvent was "+t+", state was "+i.state;n(this.errorReason||new rr(r,9e4,400))}}sendImpl(e){var t=e.message;e.ackRequired&&!e.sendAttempted&&(t.msgSerial=this.msgSerial++);try{this.activeProtocol.send(e)}catch(e){tr.logAction(this.logger,tr.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+e.stack)}}queue(e,t){this.queuedMessages.push(new ga(e,t))}sendQueuedMessages(){for(var e;e=this.queuedMessages.shift();)this.sendImpl(e)}queuePendingMessages(e){e&&e.length&&this.queuedMessages.prepend(e)}failQueuedMessages(e){var t=this.queuedMessages.count();t>0&&(tr.logAction(this.logger,tr.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+t+" queued messages, err = "+Mr(e)),this.queuedMessages.completeAllMessages(e))}onChannelMessage(e,t){this.pendingChannelMessagesState.queue.push({message:e,transport:t}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;var e=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(e.message).catch(e=>{tr.logAction(this.logger,tr.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",e)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}processChannelMessage(e){var t=this;return c(function*(){yield t.realtime.channels.processChannelMessage(e)})()}ping(){var e=this;return c(function*(){var t;if("connected"!==e.state.state)throw new rr("Unable to ping service; not connected",4e4,400);var n=null==(t=e.activeProtocol)?void 0:t.getTransport();if(!n)throw e.getStateError();var i=Date.now(),r=Lr();return Yr(new Promise(e=>{var t=s=>{s===r&&(n.off("heartbeat",t),e(Date.now()-i))};n.on("heartbeat",t),n.ping(r)}),e.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")})()}abort(e){this.activeProtocol.getTransport().fail(e)}getTransportPreference(){var e,t;return this.transportPreference||Ta()&&(null==(t=null==(e=Qi.WebStorage)?void 0:e.get)?void 0:t.call(e,Aa))}persistTransportPreference(e){var t,n;this.transportPreference=e.shortName,Ta()&&(null==(n=null==(t=Qi.WebStorage)?void 0:t.set)||n.call(t,Aa,e.shortName))}unpersistTransportPreference(){var e,t;this.transportPreference=null,Ta()&&(null==(t=null==(e=Qi.WebStorage)?void 0:e.remove)||t.call(e,Aa))}actOnErrorFromAuthorize(e){if(40171===e.code)this.notifyState({state:"failed",error:e});else if(40102===e.code)this.notifyState({state:"failed",error:e});else if(e.statusCode===ys.Forbidden){var t="Client configured authentication provider returned 403; failing the connection";tr.logAction(this.logger,tr.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",t),this.notifyState({state:"failed",error:new rr(t,80019,403,e)})}else{this.notifyState({state:this.state.failState,error:new rr("Client configured authentication provider request failed",80019,401,e)})}}onConnectionDetailsUpdate(e,t){if(e){this.connectionDetails=e,e.maxMessageSize&&(this.options.maxMessageSize=e.maxMessageSize);var n=e.clientId;if(n){var i=this.realtime.auth._uncheckedSetClientId(n);if(i)return tr.logAction(this.logger,tr.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",i.message),void t.fail(i)}var r=e.connectionStateTtl;r&&(this.connectionStateTtl=r),this.maxIdleInterval=e.maxIdleInterval,this.emit("connectiondetails",e)}}checkWsConnectivity(){var e=this.options.wsConnectivityCheckUrl||vs.wsConnectivityCheckUrl,t=new Qi.Config.WebSocket(e);return new Promise((e,n)=>{var i=!1;t.onopen=()=>{i||(i=!0,e(),t.close())},t.onclose=t.onerror=()=>{i||(i=!0,n())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var e,t;return Ia()&&(null==(t=null==(e=Qi.WebStorage)?void 0:e.getSession)?void 0:t.call(e,this.sessionRecoveryName()))}setSessionRecoverData(e){var t,n;return Ia()&&(null==(n=null==(t=Qi.WebStorage)?void 0:t.setSession)?void 0:n.call(t,this.sessionRecoveryName(),e))}clearSessionRecoverData(){var e,t;return Ia()&&(null==(t=null==(e=Qi.WebStorage)?void 0:e.removeSession)?void 0:t.call(e,this.sessionRecoveryName()))}},Pa=class extends Os{constructor(e,t){super(e.logger),this.whenState=e=>Os.prototype.whenState.call(this,e,this.state),this.ably=e,this.connectionManager=new Ra(e,t),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",e=>{var t=this.state=e.current;Qi.Config.nextTick(()=>{this.emit(t,e)})}),this.connectionManager.on("update",e=>{Qi.Config.nextTick(()=>{this.emit("update",e)})})}connect(){this.connectionManager.requestState({state:"connecting"})}ping(){var e=this;return c(function*(){return e.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()}},La=class e extends Xs{constructor(t){var n,i,r,s;if(super(vs.objectifyOptions(t,!1,"BaseRealtime",tr.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._additionalTransportImplementations=e.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=null!=(i=null==(n=this.options.plugins)?void 0:n.RealtimePresence)?i:null,this._liveObjectsPlugin=null!=(s=null==(r=this.options.plugins)?void 0:r.LiveObjects)?s:null,this.connection=new Pa(this,this.options),this._channels=new Da(this),!1!==this.options.autoConnect&&this.connect()}static transportImplementationsFromPlugins(e){var t={};return(null==e?void 0:e.WebSocketTransport)&&(t[ya.WebSocket]=e.WebSocketTransport),(null==e?void 0:e.XHRPolling)&&(t[ya.XhrPolling]=e.XHRPolling),t}get channels(){return this._channels}get clientId(){return this.auth.clientId}connect(){this.connection.connect()}close(){this.connection.close()}};La.EventEmitter=Os;var Ua=La,Da=class extends Os{constructor(e){super(e.logger),this.realtime=e,this.all=Object.create(null),e.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){var e={};for(var t of wr(this.all,!0)){var n=this.all[t];n.properties.channelSerial&&(e[t]=n.properties.channelSerial)}return e}recoverChannels(e){for(var t of wr(e,!0)){this.get(t).properties.channelSerial=e[t]}}processChannelMessage(e){var t=this;return c(function*(){var n=e.channel;if(void 0!==n){var i=t.all[n];i?yield i.processMessage(e):tr.logAction(t.logger,tr.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+n)}else tr.logAction(t.logger,tr.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+e.action)})()}onTransportActive(){for(var e in this.all){var t=this.all[e];"attaching"===t.state||"detaching"===t.state?t.checkPendingState():"suspended"===t.state?t._attach(!1,null):"attached"===t.state&&t.requestState("attaching")}}propogateConnectionInterruption(e,t){var n=["attaching","attached","detaching","suspended"],i={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"}[e];for(var r in this.all){var s=this.all[r];n.includes(s.state)&&s.notifyState(i,t)}}get(e,t){e=String(e);var n=this.all[e];if(n){if(t){if(n._shouldReattachToSetOptions(t,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(t)}}else n=this.all[e]=new oa(this.realtime,e,t);return n}getDerived(e,t,n){if(t.filter){var i=Kr(t.filter),r=Gr(e);e="[filter="+i+r.qualifierParam+"]"+r.channelName}return this.get(e,n)}release(e){e=String(e);var t=this.all[e];if(t){var n=t.getReleaseErr();if(n)throw n;delete this.all[e]}}},Na=Ua,Ba=Uint8Array,Ha=Uint32Array,qa=Math.pow,Fa=new Ha(8),ja=[],Wa=new Ha(64);function $a(e){return(e-(0|e))*qa(2,32)|0}for(var za,Va,Ga=2,Ka=0;Ka<64;){for(za=!0,Va=2;Va<=Ga/2;Va++)Ga%Va===0&&(za=!1);za&&(Ka<8&&(Fa[Ka]=$a(qa(Ga,.5))),ja[Ka]=$a(qa(Ga,1/3)),Ka++),Ga++}var Ja=!!new Ba(new Ha([1]).buffer)[0];function Qa(e){return Ja?e>>>24|(e>>>16&255)<<8|(65280&e)<<8|e<<24:e}function Xa(e,t){return e>>>t|e<<32-t}function Ya(e){var t,n=Fa.slice(),i=e.length,r=8*i,s=512-(r+64)%512-1+r+65,a=new Ba(s/8),o=new Ha(a.buffer);a.set(e,0),a[i]=128,o[o.length-1]=Qa(r);for(var l=0;l<s/32;l+=16){var c=n.slice();for(t=0;t<64;t++){var d;if(t<16)d=Qa(o[l+t]);else{var u=Wa[t-15],h=Wa[t-2];d=Wa[t-7]+Wa[t-16]+(Xa(u,7)^Xa(u,18)^u>>>3)+(Xa(h,17)^Xa(h,19)^h>>>10)}Wa[t]=d|=0;for(var p=(Xa(c[4],6)^Xa(c[4],11)^Xa(c[4],25))+(c[4]&c[5]^~c[4]&c[6])+c[7]+d+ja[t],v=(Xa(c[0],2)^Xa(c[0],13)^Xa(c[0],22))+(c[0]&c[1]^c[2]&(c[0]^c[1])),g=7;g>0;g--)c[g]=c[g-1];c[0]=p+v|0,c[4]=c[4]+p|0}for(t=0;t<8;t++)n[t]=n[t]+c[t]|0}return new Ba(new Ha(n.map(function(e){return Qa(e)})).buffer)}var Za,eo=new class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(e){for(var t,n,i,r,s="",a=this.base64CharSet,o=e.byteLength,l=o%3,c=o-l,d=0;d<c;d+=3)t=(258048&(r=e[d]<<16|e[d+1]<<8|e[d+2]))>>12,n=(4032&r)>>6,i=63&r,s+=a[(16515072&r)>>18]+a[t]+a[n]+a[i];return 1==l?(t=(3&(r=e[c]))<<4,s+=a[(252&r)>>2]+a[t]+"=="):2==l&&(t=(1008&(r=e[c]<<8|e[c+1]))>>4,n=(15&r)<<2,s+=a[(64512&r)>>10]+a[t]+a[n]+"="),s}base64ToArrayBuffer(e){for(var t=null==atob?void 0:atob(e),n=t.length,i=new Uint8Array(n),r=0;r<n;r++){var s=t.charCodeAt(r);i[r]=s}return this.toArrayBuffer(i)}isBuffer(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}toBuffer(e){if(!ArrayBuffer)throw new Error("Can't convert to Buffer: browser does not support the necessary types");if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(this.toArrayBuffer(e));throw new Error("BufferUtils.toBuffer expected an ArrayBuffer or a view onto one")}toArrayBuffer(e){if(!ArrayBuffer)throw new Error("Can't convert to ArrayBuffer: browser does not support the necessary types");if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);throw new Error("BufferUtils.toArrayBuffer expected an ArrayBuffer or a view onto one")}base64Encode(e){return this.uint8ViewToBase64(this.toBuffer(e))}base64UrlEncode(e){return this.base64Encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}base64Decode(e){if(ArrayBuffer&&Qi.Config.atob)return this.base64ToArrayBuffer(e);throw new Error("Expected ArrayBuffer to exist and Platform.Config.atob to be configured")}hexEncode(e){return this.toBuffer(e).reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}hexDecode(e){if(e.length%2!=0)throw new Error("Can't create a byte array from a hex string of odd length");for(var t=new Uint8Array(e.length/2),n=0;n<t.length;n++)t[n]=parseInt(e.slice(2*n,2*(n+1)),16);return this.toArrayBuffer(t)}utf8Encode(e){if(Qi.Config.TextEncoder){var t=(new Qi.Config.TextEncoder).encode(e);return this.toArrayBuffer(t)}throw new Error("Expected TextEncoder to be configured")}utf8Decode(e){if(!this.isBuffer(e))throw new Error("Expected input of utf8decode to be an arraybuffer or typed array");if(TextDecoder)return(new TextDecoder).decode(e);throw new Error("Expected TextDecoder to be configured")}areBuffersEqual(e,t){if(!e||!t)return!1;var n=this.toArrayBuffer(e),i=this.toArrayBuffer(t);if(n.byteLength!=i.byteLength)return!1;for(var r=new Uint8Array(n),s=new Uint8Array(i),a=0;a<r.length;a++)if(r[a]!=s[a])return!1;return!0}byteLength(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}arrayBufferViewToBuffer(e){return this.toArrayBuffer(e)}concat(e){var t=e.reduce((e,t)=>e+t.byteLength,0),n=new Uint8Array(t),i=0;for(var r of e){var s=this.toBuffer(r);n.set(s,i),i+=s.byteLength}return n.buffer}sha256(e){var t=Ya(this.toBuffer(e));return this.toArrayBuffer(t)}hmacSha256(e,t){var n=function(e,t){if(e.length>64&&(e=Ya(e)),e.length<64){var n=new Uint8Array(64);n.set(e,0),e=n}for(var i=new Uint8Array(64),r=new Uint8Array(64),s=0;s<64;s++)i[s]=54^e[s],r[s]=92^e[s];var a=new Uint8Array(t.length+64);a.set(i,0),a.set(t,64);var o=new Uint8Array(96);return o.set(r,0),o.set(Ya(a),64),Ya(o)}(this.toBuffer(t),this.toBuffer(e));return this.toArrayBuffer(n)}},to=(e=>(e[e.REQ_SEND=0]="REQ_SEND",e[e.REQ_RECV=1]="REQ_RECV",e[e.REQ_RECV_POLL=2]="REQ_RECV_POLL",e[e.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",e))(to||{}),no=to;function io(){return new rr("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var ro=(Za=class{constructor(e){var t;this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1,this.client=null!=e?e:null;var n=(null==e?void 0:e.options.connectivityCheckUrl)||vs.connectivityCheckUrl,i=null!=(t=null==e?void 0:e.options.connectivityCheckParams)?t:null,r=!(null==e?void 0:e.options.connectivityCheckUrl),s=Gi(Gi({},ro.bundledRequestImplementations),null==e?void 0:e._additionalHTTPRequestImplementations),a=s.XHRRequest,o=s.FetchRequest,l=!(!a&&!o);if(!l)throw io();Qi.Config.xhrSupported&&a?(this.supportsAuthHeaders=!0,this.Request=function(){var t=c(function*(t,n,i,r,s){return new Promise(o=>{var l,c=a.createRequest(n,i,r,s,no.REQ_SEND,null!=(l=e&&e.options.timeouts)?l:null,this.logger,t);c.once("complete",(e,t,n,i,r)=>o({error:e,body:t,headers:n,unpacked:i,statusCode:r})),c.exec()})});return function(e,n,i,r,s){return t.apply(this,arguments)}}(),(null==e?void 0:e.options.disableConnectivityCheck)?this.checkConnectivity=c(function*(){return!0}):this.checkConnectivity=c(function*(){var e,t,s=yield this.doUri(_s.Get,n,null,null,i);return r?!s.error&&"yes"==(null==(e=s.body)?void 0:e.replace(/\n/,"")):!s.error&&((t=s.statusCode)>=200&&t<400)})):Qi.Config.fetchSupported&&o?(this.supportsAuthHeaders=!0,this.Request=function(){var t=c(function*(t,n,i,r,s){return o(t,null!=e?e:null,n,i,r,s)});return function(e,n,i,r,s){return t.apply(this,arguments)}}(),(null==e?void 0:e.options.disableConnectivityCheck)?this.checkConnectivity=c(function*(){return!0}):this.checkConnectivity=c(function*(){var e,t=yield this.doUri(_s.Get,n,null,null,null);return!t.error&&"yes"==(null==(e=t.body)?void 0:e.replace(/\n/,""))})):this.Request=c(function*(){return{error:l?new sr("no supported HTTP transports available",null,400):io()}})}get logger(){var e,t;return null!=(t=null==(e=this.client)?void 0:e.logger)?t:tr.defaultLogger}doUri(e,t,n,i,r){var s=this;return c(function*(){return s.Request?s.Request(e,t,n,r,i):{error:new sr("Request invoked before assigned to",null,500)}})()}shouldFallback(e){var t=e.statusCode;return 408===t&&!e.code||400===t&&!e.code||t>=500&&t<=504}},Za.methods=[_s.Get,_s.Delete,_s.Post,_s.Put,_s.Patch],Za.methodsWithoutBody=[_s.Get,_s.Delete],Za.methodsWithBody=[_s.Post,_s.Put,_s.Patch],Za),so=ro,ao="ablyjs-storage-test",oo="undefined"!=typeof global?global:"undefined"!=typeof window?window:self,lo=new class{constructor(){try{oo.sessionStorage.setItem(ao,ao),oo.sessionStorage.removeItem(ao),this.sessionSupported=!0}catch(e){this.sessionSupported=!1}try{oo.localStorage.setItem(ao,ao),oo.localStorage.removeItem(ao),this.localSupported=!0}catch(e){this.localSupported=!1}}get(e){return this._get(e,!1)}getSession(e){return this._get(e,!0)}remove(e){return this._remove(e,!1)}removeSession(e){return this._remove(e,!0)}set(e,t,n){return this._set(e,t,n,!1)}setSession(e,t,n){return this._set(e,t,n,!0)}_set(e,t,n,i){var r={value:t};return n&&(r.expires=Date.now()+n),this.storageInterface(i).setItem(e,JSON.stringify(r))}_get(e,t){if(t&&!this.sessionSupported)throw new Error("Session Storage not supported");if(!t&&!this.localSupported)throw new Error("Local Storage not supported");var n=this.storageInterface(t).getItem(e);if(!n)return null;var i=JSON.parse(n);return i.expires&&i.expires<Date.now()?(this.storageInterface(t).removeItem(e),null):i.value}_remove(e,t){return this.storageInterface(t).removeItem(e)}storageInterface(e){return e?oo.sessionStorage:oo.localStorage}},co=zr(),uo="string"==typeof EdgeRuntime;"undefined"!=typeof Window||"undefined"!=typeof WorkerGlobalScope||uo||console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var ho,po,vo={agent:"browser",logTimestamps:!0,userAgent:co.navigator&&co.navigator.userAgent.toString(),currentUrl:co.location&&co.location.href,binaryType:"arraybuffer",WebSocket:co.WebSocket,fetchSupported:!!co.fetch,xhrSupported:co.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:(po=co.location,!co.WebSocket||!po||!po.origin||po.origin.indexOf("http")>-1),useProtocolHeartbeats:!0,supportsBinary:!!co.TextDecoder,preferBinary:!1,ArrayBuffer:co.ArrayBuffer,atob:co.atob,nextTick:"function"==typeof co.queueMicrotask?e=>co.queueMicrotask(e):e=>Promise.resolve().then(e),addEventListener:co.addEventListener,inspect:JSON.stringify,stringByteSize:function(e){return co.TextDecoder&&(new co.TextEncoder).encode(e).length||e.length},TextEncoder:co.TextEncoder,TextDecoder:co.TextDecoder,getRandomArrayBuffer:(ho=c(function*(e){var t=new Uint8Array(e);return co.crypto.getRandomValues(t),t.buffer}),function(e){return ho.apply(this,arguments)}),isWebworker:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,push:{platform:"browser",formFactor:"desktop",storage:lo}},go=vo;ya.XhrPolling;var fo=ya.WebSocket;var _o=class extends ka{constructor(e,t,n){super(e,t,n),this.shortName=fo,n.heartbeats=Qi.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!Qi.Config.WebSocket}createWebSocket(e,t){return this.uri=e+Ir(t),new Qi.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){ka.prototype.connect.call(this);var e=this,t=this.params,n=t.options,i=(n.tls?"wss://":"ws://")+this.wsHost+":"+vs.getPort(n)+"/";Nr(this.auth.getAuthParams(),function(n,r){if(!e.isDisposed){for(var s in r)" "+s+": "+r[s]+";";if(n)e.disconnect(n);else{var a=t.getConnectParams(r);try{var o=e.wsConnection=e.createWebSocket(i,a);o.binaryType=Qi.Config.binaryType,o.onopen=function(){e.onWsOpen()},o.onclose=function(t){e.onWsClose(t)},o.onmessage=function(t){e.onWsData(t.data)},o.onerror=function(t){e.onWsError(t)},o.on&&o.on("ping",function(){e.onActivity()})}catch(t){tr.logAction(e.logger,tr.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(t.stack||t.message)),e.disconnect(t)}}}})}send(e){var t=this.wsConnection;if(t)try{t.send(la(e,this.connectionManager.realtime._MsgPack,this.params.format))}catch(e){var n="Exception from ws connection when trying to send: "+Mr(e);tr.logAction(this.logger,tr.LOG_ERROR,"WebSocketTransport.send()",n),this.finish("disconnected",new rr(n,5e4,500))}else tr.logAction(this.logger,tr.LOG_ERROR,"WebSocketTransport.send()","No socket connection")}onWsData(e){try{this.onProtocolMessage(da(e,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin,this.format))}catch(e){tr.logAction(this.logger,tr.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+e.stack)}}onWsOpen(){this.emit("preconnect")}onWsClose(e){var t,n;if("object"==typeof e?(n=e.code,t=e.wasClean||1e3===n):t=1e3==(n=e),delete this.wsConnection,t){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(e){Qi.Config.nextTick(()=>{this.disconnect(Error(e.message))})}dispose(){this.isDisposed=!0;var e=this.wsConnection;e&&(e.onmessage=function(){},delete this.wsConnection,Qi.Config.nextTick(()=>{if(!e)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");e.close()}))}},mo={order:["xhr_polling"],bundledImplementations:{}},yo={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[ya.XhrPolling,ya.WebSocket]};function bo(e,t,n,i,r,s){return wo.apply(this,arguments)}function wo(){return(wo=c(function*(e,t,n,i,r,s){var a,o=new Headers(i||{}),l=e?e.toUpperCase():ur(s)?"GET":"POST",d=new AbortController,u=new Promise(e=>{a=setTimeout(()=>{d.abort(),e({error:new sr("Request timed out",null,408)})},t?t.options.timeouts.httpRequestTimeout:vs.TIMEOUTS.httpRequestTimeout)}),h={method:l,headers:o,body:s,signal:d.signal};Qi.Config.isWebworker||(h.credentials=o.has("authorization")?"include":"same-origin");var p=c(function*(){try{var e=new URLSearchParams(r||{});e.set("rnd",Lr());var t=n+"?"+e,i=yield zr().fetch(t,h);if(clearTimeout(a),204==i.status)return{error:null,statusCode:i.status};var s,o=i.headers.get("Content-Type");s=o&&o.indexOf("application/x-msgpack")>-1?yield i.arrayBuffer():o&&o.indexOf("application/json")>-1?yield i.json():yield i.text();var l=!!o&&-1===o.indexOf("application/x-msgpack"),c=function(e){var t={};return e.forEach((e,n)=>{t[n]=e}),t}(i.headers);if(i.ok)return{error:null,body:s,headers:c,unpacked:l,statusCode:i.status};var d=function(e,t){if(function(e,t){return!!t.get("x-ably-errorcode")}(0,t))return e.error&&rr.fromValues(e.error)}(s,i.headers)||new sr("Error response received from server: "+i.status+" body was: "+Qi.Config.inspect(s),null,i.status);return{error:d,body:s,headers:c,unpacked:l,statusCode:i.status}}catch(d){return clearTimeout(a),{error:d}}})();return Promise.race([u,p])})).apply(this,arguments)}var Co;function So(e,t){var n,i,r=null!==(n=e.metadata)&&void 0!==n?n:{},s=null!==(i=t.metadata)&&void 0!==i?i:{};return!s.widgets&&r._widgets?d({},t,{metadata:d({},s,{_widgets:r._widgets})}):t}function ko(e,t,n,i){var r,s,a,o=(s=e.messages.value,a=t.id,s.some(e=>e.id===a));if(e.setMessages(function(e,t){var n=e.findIndex(e=>e.id===t.id);if(-1!==n){var i=e[n],r=So(i,t);if(function(e,t){return e.id===t.id&&e.channel_id===t.channel_id&&e.sender_type===t.sender_type&&e.sender_id===t.sender_id&&e.sender_name===t.sender_name&&e.sender_avatar_url===t.sender_avatar_url&&e.content===t.content&&e.content_type===t.content_type&&e.created_at===t.created_at&&e.metadata===t.metadata}(i,r))return e;var s=[...e];return s[n]=r,s}if("ai"===t.sender_type){var a=e.findIndex(e=>e.id.startsWith("temp-ai-"));if(-1!==a){var o=So(e[a],t),l=[...e];return l[a]=o,l}}return hi(e,t)}(e.messages.value,t)),"user"!==t.sender_type||t.sender_id!==n){if(!o){if("ai"===t.sender_type||"agent"===t.sender_type){var l=e.isOpen.value,c=(null===(r=e.channel.value)||void 0===r?void 0:r.id)===t.channel_id;if(l&&c)i.onAgentMessageWhileOpen();else{var u=e.channels.value.findIndex(e=>e.id===t.channel_id);if(-1!==u){var h=[...e.channels.value];h[u]=d({},h[u],{unread_count:(h[u].unread_count||0)+1}),e.channels.value=h}}i.onTrack(t)}e.isTyping.value=!1,e.typingSender.value=null,e.typingSenderType.value=null,i.onMessageDispatched(t)}}else i.onMessageDispatched(t)}Qi.BufferUtils=eo,Qi.Http=so,Qi.Config=go,Qi.Transports=mo,Qi.WebStorage=lo,so.bundledRequestImplementations={},tr.initLogHandlers(),Qi.Defaults=(Co=yo,Object.assign(ns,Co)),Qi.Config.agent&&(Qi.Defaults.agent+=" "+Qi.Config.agent);var xo="chat.ably";function To(e,t,n){return Io.apply(this,arguments)}function Io(){return(Io=c(function*(e,t,n){return ne(e,te,{method:"POST",body:JSON.stringify(d({distinct_id:t},n&&{channel_id:n}))})})).apply(this,arguments)}function Eo(){return(Eo=c(function*(e,t){var n=yield To(e,t);return(null==n?void 0:n.tokenRequest)?n.clientId&&null!=n.project_id?{tokenRequest:n.tokenRequest,clientId:n.clientId,projectId:n.project_id}:(I().warn(xo,"token:request:incomplete — missing clientId or project_id"),null):(I().warn(xo,"token:request:failed (initial)"),null)})).apply(this,arguments)}var Ao="chat.ably";function Oo(e,t){var n=(()=>{if(!t||"object"!=typeof t)return String(t);var e=t,n="string"==typeof e.message?e.message:String(t),i="number"==typeof e.code?e.code:null,r="number"==typeof e.statusCode?e.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")?e+" — "+n+" (browser cannot reach Ably hosts (*.ably.io / *.ably-realtime.com) — check ad-blocker, firewall, VPN, or offline state)":e+" — "+n}var Mo=e=>new Na(e);class Ro{constructor(e,t,n,i){void 0===i&&(i=Mo),this.instance=e,this.store=t,this.hooks=n,this._client=null,this._notificationsChannel=null,this._conversationChannel=null,this._typingChannel=null,this._teardownInFlight=null,this._factory=i}get clientId(){var e,t;return null!==(t=null===(e=this._client)||void 0===e?void 0:e.auth.clientId)&&void 0!==t?t:null}get isLive(){return null!=this._client}get currentChannelId(){return this.store.realtimeChannelId.value}ensureConnected(){var e=this;return c(function*(){if(!e._client){e.store.connectionState.value="connecting",I().debug(Ao,"connect:start");var t=e.hooks.getDistinctId(),n=yield function(e,t){return Eo.apply(this,arguments)}(e.instance,t);if(n){e.store.ablyProjectId.value=n.projectId;var i,r=n.clientId,s=e._factory({plugins:{WebSocketTransport:_o,FetchRequest:bo},authCallback:(i={instance:e.instance,getDistinctId:()=>e.hooks.getDistinctId(),getChannelScope:()=>{var t,n,i,r;return null!==(r=null!==(n=null!==(t=e.store.pendingRealtimeChannelId.value)&&void 0!==t?t:e.store.realtimeChannelId.value)&&void 0!==n?n:null===(i=e.store.channel.value)||void 0===i?void 0:i.id)&&void 0!==r?r:null},getLiveClientId:()=>{var t,n;return null!==(n=null===(t=e._client)||void 0===t?void 0:t.auth.clientId)&&void 0!==n?n:null},onIdentityChange:()=>e.hooks.onIdentityChange()},function(){var e=c(function*(e,t){try{var n=i.getChannelScope(),r=yield To(i.instance,i.getDistinctId(),null!=n?n:void 0);if(!(null==r?void 0:r.tokenRequest))return void t("Failed to refresh token",null);var s=r.tokenRequest.clientId,a=i.getLiveClientId();if(a&&s&&s!==a)return I().warn(xo,"token:request:clientid-mismatch — recreating connection"),t("clientId changed; recreating connection",null),void i.onIdentityChange();t(null,r.tokenRequest)}catch(e){t(String(e),null)}});return function(t,n){return e.apply(this,arguments)}}()),authMethod:"POST"});e._client=s,s.connection.on("connected",()=>{e.store.connectionState.value="connected",e._checkClientIdDrift(),I().debug(Ao,"connect:connected")}),s.connection.on("disconnected",()=>{e.store.connectionState.value="disconnected",I().debug(Ao,"connect:disconnected")}),s.connection.on("suspended",()=>{e.store.connectionState.value="suspended",I().debug(Ao,"connect:suspended")}),s.connection.on("failed",()=>{e.store.connectionState.value="failed",I().debug(Ao,"connect:failed")});try{yield s.auth.authorize(n.tokenRequest)}catch(t){return I().error(Ao,Oo("connect:authorize-failed",t)),void(e.store.connectionState.value="failed")}var a=s.connection.state;"connected"===a?(e.store.connectionState.value="connected",e._checkClientIdDrift(),I().debug(Ao,"connect:connected (sync)")):"disconnected"!==a&&"suspended"!==a&&"failed"!==a||(e.store.connectionState.value=a,I().debug(Ao,"connect:"+a+" (sync)"));var o="chat:"+n.projectId+":notifications";e._notificationsChannel=s.channels.get(o),e._notificationsChannel.subscribe("notification",t=>{!function(e,t,n){var i,r,s,{type:a,channel_id:o,data:l}=t;if("new_channel"!==a)if("channel_updated"===a&&l){var c=e.channels.value.findIndex(e=>e.id===o);if(-1!==c){var u={};void 0!==l.last_message_at&&(u.last_message_at=l.last_message_at),void 0!==l.last_message_preview&&(u.last_message_preview=l.last_message_preview),void 0!==l.last_message_sender&&(u.last_message_sender=l.last_message_sender),void 0!==l.user_unread_count&&(e.isOpen.value&&(null===(i=e.channel.value)||void 0===i?void 0:i.id)===o||(u.unread_count=l.user_unread_count)),void 0!==l.status&&(u.status=l.status),void 0!==l.ai_mode&&(u.ai_mode=l.ai_mode),e.patchChannelSummary(o,u)}(null===(r=e.channel.value)||void 0===r?void 0:r.id)===o&&"closed"===l.status&&(e.channel.value=d({},e.channel.value,{status:"closed"}))}else"channel_closed"===a&&(e.patchChannelSummary(o,{status:"closed"}),(null===(s=e.channel.value)||void 0===s?void 0:s.id)===o&&(e.channel.value=d({},e.channel.value,{status:"closed"})));else n.onNewChannel()}(e.store,t.data,{onNewChannel:e.hooks.onNewChannelNotification})}),e.store.lastConnectedDistinctId.value=r.split(":").slice(1).join(":")||t}else e.store.connectionState.value="failed"}})()}refreshToken(e){var t=this;return c(function*(){var n=t._client;if(!n)return!1;if("failed"===n.connection.state)return I().warn(Ao,"token:skip — connection failed"),t.hooks.onIdentityChange(),!1;var i=yield To(t.instance,t.hooks.getDistinctId(),e);if(!(null==i?void 0:i.tokenRequest))return I().warn(Ao,"token:request:failed",null!=e?e:"(list)"),!1;var r=i.tokenRequest.clientId,s=n.auth.clientId;if(s&&r&&r!==s)return I().warn(Ao,"token:request:clientid-mismatch — recreating connection"),t.hooks.onIdentityChange(),!1;try{return yield n.auth.authorize(i.tokenRequest),!0}catch(e){return I().warn(Ao,Oo("token:authorize-failed",e)),!1}})()}attachConversation(e){var t=this;return c(function*(){var n;if(yield t.ensureConnected(),t._client&&null!=t.store.ablyProjectId.value){if(t._conversationChannel||t._typingChannel||t._teardownInFlight){var i=null!==(n=t._teardownInFlight)&&void 0!==n?n:t._teardownActive();try{yield i}catch(e){}}if(t.store.pendingRealtimeChannelId.value=e,!(yield t.refreshToken(e)))return I().warn(Ao,"channel:attach:no-capability for",e),void(t.store.pendingRealtimeChannelId.value===e&&(t.store.pendingRealtimeChannelId.value=null));var r="chat:"+t.store.ablyProjectId.value+":"+e,s=r+":typing",a=t._client.channels.get(r),o=t._client.channels.get(s);t._conversationChannel=a,t._typingChannel=o;var l=()=>t._conversationChannel!==a||t._typingChannel!==o;I().debug(Ao,"channel:attach:start",e);try{if(yield a.attach(),l())return void I().debug(Ao,"channel:attach:superseded",e);if(a.subscribe("message",e=>{t._conversationChannel===a&&ko(t.store,e.data,t.hooks.getDistinctId()||null,{onAgentMessageWhileOpen:t.hooks.onAgentMessageWhileOpen,onTrack:t.hooks.onMessageTrack,onMessageDispatched:t.hooks.onMessageDispatched})}),a.subscribe("read",e=>{var n,i;t._conversationChannel===a&&(n=t.store,"agent"===(i=e.data).reader_type&&(n.agentLastReadAt.value=i.read_at))}),yield o.attach(),l())return void I().debug(Ao,"channel:attach:superseded",e);if(o.subscribe("typing",e=>{t._typingChannel===o&&function(e,t,n){if("user"!==t.sender_type){e.isTyping.value=t.is_typing,e.typingSenderType.value=t.is_typing?t.sender_type:null;var i="ai"===t.sender_type?null:t.sender_name||("agent"===t.sender_type?"Agent":null);e.typingSender.value=t.is_typing?i:null,n.onTyping(t.is_typing,i||"")}}(t.store,e.data,{onTyping:t.hooks.onTypingDispatched})}),t.store.pendingRealtimeChannelId.value!==e)return void I().debug(Ao,"channel:attach:abandoned (pending cleared)",e);t.store.realtimeChannelId.value=e,t.store.realtimeAttached.value=!0,t.store.pendingRealtimeChannelId.value===e&&(t.store.pendingRealtimeChannelId.value=null),I().debug(Ao,"channel:realtime.attached",{channelId:e})}catch(n){if(l())return void I().debug(Ao,"channel:attach:superseded (after error)",e);I().error(Ao,"channel:attach:failed",n),t.store.realtimeAttached.value=!1,t.store.pendingRealtimeChannelId.value===e&&(t.store.pendingRealtimeChannelId.value=null),yield t._teardownActive()}}})()}detachConversation(){var e=this._teardownActive().finally(()=>{this._teardownInFlight===e&&(this._teardownInFlight=null)});return this._teardownInFlight=e,e}_teardownActive(){var e=this._client,t=this._conversationChannel,n=this._typingChannel;return this._conversationChannel=null,this._typingChannel=null,Promise.all([this._teardownChannel(e,t),this._teardownChannel(e,n)]).then(()=>{})}publishTyping(e){var t=this._typingChannel;t&&t.publish("typing",e).catch(e=>{I().warn(Ao,"failed to publish typing indicator:",e)})}disconnectAll(){var e=this;return c(function*(){if(e._teardownInFlight)try{yield e._teardownInFlight}catch(e){}var t=e._client,n=e._conversationChannel,i=e._typingChannel,r=e._notificationsChannel;if(e._conversationChannel=null,e._typingChannel=null,e._notificationsChannel=null,e.store.realtimeChannelId.value=null,e.store.realtimeAttached.value=!1,null==n||n.unsubscribe(),null==i||i.unsubscribe(),null==r||r.unsubscribe(),t){try{t.close()}catch(e){I().debug(Ao,"disconnect:close:error",e)}e._client=null}e.store.ablyProjectId.value=null,e.store.connectionState.value="disconnected",e.store.lastConnectedDistinctId.value=null})()}_checkClientIdDrift(){var e,t=null===(e=this._client)||void 0===e?void 0:e.auth.clientId,n=this.store.lastConnectedDistinctId.value;if(t&&n){var i=t.split(":").slice(1).join(":")||t;i&&i!==n&&(I().warn(Ao,"identity:drift detected on connected — recreating"),this.hooks.onIdentityChange())}}_teardownChannel(e,t){return c(function*(){if(t&&e){t.unsubscribe();try{yield t.detach()}catch(e){}}})()}}var Po=["delivery_status"];function Lo(e,t,n){var i=e.messages.value,r=i.findIndex(e=>e.id===t);if(-1!==r){var s=i[r];if(s.delivery_status!==n){var a=[...i];if(void 0===n){var o=function(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;n[i]=e[i]}return n}(s,Po);a[r]=o}else a[r]=d({},s,{delivery_status:n});e.setMessages(a)}}}function Uo(e,t){return Do.apply(this,arguments)}function Do(){return Do=c(function*(e,t){var n;if(!e.ok)return!1;if(e.headers.get("X-Vtilt-User-Message-Id")===t)return!0;var i=e.headers.get("content-type")||"";if(i.includes("text/plain"))return e.ok;if(i.includes("application/json"))try{var r=yield e.clone().json();return(null===(n=null==r?void 0:r.message)||void 0===n?void 0:n.id)===t}catch(e){return!1}return e.ok}),Do.apply(this,arguments)}function No(e,t){return"vtilt-chat-outbox:"+e+":"+t}function Bo(e){return e+":last-channel"}class Ho{constructor(e){this._storageKey=e,this._memory=[]}list(){var e=this._readStorage();return e.length>0?(this._memory=e,e):this._memory}get(e){return this.list().find(t=>t.messageId===e)}upsert(e){var t=this.list().filter(t=>t.messageId!==e.messageId);t.push(e),this._write(t)}patch(e,t){var n=this.list(),i=n.findIndex(t=>t.messageId===e);-1!==i&&(n[i]=d({},n[i],t),this._write(n))}remove(e){this._write(this.list().filter(t=>t.messageId!==e))}dueEntries(e){return void 0===e&&(e=Date.now()),this.list().filter(t=>"sending"!==t.state&&t.nextRetryAt<=e&&!(t.newChannel&&!t.channelId))}requeueStaleSending(e,t){var n;void 0===e&&(e=3e4),void 0===t&&(t=Date.now());for(var i=this.list(),r=!1,s=0;s<i.length;s++){var a=i[s];if("sending"===a.state){var o=null!==(n=a.sendingSince)&&void 0!==n?n:0;(!o||t-o>=e)&&(i[s]=d({},a,{state:"pending",sendingSince:void 0}),r=!0)}}r&&this._write(i)}_readStorage(){if("undefined"==typeof sessionStorage)return[];try{var e=sessionStorage.getItem(this._storageKey);if(!e)return[];var t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return[]}}_write(e){if(this._memory=e,"undefined"!=typeof sessionStorage)try{0===e.length?sessionStorage.removeItem(this._storageKey):sessionStorage.setItem(this._storageKey,JSON.stringify(e))}catch(e){}}}function qo(e,t){return void 0===t&&(t=Date.now()),t+Math.min(6e4,1e3*Math.pow(2,Math.max(0,e-1)))}var Fo="chat";class jo{constructor(e,t){var n,i,r,s,a,o,l,c,u;void 0===t&&(t={}),this._ui=null,this._registry=new de,this._messageCallbacks=[],this._typingCallbacks=[],this._connectionCallbacks=[],this._lastConnectedNotified=null,this._unsubscribeIdentity=null,this._unsubscribeReset=null,this._identityChangeInFlight=!1,this._typingIdleTimer=null,this._isUserTyping=!1,this._lastTypingPublishAt=0,this._lastTypingActivityAt=0,this._pendingTypingIntent=!1,this._disposeRealtimeReadyWatcher=null,this._isMarkingRead=!1,this._streamAbort=null,this._streamingMessageId=null,this._optimisticAiTyping=!1,this._openedAt=null,this._disposeConnectionWatcher=null,this._drainInFlight=!1,this._drainTimer=null,this._onOutboxOnline=()=>{this._scheduleDrainOutbox()},this._onOutboxVisible=()=>{"undefined"!=typeof document&&"visible"===document.visibilityState&&this._scheduleDrainOutbox()},this._bubbleExplicitShow=!1,this._instance=e,this._config=d({enabled:!0,position:"bottom-right",aiMode:!0,preload:!1},t,{theme:d({},yn,t.theme)}),this._store=new bn,this._store.isVisible.value=!1!==(null===(n=this._config.bubble)||void 0===n?void 0:n.visible),this._store.theme.value={primaryColor:null!==(r=null===(i=this._config.theme)||void 0===i?void 0:i.primaryColor)&&void 0!==r?r:yn.primaryColor,fontFamily:null!==(a=null===(s=this._config.theme)||void 0===s?void 0:s.fontFamily)&&void 0!==a?a:yn.fontFamily,borderRadius:null!==(l=null===(o=this._config.theme)||void 0===o?void 0:o.borderRadius)&&void 0!==l?l:yn.borderRadius},this._registry.register(Pt),this._registry.register($t),this._ably=new Ro(e,this._store,{getDistinctId:()=>this._distinctId,onIdentityChange:()=>{this._handleIdentityChange()},onNewChannelNotification:()=>{this.getChannels()},onAgentMessageWhileOpen:()=>{setTimeout(()=>this._autoMarkAsRead(),100)},onMessageTrack:e=>{var t,n,i,r;this._trackChatMessage(e,e.channel_id,null!==(n=null===(t=this._store.channel.value)||void 0===t?void 0:t.ai_mode)&&void 0!==n&&n),"ai"!==e.sender_type&&"agent"!==e.sender_type||null===(r=(i=this._config).onMessageReceived)||void 0===r||r.call(i,{channelId:e.channel_id,messageId:e.id,senderType:e.sender_type})},onMessageDispatched:e=>{this._messageCallbacks.forEach(t=>t(e))},onTypingDispatched:(e,t)=>{this._typingCallbacks.forEach(n=>n(e,t))}}),this._disposeConnectionWatcher=this._watchConnectionState(),this._disposeRealtimeReadyWatcher=this._store.realtimeReady.subscribe(e=>{if(e&&this._pendingTypingIntent){var t=Date.now()-this._lastTypingActivityAt;this._pendingTypingIntent=!1,t<3e3&&(this._isUserTyping=!0,this._publishTyping(!0),this._lastTypingPublishAt=Date.now(),this._scheduleTypingIdle())}}),this._ui=Bi({store:this._store,controller:this,position:null!==(c=this._config.position)&&void 0!==c?c:"bottom-right",bubbleDraggable:!!(null===(u=this._config.bubble)||void 0===u?void 0:u.draggable)}),this._applyBubbleLayout(),this._unsubscribeIdentity=this._instance._emitter.on("user:identified",()=>{this._handleIdentityChange()}),this._unsubscribeReset=this._instance._emitter.on("user:reset",()=>{this._handleIdentityChange()}),this._outboxDistinctId=this._distinctId,this._outbox=new Ho(this._outboxStorageKey()),this._outbox.requeueStaleSending(),this._bindOutboxLifecycle(),this._scheduleDrainOutbox()}get isOpen(){return this._store.isOpen.value}get isConnected(){return this._store.isConnected.value}get isLoading(){return this._store.isLoading.value}get unreadCount(){return this._store.unreadCount.value}get channel(){return this._store.channel.value}get channels(){return this._store.channels.value}get currentView(){return this._store.currentView.value}get store(){return this._store}get widgets(){return this._registry}get theme(){return this._store.theme.value}get config(){return this._config}open(){var e,t;this._store.isOpen.value||(this._store.isVisible.value=!0,this._store.isOpen.value=!0,this._store.polledUnreadTotal.value=null,this._openedAt=Date.now(),null===(t=(e=this._config).onWidgetOpen)||void 0===t||t.call(e),this._ably.ensureConnected(),0===this._store.channels.value.length&&this.getChannels())}close(){var e,t,n;if(this._store.isOpen.value){var i=this._openedAt?Math.round((Date.now()-this._openedAt)/1e3):0;this._openedAt=null,this._store.isOpen.value=!1,this.stopUserTyping(),this._bubbleExplicitShow||!1!==(null===(e=this._config.bubble)||void 0===e?void 0:e.visible)||(this._store.isVisible.value=!1);var r=this._store.messages.value.filter(e=>"user"===e.sender_type).length;null===(n=(t=this._config).onWidgetClose)||void 0===n||n.call(t,{timeOpenSeconds:i,messagesSent:r}),this._teardownRealtimeOnClose()}}_teardownRealtimeOnClose(){var e=this;return c(function*(){yield e._ably.detachConversation(),yield e._ably.disconnectAll()})()}applyPolledUnreadCount(e){this._store.isOpen.value||(this._store.polledUnreadTotal.value=e)}toggle(){this._store.isOpen.value?this.close():this.open()}show(){this._bubbleExplicitShow=!0,this._store.isVisible.value=!0}hide(){this._bubbleExplicitShow=!1,this._store.isVisible.value=!1}getChannels(){var e=this;return c(function*(){e._store.isLoading.value=!0;try{var t=yield ne(e._instance,Y+"?distinct_id="+encodeURIComponent(e._distinctId),{method:"GET"});t&&(e._store.channels.value=t.channels||[])}catch(e){I().error(Fo,"failed to fetch channels:",e)}finally{e._store.isLoading.value=!1}})()}selectChannel(e){var t=this;return c(function*(){var n=t._store.channels.value.find(t=>t.id===e);t._store.channel.value=n?t._stubChannelFromSummary(n):null,t._store.prepareChannelSwitch();var i=t._store.getCachedMessages(e);i&&(t._store.messages.value=i),t._store.currentView.value="conversation",t._store.isLoading.value=!0,t._store.pendingRealtimeChannelId.value=e,t._ably.detachConversation();var r=!1,s=!1;try{var a=yield ne(t._instance,Y+"/"+e+"?distinct_id="+encodeURIComponent(t._distinctId),{method:"GET"});if(t._store.pendingRealtimeChannelId.value!==e)return void(s=!0);if(!a)return void I().error(Fo,"selectChannel: server returned no data for channel",e);t._store.channel.value=a.channel;var o=a.messages||[];t._store.messages.value=o,t._store.cacheMessages(a.channel.id,o),t._store.agentLastReadAt.value=a.channel.agent_last_read_at||null,t._store.initialUserReadAt.value=a.channel.user_last_read_at||null,t._ably.attachConversation(a.channel.id),t._store.isOpen.value&&t._autoMarkAsRead(),r=!0}catch(e){I().error(Fo,"failed to select channel:",e)}finally{t._store.pendingRealtimeChannelId.value===e&&(t._store.pendingRealtimeChannelId.value=null),t._store.isLoading.value=!1,s||r||null!==t._store.channel.value||"conversation"!==t._store.currentView.value||(t._store.currentView.value="list")}})()}createChannel(t){var n=this;return c(function*(){var i,r,s,a=!0===(null==t?void 0:t.skipGreeting),o=!0===(null==t?void 0:t.preserveMessages),l=o?n._store.messages.value.slice():[];n._store.channel.value=null,o||n._store.prepareChannelSwitch(),n._store.currentView.value="conversation",n._store.isLoading.value=!0,n._ably.detachConversation();var c=!1;try{var u=yield ne(n._instance,Y,{method:"POST",body:JSON.stringify(d({distinct_id:n._distinctId,page_url:null===(i=null==e?void 0:e.location)||void 0===i?void 0:i.href,page_title:"undefined"!=typeof document?document.title:""},a&&{skip_greeting:!0}))});if(!u)return void I().error(Fo,"createChannel: server returned no data, channel was not created");n._store.channel.value=u.channel;var h=u.messages||[];if(l.length>0){var p=new Set(h.map(e=>e.id)),v=l.filter(e=>!p.has(e.id)).map(e=>e.channel_id?e:d({},e,{channel_id:u.channel.id}));n._store.messages.value=[...h,...v]}else n._store.messages.value=h;n._store.agentLastReadAt.value=u.channel.agent_last_read_at||null,n._store.initialUserReadAt.value=u.channel.user_last_read_at||null;var g={id:u.channel.id,status:u.channel.status,ai_mode:u.channel.ai_mode,last_message_at:u.channel.last_message_at,last_message_preview:u.channel.last_message_preview,last_message_sender:u.channel.last_message_sender,unread_count:0,user_last_read_at:u.channel.user_last_read_at,created_at:u.channel.created_at};n._store.prependChannelSummary(g),null===(s=(r=n._config).onConversationStart)||void 0===s||s.call(r,{channelId:u.channel.id,aiMode:u.channel.ai_mode}),n._ably.attachConversation(u.channel.id),n._bindOutboxToChannel(u.channel.id),n._rememberLastCreatedChannel(u.channel.id),c=!0}catch(e){I().error(Fo,"failed to create channel:",e)}finally{if(n._store.pendingRealtimeChannelId.value=null,n._store.isLoading.value=!1,!c&&null===n._store.channel.value)if(l.length>0){var f=new Set(n._outbox.list().map(e=>e.messageId)),_=l.filter(e=>f.has(e.id));_.length>0?(n._store.messages.value=_.map(e=>e.delivery_status?e:d({},e,{delivery_status:"failed"})),n._store.currentView.value="conversation"):(n._store.messages.value=[],n._store.currentView.value="list")}else n._store.currentView.value="list"}})()}goToChannelList(){var e,t,n,i=this._store.channel.value;if(i){var r=this._store.messages.value[this._store.messages.value.length-1];this._store.patchChannelSummary(i.id,{last_message_at:null!==(e=null==r?void 0:r.created_at)&&void 0!==e?e: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!==(t=null==r?void 0:r.sender_type)&&void 0!==t?t:void 0,unread_count:0}),this._store.cacheMessages(i.id,this._store.messages.value)}this._store.clearActiveChannel(),this._store.currentView.value="list",this._ably.detachConversation().then(()=>{this._ably.isLive&&!this._store.pendingRealtimeChannelId.value&&this._ably.refreshToken()})}_cancelActiveStream(){this._streamAbort&&(this._streamAbort.abort(),this._streamAbort=null),this._streamingMessageId&&(mi(this._store,this._streamingMessageId),this._streamingMessageId=null),this._stripTrailingAiAfterLastUser(),this._clearOptimisticAiTyping()}_stripTrailingAiAfterLastUser(){for(var e=this._store.messages.value,t=-1,n=e.length-1;n>=0;n--)if("user"===e[n].sender_type){t=n;break}if(-1!==t){var i=e.filter((e,n)=>n<=t||"ai"!==e.sender_type);i.length!==e.length&&this._store.setMessages(i)}}_showOptimisticAiTyping(){this._optimisticAiTyping=!0,this._store.isTyping.value=!0,this._store.typingSenderType.value="ai",this._store.typingSender.value="AI Assistant"}_clearOptimisticAiTyping(){this._optimisticAiTyping&&(this._optimisticAiTyping=!1,this._store.isTyping.value=!1,this._store.typingSender.value=null,this._store.typingSenderType.value=null)}sendMessage(e,t){var n=this;return c(function*(){var i,r=le(e,t);if(r){n._store.identityChangeInFlight.value&&(yield n._waitForIdentityChange());var{content:s,content_type:a,metadata:o}=r,l=!1!==(null==t?void 0:t.open),c="conversation"===n._store.currentView.value&&null!==n._store.channel.value,u=null!==(i=null==t?void 0:t.channel)&&void 0!==i?i:c?void 0:"new",h=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();var e=crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;var t=e=>e.toString(16).padStart(2,"0");return t(e[0])+t(e[1])+t(e[2])+t(e[3])+"-"+t(e[4])+t(e[5])+"-"+t(e[6])+t(e[7])+"-"+t(e[8])+t(e[9])+"-"+t(e[10])+t(e[11])+t(e[12])+t(e[13])+t(e[14])+t(e[15])}(),p=(new Date).toISOString(),v="new"===u;if(n._enqueueOutbox(d({messageId:h,channelId:"",distinctId:n._distinctId,body:s,content_type:a,metadata:o,created_at:p,state:"pending",attempts:0,nextRetryAt:0},v?{newChannel:{skipGreeting:!0}}:{})),n._markOutboxSending(h),v){n._store.currentView.value="conversation",n._store.channel.value=null;var g={id:h,channel_id:"",sender_type:"user",sender_id:n._distinctId||null,sender_name:null,sender_avatar_url:null,content:s,content_type:a,metadata:o,created_at:p,delivery_status:"pending"};n._store.setMessages([g]),n._store.isLoading.value=!0,l&&n.open(),yield n.createChannel({skipGreeting:!0,preserveMessages:!0})}else l&&n.open(),u&&(yield n.selectChannel(u));if(!n._store.channel.value)throw I().error(Fo,"cannot send message: no active channel (channel creation or selection failed)"),n._outbox.patch(h,{state:"failed"}),Lo(n._store,h,"failed"),new Error("No active channel");if("conversation"!==n._store.currentView.value)throw I().error(Fo,"cannot send message: not in conversation view"),n._outbox.patch(h,{state:"failed"}),Lo(n._store,h,"failed"),new Error("Not in conversation view");var f,_=n._store.channel.value.id;if(n._outbox.patch(h,{channelId:_,newChannel:void 0}),v){var m=n._store.messages.value.find(e=>e.id===h);if(!m)throw I().error(Fo,"sendMessage: optimistic temp message was lost during createChannel"),n._outbox.patch(h,{state:"failed"}),new Error("Optimistic message lost");f=m}else f={id:h,channel_id:_,sender_type:"user",sender_id:n._distinctId||null,sender_name:null,sender_avatar_url:null,content:s,content_type:a,metadata:o,created_at:p,delivery_status:"pending"},n._store.setMessages([...n._store.messages.value,f]);try{yield n._postUserMessage({messageId:h,channelId:_,body:s,content_type:a,metadata:o,tempMessage:f})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw n._failOutboxMessage(h),e;throw n._clearOptimisticAiTyping(),I().error(Fo,"failed to send message:",e),n._failOutboxMessage(h),n._scheduleDrainOutbox(),e}}else I().warn(Fo,"sendMessage: message is empty")})()}retryFailedMessage(e){var t,n=this._outbox.get(e);if(n&&"failed"===n.state){this._outbox.patch(e,{state:"pending",nextRetryAt:0,sendingSince:void 0}),Lo(this._store,e,"pending");var i=n.channelId||(null===(t=this._store.channel.value)||void 0===t?void 0:t.id)||"";if(i){var r=this._store.messages.value.find(t=>t.id===e);r?(this._markOutboxSending(e),this._postUserMessage({messageId:e,channelId:i,body:n.body,content_type:n.content_type,metadata:n.metadata,tempMessage:r}).catch(t=>{t instanceof DOMException&&"AbortError"===t.name?this._failOutboxMessage(e):(I().error(Fo,"retry send failed:",t),this._failOutboxMessage(e),this._scheduleDrainOutbox())})):this._scheduleDrainOutbox()}}}markAsRead(){this._autoMarkAsRead()}triggerAIAfterWidgetAction(e){var t=this;return c(function*(){try{t._cancelActiveStream();var n=new AbortController;t._streamAbort=n,t._showOptimisticAiTyping();var i=t._instance.getConfig(),r=h(i,Z(e)),s=yield fetch(r,{method:"POST",signal:n.signal,headers:d({"Content-Type":"application/json"},p(i)),body:JSON.stringify({channel_id:e,distinct_id:t._distinctId,widget_action_trigger:!0})});if(!s.ok)return void t._clearOptimisticAiTyping();(s.headers.get("content-type")||"").includes("text/plain")&&(yield fi({store:t._store,response:s,channelId:e,signal:n.signal,isActive:()=>t._streamAbort===n,onStreamStart:e=>{t._clearOptimisticAiTyping(),t._streamAbort===n&&(t._streamingMessageId=e)},onComplete:()=>{t._streamAbort===n&&(t._streamAbort=null,t._streamingMessageId=null)}}))}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return}})()}onMessage(e){return this._messageCallbacks.push(e),()=>{var t=this._messageCallbacks.indexOf(e);t>-1&&this._messageCallbacks.splice(t,1)}}onTyping(e){return this._typingCallbacks.push(e),()=>{var t=this._typingCallbacks.indexOf(e);t>-1&&this._typingCallbacks.splice(t,1)}}onConnectionChange(e){return this._connectionCallbacks.push(e),()=>{var t=this._connectionCallbacks.indexOf(e);t>-1&&this._connectionCallbacks.splice(t,1)}}updateConfig(e){var t,n,i,r,s,a,o;this._config=function(e,t){var n,i,r=t.bubble,s=e.bubble;if(r){var a=null===r.offset?void 0:void 0!==r.offset?d({},null===(n=e.bubble)||void 0===n?void 0:n.offset,r.offset):null===(i=e.bubble)||void 0===i?void 0:i.offset;s=d({},e.bubble,r,{offset:a})}return d({},e,t,{theme:t.theme?d({},e.theme,t.theme):e.theme,bubble:s})}(this._config,e),this._store.theme.value={primaryColor:null!==(n=null===(t=this._config.theme)||void 0===t?void 0:t.primaryColor)&&void 0!==n?n:yn.primaryColor,fontFamily:null!==(r=null===(i=this._config.theme)||void 0===i?void 0:i.fontFamily)&&void 0!==r?r:yn.fontFamily,borderRadius:null!==(a=null===(s=this._config.theme)||void 0===s?void 0:s.borderRadius)&&void 0!==a?a:yn.borderRadius},(null===(o=this._config.bubble)||void 0===o?void 0:o.draggable)||this._applyBubbleLayout()}_applyBubbleLayout(){var e,t,n,i,r=null===(e=this._ui)||void 0===e?void 0:e.host;if(r){var s=null!==(t=this._config.position)&&void 0!==t?t:"bottom-right";!function(e,t){e.style.setProperty("--vt-bubble-offset-bottom",t.bottom+"px"),e.style.setProperty("--vt-bubble-offset-right",t.right+"px"),e.style.setProperty("--vt-bubble-offset-left",t.left+"px")}(r,Sn(null===(n=this._config.bubble)||void 0===n?void 0:n.offset));var a=null===(i=r.shadowRoot)||void 0===i?void 0:i.querySelector(".vt-container");a instanceof HTMLElement&&a.setAttribute("data-position",s)}}registerWidget(e){this._registry.register(e)}notifyUserTyping(){this._lastTypingActivityAt=Date.now(),this._store.realtimeReady.value?(this._isUserTyping?Date.now()-this._lastTypingPublishAt>4e3&&(this._publishTyping(!0),this._lastTypingPublishAt=Date.now()):(this._isUserTyping=!0,this._publishTyping(!0),this._lastTypingPublishAt=Date.now()),this._scheduleTypingIdle()):this._pendingTypingIntent=!0}stopUserTyping(){this._pendingTypingIntent=!1,this._typingIdleTimer&&(clearTimeout(this._typingIdleTimer),this._typingIdleTimer=null),this._isUserTyping&&this._store.realtimeReady.value&&this._publishTyping(!1),this._isUserTyping=!1}_scheduleTypingIdle(){this._typingIdleTimer&&clearTimeout(this._typingIdleTimer),this._typingIdleTimer=setTimeout(()=>{this._typingIdleTimer=null,this._isUserTyping&&this._store.realtimeReady.value&&this._publishTyping(!1),this._isUserTyping=!1},5e3)}destroy(){var e,t,n,i,r;this._unbindOutboxLifecycle(),this._drainTimer&&(clearTimeout(this._drainTimer),this._drainTimer=null),this._ably.disconnectAll(),this._typingIdleTimer&&(clearTimeout(this._typingIdleTimer),this._typingIdleTimer=null),null===(e=this._unsubscribeIdentity)||void 0===e||e.call(this),this._unsubscribeIdentity=null,null===(t=this._unsubscribeReset)||void 0===t||t.call(this),this._unsubscribeReset=null,null===(n=this._disposeConnectionWatcher)||void 0===n||n.call(this),this._disposeConnectionWatcher=null,null===(i=this._disposeRealtimeReadyWatcher)||void 0===i||i.call(this),this._disposeRealtimeReadyWatcher=null,null===(r=this._ui)||void 0===r||r.destroy(),this._ui=null,this._messageCallbacks=[],this._typingCallbacks=[],this._connectionCallbacks=[]}getWidgetContext(e,t){var n,i,r,s=this,a=this._instance.getConfig();return{channelId:null!==(i=null===(n=this._store.channel.value)||void 0===n?void 0:n.id)&&void 0!==i?i:"",distinctId:this._distinctId,primaryColor:this._store.theme.value.primaryColor,apiBase:a.api_host||"",token:a.token||"",messageId:e,buildEndpointUrl:e=>h(this._instance.getConfig(),e),dispatch:(r=c(function*(n,i){var r=s._registry.get(t);if(r){var a=s.getWidgetContext(e,t);try{var o=yield r.onAction(n,i,a);(null==o?void 0:o.success)&&s.markWidgetSubmittedAndFollowUp(e,t,i)}catch(e){I().warn(Fo,"widget action failed:",e)}}}),function(e,t){return r.apply(this,arguments)})}}markWidgetSubmittedAndFollowUp(e,t,n){var i,r,s,a,o=this._store.messages.value.find(t=>t.id===e);if(o){var l=d({},null!==(i=o.metadata)&&void 0!==i?i:{}),c=(null!==(s=null!==(r=l._widgets)&&void 0!==r?r:l.widgets)&&void 0!==s?s:[]).map(e=>{if(e.type!==t)return e;var i=d({},e,{submitted:!0});return n.email&&(i.submittedEmail=String(n.email).trim()),n.name&&(i.submittedName=String(n.name).trim()),i});l.widgets=c,l._widgets&&(l._widgets=c);var u=this._store.messages.value.map(t=>t.id===e?d({},t,{metadata:l}):t);this._store.setMessages(u);var h=null===(a=this._store.channel.value)||void 0===a?void 0:a.id;"escalate_to_human"!==t&&h&&this.triggerAIAfterWidgetAction(h)}}_outboxStorageKey(){return No(this._instance.getConfig().token||"unknown",this._distinctId)}_refreshOutboxKey(){this._outbox=new Ho(this._outboxStorageKey()),this._outbox.requeueStaleSending()}_markOutboxSending(e){this._outbox.patch(e,{state:"sending",sendingSince:Date.now()})}_failOutboxMessage(e){var t,n,i=(null!==(n=null===(t=this._outbox.get(e))||void 0===t?void 0:t.attempts)&&void 0!==n?n:0)+1;this._outbox.patch(e,{state:"failed",attempts:i,nextRetryAt:qo(i),sendingSince:void 0}),Lo(this._store,e,"failed")}_bindOutboxToChannel(e){for(var t of this._outbox.list())t.newChannel&&!t.channelId&&this._outbox.patch(t.messageId,{channelId:e,newChannel:void 0})}_rememberLastCreatedChannel(e){!function(e,t){if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem(Bo(e),JSON.stringify({channelId:t,at:Date.now()}))}catch(e){}}(this._outboxStorageKey(),e)}_migrateOutboxFromDistinctId(e){var t=this._distinctId;if(e&&e!==t){var n=this._instance.getConfig().token||"unknown",i=new Ho(No(n,e)),r=i.list();for(var s of r)this._outbox.upsert(d({},s,{distinctId:t})),i.remove(s.messageId)}}_bindOutboxLifecycle(){"undefined"!=typeof window&&(window.addEventListener("online",this._onOutboxOnline),document.addEventListener("visibilitychange",this._onOutboxVisible))}_unbindOutboxLifecycle(){"undefined"!=typeof window&&(window.removeEventListener("online",this._onOutboxOnline),document.removeEventListener("visibilitychange",this._onOutboxVisible))}_enqueueOutbox(e){this._outbox.upsert(e)}_markMessageDelivered(e,t){var n,i;this._outbox.remove(e),Lo(this._store,e,void 0),null===(i=(n=this._config).onMessageDelivered)||void 0===i||i.call(n,{channelId:t,messageId:e})}_scheduleDrainOutbox(){this._drainTimer&&clearTimeout(this._drainTimer),this._drainTimer=setTimeout(()=>{this._drainTimer=null,this._drainOutbox()},0)}_drainOutbox(){var e=this;return c(function*(){if(!e._drainInFlight){e._drainInFlight=!0,e._outbox.requeueStaleSending();try{var t=Date.now(),n=function*(t){var n=e._store.messages.value.some(e=>e.id===t.messageId&&"sending"===e.delivery_status);if(n)return 1;try{yield e._deliverOutboxEntry(t)}catch(n){I().warn(Fo,"outbox drain failed:",n);var i=t.attempts+1;e._outbox.patch(t.messageId,{state:"failed",attempts:i,nextRetryAt:qo(i)}),Lo(e._store,t.messageId,"failed")}};for(var i of e._outbox.dueEntries(t))yield*n(i)}finally{e._drainInFlight=!1;var r=e._outbox.dueEntries(Date.now());if(r.length>0){var s=Math.max(0,r[0].nextRetryAt-Date.now());e._drainTimer=setTimeout(()=>{e._drainTimer=null,e._drainOutbox()},s)}}}})()}_deliverOutboxEntry(e){var t=this;return c(function*(){var n=e.channelId||void 0;if(!n&&e.newChannel){var i=function(e,t){if(void 0===t&&(t=Date.now()),"undefined"==typeof sessionStorage)return null;try{var n=sessionStorage.getItem(Bo(e));if(!n)return null;var i=JSON.parse(n);return!(null==i?void 0:i.channelId)||"number"!=typeof i.at||t-i.at>12e4?null:i}catch(e){return null}}(t._outboxStorageKey());i&&(n=i.channelId,t._outbox.patch(e.messageId,{channelId:n,newChannel:void 0}))}if(!n&&e.newChannel){var r=yield t._createChannelIdForOutbox(e.newChannel.skipGreeting);if(!(n=null!=r?r:void 0))throw new Error("Failed to create channel for outbox entry");t._outbox.patch(e.messageId,{channelId:n,newChannel:void 0}),t._rememberLastCreatedChannel(n)}if(!n)throw new Error("Outbox entry missing channelId");var s=t._store.messages.value.find(t=>t.id===e.messageId);if(s)return t._markOutboxSending(e.messageId),void(yield t._postUserMessage({messageId:e.messageId,channelId:n,body:e.body,content_type:e.content_type,metadata:e.metadata,tempMessage:s}));yield t._postUserMessageSilent({messageId:e.messageId,channelId:n,body:e.body,content_type:e.content_type,metadata:e.metadata}),t._markMessageDelivered(e.messageId,n)})()}_createChannelIdForOutbox(t){var n=this;return c(function*(){var i,r,s,a=yield ne(n._instance,Y,{method:"POST",body:JSON.stringify(d({distinct_id:n._distinctId,page_url:null===(i=null==e?void 0:e.location)||void 0===i?void 0:i.href,page_title:"undefined"!=typeof document?document.title:""},t&&{skip_greeting:!0}))}),o=null!==(s=null===(r=null==a?void 0:a.channel)||void 0===r?void 0:r.id)&&void 0!==s?s:null;return o&&(n._bindOutboxToChannel(o),n._rememberLastCreatedChannel(o)),o})()}_postUserMessageSilent(e){var t=this;return c(function*(){var n,i=t._instance.getConfig(),r=h(i,Z(e.channelId)),s=yield fetch(r,{method:"POST",keepalive:!0,headers:d({"Content-Type":"application/json"},p(i)),body:JSON.stringify({id:e.messageId,channel_id:e.channelId,distinct_id:t._distinctId,content:e.body,content_type:e.content_type,metadata:e.metadata})});if(!s.ok)throw new Error("API error: "+s.status);if(!(yield Uo(s,e.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(()=>{}))})()}_postUserMessage(e){var t=this;return c(function*(){var n,i,r,s,a,{messageId:o,channelId:l,body:c,content_type:u,metadata:v,tempMessage:g}=e;Lo(t._store,o,"sending"),t._cancelActiveStream();var f=new AbortController;t._streamAbort=f,!1!==(null===(n=t._store.channel.value)||void 0===n?void 0:n.ai_mode)&&t._showOptimisticAiTyping();var _=t._instance.getConfig(),m=h(_,Z(l)),y=yield fetch(m,{method:"POST",keepalive:!0,signal:f.signal,headers:d({"Content-Type":"application/json"},p(_)),body:JSON.stringify({id:o,channel_id:l,distinct_id:t._distinctId,content:c,content_type:u,metadata:v})});if(!y.ok)throw new Error("API error: "+y.status);if(!(yield Uo(y,o)))throw new Error("User message not acknowledged");if(t._markMessageDelivered(o,l),(y.headers.get("content-type")||"").includes("text/plain"))yield fi({store:t._store,response:y,channelId:l,signal:f.signal,isActive:()=>t._streamAbort===f,onStreamStart:e=>{t._clearOptimisticAiTyping(),t._streamAbort===f&&(t._streamingMessageId=e)},onComplete:()=>{var e,n,i,r;t._streamAbort===f&&(t._streamAbort=null,t._streamingMessageId=null),null===(n=(e=t._config).onMessageSent)||void 0===n||n.call(e,{channelId:l,messageId:g.id}),t._trackChatMessage(g,l,null===(r=null===(i=t._store.channel.value)||void 0===i?void 0:i.ai_mode)||void 0===r||r)}});else{t._clearOptimisticAiTyping(),t._streamAbort===f&&(t._streamAbort=null);var b=yield y.json();if(null==b?void 0:b.message){var w=t._store.messages.value.findIndex(e=>e.id===b.message.id);if(-1===w&&(w=t._store.messages.value.findIndex(e=>e.id===o)),-1!==w){var C=[...t._store.messages.value];C[w]=b.message,t._store.setMessages(C)}null===(r=(i=t._config).onMessageSent)||void 0===r||r.call(i,{channelId:l,messageId:b.message.id}),t._trackChatMessage(b.message,l,null!==(a=null===(s=t._store.channel.value)||void 0===s?void 0:s.ai_mode)&&void 0!==a&&a)}}})()}get _distinctId(){return this._instance.getDistinctId()||""}_stubChannelFromSummary(e){return{id:e.id,project_id:"",person_id:"",distinct_id:this._distinctId,status:e.status,ai_mode:e.ai_mode,unread_count:e.unread_count,last_message_at:e.last_message_at,last_message_preview:e.last_message_preview,last_message_sender:e.last_message_sender,user_last_read_at:e.user_last_read_at,agent_last_read_at:null,created_at:e.created_at}}_handleIdentityChange(){var e=this;return c(function*(){if(!e._identityChangeInFlight){var t=e._distinctId;if(t&&t!==e._store.lastConnectedDistinctId.value){e._identityChangeInFlight=!0,e._store.identityChangeInFlight.value=!0,e._store.clearActiveChannel(),e._store.currentView.value="list",e._migrateOutboxFromDistinctId(e._outboxDistinctId),e._refreshOutboxKey(),e._outboxDistinctId=t;try{yield e._ably.disconnectAll(),e._store.channels.value=[],e._store.clearMessagesCache(),yield e.getChannels(),e._store.isOpen.value&&(yield e._ably.ensureConnected()),e._scheduleDrainOutbox()}catch(e){I().error(Fo,"failed to recreate Ably client after identity change:",e)}finally{e._identityChangeInFlight=!1,e._store.identityChangeInFlight.value=!1}}}})()}_waitForIdentityChange(){return new Promise(e=>{if(this._store.identityChangeInFlight.value)var t=this._store.identityChangeInFlight.subscribe(n=>{n||(t(),e())});else e()})}_trackChatMessage(e,t,n){var i,r=this._instance.getRemoteConfig(),s=null==r?void 0:r.chatTracking;if("user"===e.sender_type){if(!1===(null==s?void 0:s.trackUserMessages))return}else if(("ai"===e.sender_type||"agent"===e.sender_type)&&!1===(null==s?void 0:s.trackAgentMessages))return;this._instance.capture(ce,{$channel_type:"chat",$conversation_id:t,$message_id:e.id,$direction:"user"===e.sender_type?"inbound":"outbound",$sender_type:e.sender_type,$content_preview:(null!==(i=e.content)&&void 0!==i?i:"").slice(0,100),$ai_mode:n})}_autoMarkAsRead(){var e,t=this._store.channel.value;if(t&&!this._isMarkingRead){var n=this._store.messages.value,i=n[n.length-1];if(i){var r=this._store.initialUserReadAt.value,s=n.some(e=>{return!("agent"!==e.sender_type&&"ai"!==e.sender_type||(t=e.created_at,r&&new Date(t)<=new Date(r)));var t}),a=this._store.channels.value.find(e=>e.id===t.id),o=(null!==(e=null==a?void 0:a.unread_count)&&void 0!==e?e:0)>0;(s||o)&&(this._isMarkingRead=!0,ne(this._instance,ee(t.id),{method:"POST",body:JSON.stringify({channel_id:t.id,distinct_id:this._distinctId,read_at:i.created_at})}).then(e=>{e&&(this._store.initialUserReadAt.value=i.created_at,this._store.patchChannelSummary(t.id,{unread_count:0})),this._isMarkingRead=!1}).catch(()=>{this._isMarkingRead=!1}))}}}_publishTyping(e){this._ably.publishTyping({sender_type:"user",sender_name:null,is_typing:e,sender_id:this._distinctId})}_watchConnectionState(){return this._store.isConnected.subscribe(e=>{this._lastConnectedNotified!==e&&(this._lastConnectedNotified=e,this._connectionCallbacks.forEach(t=>t(e)))})}}o.__VTiltExtensions__=o.__VTiltExtensions__||{},o.__VTiltExtensions__.initChat=function(e,t){return new jo(e,t)};var Wo="1.13.1",$o="__vt_session",zo="__vt_window_id",Vo="__vt_primary_window",Go="__vt_user_state",Ko="__vt_device_id",Jo="__vt_anonymous_id",Qo="__vt_remote_config",Xo="__vt_distinct_id",Yo="__vt_user_properties",Zo="localStorage",el="localStorage+cookie",tl="sessionStorage",nl="memory",il="$initial_person_info",rl="$pageview",sl="$pageleave",al="$identify",ol="$alias",ll="$set",cl="$performance_event",dl="$autocapture",ul="$scroll_depth",hl="$snapshot",pl="$snapshot_items",vl="$$client_ingestion_warning",gl="$current_url",fl="$pathname",_l="$prev_pageview_duration",ml="$prev_pageview_pathname",yl="$prev_pageview_url",bl="$scroll_depth_pct",wl="$scroll_depth_max_pct",Cl="$prev_pageview_scroll_depth_pct";function Sl(e,t){var n,i,r=t.bubble,s=null==e?void 0:e.bubble;if(r){var a=null===r.offset?void 0:void 0!==r.offset?d({},null===(n=null==e?void 0:e.bubble)||void 0===n?void 0:n.offset,r.offset):null===(i=null==e?void 0:e.bubble)||void 0===i?void 0:i.offset;s=d({},null==e?void 0:e.bubble,r,{offset:a})}return d({},e,t,{bubble:s})}class kl{constructor(e){void 0===e&&(e={}),this.config=this.parseConfigFromScript(e)}parseConfigFromScript(e){if(!(null==i?void 0:i.currentScript))return d({token:e.token||""},e);var t=i.currentScript,n=d({token:""},e);n.api_host=t.getAttribute("data-api-host")||t.getAttribute("data-host")||e.api_host,n.script_host=t.getAttribute("data-script-host")||e.script_host,n.token=t.getAttribute("data-token")||e.token||"",n.domain=t.getAttribute("data-domain")||e.domain,n.storage=t.getAttribute("data-storage")||e.storage,n.stringifyPayload="false"!==t.getAttribute("data-stringify-payload");var r="true"===t.getAttribute("data-capture-performance");for(var s of(n.capture_performance=!!r||e.capture_performance,n.globalAttributes=d({},e.globalAttributes),Array.from(t.attributes)))s.name.startsWith("data-vt-")&&(n.globalAttributes[s.name.slice(8).replace(/-/g,"_")]=s.value);return n}getConfig(){return d({},this.config)}updateConfig(e){var t=function(e,t){return void 0===t.chat?t:d({},t,{chat:Sl(e.chat,t.chat)})}(this.config,e);this.config=d({},this.config,t)}}var xl=[Jo,Ko,Xo,Go],Tl=31536e3,Il=["herokuapp.com","vercel.app","netlify.app"];function El(e){var t;if(!e||"undefined"==typeof document)return"";var n=null===(t=document.location)||void 0===t?void 0:t.hostname;if(!n)return"";var i=n.match(/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i);return i?"."+i[0]:""}class Al{constructor(e){var t,n,i;this.memoryStorage=new Map,this._localStorageSupported=null,this.method=e.method,this.cross_subdomain=null!==(t=e.cross_subdomain)&&void 0!==t?t:function(){var e;if("undefined"==typeof document)return!1;var t=null===(e=document.location)||void 0===e?void 0:e.hostname;if(!t)return!1;var n=t.split(".").slice(-2).join(".");return!Il.includes(n)}(),this.sameSite=null!==(n=e.sameSite)&&void 0!==n?n:"Lax",this.secure=null!==(i=e.secure)&&void 0!==i?i:"undefined"!=typeof location&&"https:"===location.protocol}isLocalStorageSupported(){if(null!==this._localStorageSupported)return this._localStorageSupported;if(void 0===e||!e.localStorage)return this._localStorageSupported=!1,!1;try{var t="__vt_ls_test__";e.localStorage.setItem(t,"1");var n="1"===e.localStorage.getItem(t);return e.localStorage.removeItem(t),this._localStorageSupported=n,n||I().warn("storage","localStorage unavailable, using cookies"),n}catch(e){return this._localStorageSupported=!1,I().warn("storage","localStorage unavailable, using cookies"),!1}}isCriticalProperty(e){return xl.includes(e)}get(e){var t;try{switch(this.method){case nl:return null!==(t=this.memoryStorage.get(e))&&void 0!==t?t:null;case el:return this.getLocalStoragePlusCookie(e);case Zo:return this.getLocalStorage(e);case tl:return this.readFromSessionStorage(e);default:return this.getCookie(e)}}catch(t){return I().warn("storage",'get error for "'+e+'":',t),null}}set(e,t,n){try{switch(this.method){case nl:this.memoryStorage.set(e,t);break;case el:this.setLocalStoragePlusCookie(e,t,n);break;case Zo:this.setLocalStorage(e,t);break;case tl:this.writeToSessionStorage(e,t);break;default:this.setCookie(e,t,null!=n?n:Tl)}}catch(t){I().warn("storage",'set error for "'+e+'":',t)}}remove(e){try{switch(this.method){case nl:this.memoryStorage.delete(e);break;case el:this.removeLocalStoragePlusCookie(e);break;case Zo:this.removeLocalStorage(e);break;case tl:this.removeFromSessionStorage(e);break;default:this.removeCookie(e)}}catch(t){I().warn("storage",'remove error for "'+e+'":',t)}}getLocalStoragePlusCookie(t){if(this.isCriticalProperty(t)){var n=this.getCookie(t),i=this.getLocalStorage(t);if(null!==n){if(i!==n&&this.isLocalStorageSupported())try{null==e||e.localStorage.setItem(t,n)}catch(e){}return n}return null!==i?i:this.readFromSessionStorage(t)}return this.getLocalStorage(t)}setLocalStoragePlusCookie(e,t,n){this.setLocalStorage(e,t),this.isCriticalProperty(e)&&(this.setCookie(e,t,null!=n?n:Tl),this.writeToSessionStorage(e,t))}removeLocalStoragePlusCookie(e){this.removeLocalStorage(e),this.isCriticalProperty(e)&&(this.removeCookie(e),this.removeFromSessionStorage(e))}getLocalStorage(t){var n;if(!this.isLocalStorageSupported())return null;try{return null!==(n=null==e?void 0:e.localStorage.getItem(t))&&void 0!==n?n:null}catch(e){return null}}setLocalStorage(t,n){if(this.isLocalStorageSupported())try{null==e||e.localStorage.setItem(t,n)}catch(e){I().warn("storage","localStorage write error:",e)}}removeLocalStorage(t){if(this.isLocalStorageSupported())try{null==e||e.localStorage.removeItem(t)}catch(e){}}readFromSessionStorage(t){var n;try{return null!==(n=null==e?void 0:e.sessionStorage.getItem(t))&&void 0!==n?n:null}catch(e){return null}}writeToSessionStorage(t,n){try{null==e||e.sessionStorage.setItem(t,n)}catch(e){I().warn("storage","sessionStorage write error:",e)}}removeFromSessionStorage(t){try{null==e||e.sessionStorage.removeItem(t)}catch(e){}}getCookie(e){if("undefined"==typeof document)return null;var t=e+"=";for(var n of document.cookie.split(";")){var i=n.trim();if(i.startsWith(t))try{return decodeURIComponent(i.slice(t.length))}catch(e){return i.slice(t.length)}}return null}setCookie(e,t,n){if("undefined"!=typeof document){var i=El(this.cross_subdomain),r=e+"="+encodeURIComponent(t)+"; Max-Age="+n+"; path=/; SameSite="+this.sameSite;this.secure&&(r+="; Secure"),i&&(r+="; domain="+i),document.cookie=r}}removeCookie(e){if("undefined"!=typeof document){var t=El(this.cross_subdomain);document.cookie=e+"=; Max-Age=0; path=/"+(t?"; domain="+t:""),document.cookie=e+"=; Max-Age=0; path=/"}}getWithExpiry(e){var t=this.get(e);if(!t)return null;try{var n=JSON.parse(t);return n.expiry&&Date.now()>n.expiry?(this.remove(e),null):n.value}catch(e){return null}}setWithExpiry(e,t,n){var i=d({value:t},n?{expiry:Date.now()+n}:{});this.set(e,JSON.stringify(i))}getJSON(e){var t=this.get(e);if(!t)return null;try{return JSON.parse(t)}catch(e){return null}}setJSON(e,t,n){this.set(e,JSON.stringify(t),n)}canUseSessionStorage(){if(void 0===e||!(null==e?void 0:e.sessionStorage))return!1;try{var t="__vt_ss_test__";return e.sessionStorage.setItem(t,"1"),e.sessionStorage.removeItem(t),!0}catch(e){return!1}}getSessionStorage(){var t;return this.canUseSessionStorage()&&null!==(t=null==e?void 0:e.sessionStorage)&&void 0!==t?t:null}setMethod(e){this.method=e}getMethod(){return this.method}}class Ol{constructor(e,t){void 0===e&&(e="cookie"),this._isNewSession=!1,this.storage=new Al({method:e,cross_subdomain:t,sameSite:"Lax"}),this._windowId=void 0,I().debug("session","ctor")}hydrateFromStorage(){I().debug("session","hydrate"),this._initializeWindowId()}getSessionId(){var e=this._getSessionIdRaw();return e||(e=z(16),this._storeSessionId(e),this._isNewSession=!0),e}setSessionId(){var e=this._getSessionIdRaw(),t=e||z(16);return e||(this._isNewSession=!0),this._storeSessionId(t),t}resetSessionId(){this._clearSessionId(),this._isNewSession=!0,this.setSessionId(),this._setWindowId(z(16))}consumeSessionStart(){return!!this._isNewSession&&(this._isNewSession=!1,!0)}_getSessionIdRaw(){return this.storage.get($o)}_storeSessionId(e){this.storage.set($o,e,1800)}_clearSessionId(){this.storage.remove($o)}getWindowId(){if(this._windowId)return this._windowId;var e=this.storage.getSessionStorage();if(e){var t=e.getItem(zo);if(t)return this._windowId=t,t}var n=z(16);return this._setWindowId(n),n}_setWindowId(e){if(e!==this._windowId){this._windowId=e;var t=this.storage.getSessionStorage();t&&t.setItem(zo,e)}}_initializeWindowId(){var e=this.storage.getSessionStorage();if(e){var t=e.getItem(Vo),n=e.getItem(zo);n&&!t?this._windowId=n:(n&&e.removeItem(zo),this._setWindowId(z(16))),e.setItem(Vo,"true"),this._listenToUnload()}else this._windowId=z(16)}_listenToUnload(){var t=this.storage.getSessionStorage();e&&t&&K(e,"beforeunload",()=>{var e=this.storage.getSessionStorage();e&&e.removeItem(Vo)},{capture:!1})}updateStorageMethod(e,t){this.storage=new Al({method:e,cross_subdomain:t,sameSite:"Lax"})}}function Ml(e){if(!i)return null;var t=i.createElement("a");return t.href=e,t}function Rl(e){try{return decodeURIComponent(e).replace(/\+/g," ")}catch(t){return e.replace(/\+/g," ")}}function Pl(e){for(var t={},n=function(e){return((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"")}(e).split("&"),i=0;i<n.length;i++){var r=n[i];if(r){var s=r.indexOf("="),a=-1===s?r:r.slice(0,s);if(a){var o=Rl(a),l=-1===s?"":r.slice(s+1);t[o]=Rl(l)}}}return t}function Ll(e,t){var n;return null!==(n=Pl(e)[t])&&void 0!==n?n:""}function Ul(e,t,n){if(!e||!t||!t.length)return e;for(var i=e.split("#"),r=i[0]||"",s=i[1],a=r.split("?"),o=a[1],l=a[0],c=(o||"").split("&"),d=[],u=0;u<c.length;u++){var h=c[u].split("="),p=h[0],v=h.slice(1).join("=");-1!==t.indexOf(p)?d.push(p+"="+n):p&&d.push(p+(v?"="+v:""))}var g=d.join("&");return l+(g?"?"+g:"")+(s?"#"+s:"")}var Dl="_fbp",Nl="_fbc",Bl=15552e3,Hl=7776e3;function ql(){void 0!==i&&(function(){if(Fl(Dl))return;var e=Date.now(),t=Math.floor(1e9+9e9*Math.random()),n="fb.1."+e+"."+t;jl(Dl,n,Bl)}(),function(){if(!(null==r?void 0:r.search))return;try{var e=new URL(r.href).searchParams.get("fbclid");if(!(null==e?void 0:e.trim()))return;var t="fb.1."+Date.now()+"."+e.trim();jl(Nl,t,Hl)}catch(e){}}())}function Fl(e){if(void 0===i||!(null==i?void 0:i.cookie))return null;var t=e+"=";for(var n of i.cookie.split(";")){var r=n.trim();if(r.startsWith(t))try{return decodeURIComponent(r.slice(t.length))}catch(e){return r.slice(t.length)}}return null}function jl(e,t,n){if(void 0!==i){var s=void 0!==r&&"https:"===r.protocol?"; Secure":"";i.cookie=e+"="+encodeURIComponent(t)+"; Max-Age="+n+"; path=/; SameSite=Lax"+s}}var Wl="Mobile",$l="iOS",zl="Android",Vl="Tablet",Gl=zl+" "+Vl,Kl="iPad",Jl="Apple",Ql=Jl+" Watch",Xl="Safari",Yl="BlackBerry",Zl="Samsung",ec=Zl+"Browser",tc=Zl+" Internet",nc="Chrome",ic=nc+" OS",rc=nc+" "+$l,sc="Internet Explorer",ac=sc+" "+Wl,oc="Opera",lc=oc+" Mini",cc="Edge",dc="Microsoft "+cc,uc="Firefox",hc=uc+" "+$l,pc="Nintendo",vc="PlayStation",gc="Xbox",fc=zl+" "+Wl,_c=Wl+" "+Xl,mc="Windows",yc=mc+" Phone",bc="Nokia",wc="Ouya",Cc="Generic",Sc=Cc+" "+Wl.toLowerCase(),kc=Cc+" "+Vl.toLowerCase(),xc="Konqueror",Tc="(\\d+(\\.\\d+)?)",Ic=new RegExp("Version/"+Tc),Ec=new RegExp(gc,"i"),Ac=new RegExp(vc+" \\w+","i"),Oc=new RegExp(pc+" \\w+","i"),Mc=new RegExp(Yl+"|PlayBook|BB10","i"),Rc={"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 Pc(e,t){return e.toLowerCase().includes(t.toLowerCase())}var Lc=(e,t)=>t&&Pc(t,Jl)||function(e){return Pc(e,Xl)&&!Pc(e,nc)&&!Pc(e,zl)}(e),Uc=function(e,t){return t=t||"",Pc(e," OPR/")&&Pc(e,"Mini")?lc:Pc(e," OPR/")?oc:Mc.test(e)?Yl:Pc(e,"IE"+Wl)||Pc(e,"WPDesktop")?ac:Pc(e,ec)?tc:Pc(e,cc)||Pc(e,"Edg/")?dc:Pc(e,"FBIOS")?"Facebook "+Wl:Pc(e,"UCWEB")||Pc(e,"UCBrowser")?"UC Browser":Pc(e,"CriOS")?rc:Pc(e,"CrMo")||Pc(e,nc)?nc:Pc(e,zl)&&Pc(e,Xl)?fc:Pc(e,"FxiOS")?hc:Pc(e.toLowerCase(),xc.toLowerCase())?xc:Lc(e,t)?Pc(e,Wl)?_c:Xl:Pc(e,uc)?uc:Pc(e,"MSIE")||Pc(e,"Trident/")?sc:Pc(e,"Gecko")?uc:""},Dc={[ac]:[new RegExp("rv:"+Tc)],[dc]:[new RegExp(cc+"?\\/"+Tc)],[nc]:[new RegExp("("+nc+"|CrMo)\\/"+Tc)],[rc]:[new RegExp("CriOS\\/"+Tc)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Tc)],[Xl]:[Ic],[_c]:[Ic],[oc]:[new RegExp("(Opera|OPR)\\/"+Tc)],[uc]:[new RegExp(uc+"\\/"+Tc)],[hc]:[new RegExp("FxiOS\\/"+Tc)],[xc]:[new RegExp("Konqueror[:/]?"+Tc,"i")],[Yl]:[new RegExp(Yl+" "+Tc),Ic],[fc]:[new RegExp("android\\s"+Tc,"i")],[tc]:[new RegExp(ec+"\\/"+Tc)],[sc]:[new RegExp("(rv:|MSIE )"+Tc)],Mozilla:[new RegExp("rv:"+Tc)]},Nc=function(e,t){var n=Uc(e,t),i=Dc[n];if(void 0===i)return null;for(var r=0;r<i.length;r++){var s=i[r],a=e.match(s);if(a)return parseFloat(a[a.length-2])}return null},Bc=[[new RegExp(gc+"; "+gc+" (.*?)[);]","i"),e=>[gc,e&&e[1]||""]],[new RegExp(pc,"i"),[pc,""]],[new RegExp(vc,"i"),[vc,""]],[Mc,[Yl,""]],[new RegExp(mc,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[yc,""];if(new RegExp(Wl).test(t)&&!/IEMobile\b/.test(t))return[mc+" "+Wl,""];var n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){var i=n[1],r=Rc[i]||"";return/arm/i.test(t)&&(r="RT"),[mc,r]}return[mc,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){var t=[e[3],e[4],e[5]||"0"];return[$l,t.join(".")]}return[$l,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=void 0===e[2]?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+zl+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+zl+")","i"),e=>{if(e&&e[2]){var t=[e[2],e[3],e[4]||"0"];return[zl,t.join(".")]}return[zl,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var t=["Mac OS X",""];if(e&&e[1]){var n=[e[1],e[2],e[3]||"0"];t[1]=n.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[ic,""]],[/Linux|debian/i,["Linux",""]]],Hc=function(e){return Oc.test(e)?pc:Ac.test(e)?vc:Ec.test(e)?gc:new RegExp(wc,"i").test(e)?wc:new RegExp("("+yc+"|WPDesktop)","i").test(e)?yc:/iPad/.test(e)?Kl:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?Ql:Mc.test(e)?Yl:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(bc,"i").test(e)?bc:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?!new RegExp(Wl).test(e)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)?/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?zl:Gl:zl:new RegExp("(pda|"+Wl+")","i").test(e)?Sc:new RegExp(Vl,"i").test(e)&&!new RegExp(Vl+" pc","i").test(e)?kc:""},qc="https?://(.*)",Fc=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],jc=Q(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],Fc),Wc="<masked>";function $c(e,t){var n=jc.concat([]),i=J({},function(e){var t={};return G(Pl(e),function(e,n){"string"==typeof n&&n.startsWith("utm_")&&e&&(t[n]=e)}),t}(e));return G(n,function(t){if(t.startsWith("utm_")){if(!(t in i)){var n=Ll(e,t);i[t]=n||null}}else{var r=Ll(e,t);i[t]=r||null}}),i}function zc(e){var t=function(e){return e?0===e.search(qc+"google.([^/?]*)")?"google":0===e.search(qc+"bing.com")?"bing":0===e.search(qc+"yahoo.com")?"yahoo":0===e.search(qc+"duckduckgo.com")?"duckduckgo":null:null}(e),n="yahoo"!==t?"q":"p",r={};if(!function(e){return null===e}(t)){r.$search_engine=t;var s=i?Ll(i.referrer,n):"";s.length&&(r.ph_keyword=s)}return r}function Vc(){if("undefined"!=typeof navigator)return navigator.language||navigator.userLanguage}function Gc(){return(null==i?void 0:i.referrer)||"$direct"}function Kc(){var e;return(null==i?void 0:i.referrer)&&(null===(e=Ml(i.referrer))||void 0===e?void 0:e.host)||"$direct"}function Jc(e){var t=function(e){var t,{r:n,u:i}=e,r={$referrer:n,$referring_domain:null==n?void 0:"$direct"===n?"$direct":null===(t=Ml(n))||void 0===t?void 0:t.host};if(i){r.$current_url=i;var s=Ml(i);r.$host=null==s?void 0:s.host,r.$pathname=null==s?void 0:s.pathname,J(r,$c(i))}return n&&J(r,zc(n)),r}(e),n={};return G(t,function(e,t){var i;n["$initial_"+(i=String(t),i.startsWith("$")?i.substring(1):i)]=e}),n}function Qc(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}function Xc(){try{return(new Date).getTimezoneOffset()}catch(e){return}}function Yc(t,n){if(!a)return{};var i,s,o,l=t?Q([],Fc,n||[]):[],[c,d]=function(e){for(var t=0;t<Bc.length;t++){var[n,i]=Bc[t],r=n.exec(e);if(r){var s="function"==typeof i?i(r,e):i;if(s)return s}}return["",""]}(a),u=Fl(Dl)||void 0,h=Fl(Nl)||void 0;return J(X({$os:c,$os_version:d,$browser:Uc(a,navigator.vendor),$device:Hc(a),$device_type:(s=a,o=Hc(s),o===Kl||o===Gl||"Kobo"===o||"Kindle Fire"===o||o===kc?Vl:o===pc||o===gc||o===vc||o===wc?"Console":o===Ql?"Wearable":o?Wl:"Desktop"),$timezone:Qc(),$timezone_offset:Xc(),$fb_browser_id:u,$fb_click_id:h}),{$current_url:Ul(null==r?void 0:r.href,l,Wc),$host:null==r?void 0:r.host,$pathname:null==r?void 0:r.pathname,$raw_user_agent:a.length>1e3?a.substring(0,997)+"...":a,$browser_version:Nc(a,navigator.vendor),$browser_language:Vc(),$browser_language_prefix:(i=Vc(),"string"==typeof i?i.split("-")[0]:void 0),$screen_height:null==e?void 0:e.screen.height,$screen_width:null==e?void 0:e.screen.width,$viewport_height:null==e?void 0:e.innerHeight,$viewport_width:null==e?void 0:e.innerWidth,$lib:"web",$lib_version:Wo,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10)})}class Zc{constructor(e,t){void 0===e&&(e="localStorage"),this._isFirstVisit=!1,this.storage=new Al({method:e,cross_subdomain:t,sameSite:"Lax"}),this.userIdentity=this.generateEphemeralIdentity(),I().debug("user","ctor","ephemeral identity only")}hydrateFromStorage(){I().debug("user","hydrate start"),this.userIdentity=this.loadUserIdentity();var e=this.userIdentity.anonymous_id,t=this.userIdentity.distinct_id;I().debug("user","hydrate done","anonymous_id",e?e.slice(0,12)+"...":"n/a","distinct_id",t?t.slice(0,12)+"...":"null")}generateEphemeralIdentity(){return{distinct_id:null,anonymous_id:this.generateAnonymousId(),device_id:this.generateDeviceId(),properties:{},user_state:"anonymous"}}getUserIdentity(){return d({},this.userIdentity)}getDistinctId(){return this.userIdentity.distinct_id}getAnonymousId(){var e=this.userIdentity.anonymous_id;return e||(this.userIdentity.anonymous_id=this.generateAnonymousId(),this.storage.set(Jo,this.userIdentity.anonymous_id,Tl),I().debug("user","getAnonymousId generated (was missing)",this.userIdentity.anonymous_id.slice(0,12)+"..."),this.userIdentity.anonymous_id)}getUserProperties(){return d({},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._isFirstVisit&&(this._isFirstVisit=!1,!0)}applyUpdate(e){if(void 0!==e.distinct_id&&(this.userIdentity.distinct_id=e.distinct_id),void 0!==e.user_state&&(this.userIdentity.user_state=e.user_state),void 0!==e.device_id&&(this.userIdentity.device_id=e.device_id),e.properties_set&&(this.userIdentity.properties=d({},this.userIdentity.properties,e.properties_set)),e.properties_set_once)for(var t of Object.keys(e.properties_set_once))t in this.userIdentity.properties||(this.userIdentity.properties[t]=e.properties_set_once[t]);this.saveUserIdentity()}reset(e){this.userIdentity={distinct_id:null,anonymous_id:this.generateAnonymousId(),device_id:e?this.generateDeviceId():this.userIdentity.device_id,properties:{$last_vtilt_reset:(new Date).toISOString()},user_state:"anonymous"},this.saveUserIdentity()}set_initial_person_info(e,t){if(!this.getStoredUserProperties()[il]){var n=function(e,t){var n=e?Q([],Fc,t||[]):[],i=null==r?void 0:r.href.substring(0,1e3);return{r:Gc().substring(0,1e3),u:i?Ul(i,n,Wc):void 0}}(e,t);this.register_once({[il]:n},void 0)}}get_initial_props(){var e=this.getStoredUserProperties()[il];return e?Jc(e):{}}update_referrer_info(){var e={$referrer:Gc(),$referring_domain:Kc()};this.register_once(e,void 0)}loadUserIdentity(){var e=this.storage.get(Jo),t=this.storage.get(Ko),n=this.storage.get(Xo),i=this.storage.get(Go),r=this.getStoredUserProperties(),s=e||this.generateAnonymousId(),a=t||this.generateDeviceId(),o=n||null,l=i||"anonymous";e?I().debug("user","hydrate","loaded from storage",e.slice(0,12)+"..."):(this._isFirstVisit=!0,I().debug("user","hydrate","generated new anonymous_id"));var c=s||this.generateAnonymousId();return e||this.storage.set(Jo,c,Tl),t||this.storage.set(Ko,a,Tl),i||this.storage.set(Go,l,Tl),{distinct_id:o,anonymous_id:c,device_id:a,properties:r,user_state:l}}saveUserIdentity(){this.storage.set(Jo,this.userIdentity.anonymous_id,Tl),this.storage.set(Ko,this.userIdentity.device_id,Tl),this.storage.set(Go,this.userIdentity.user_state,Tl),this.userIdentity.distinct_id?this.storage.set(Xo,this.userIdentity.distinct_id,Tl):this.storage.remove(Xo),this.setStoredUserProperties(this.userIdentity.properties)}getStoredUserProperties(){return this.storage.getJSON(Yo)||{}}setStoredUserProperties(e){this.storage.setJSON(Yo,e,Tl)}register_once(e,t){var n=this.getStoredUserProperties(),i=!1;for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(r in n||(n[r]=e[r],i=!0));if(t)for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(s in n||(n[s]=t[s],i=!0));i&&this.setStoredUserProperties(n)}generateAnonymousId(){return"anon_"+z(16)}generateDeviceId(){return"device_"+z(16)}updateStorageMethod(e,t){this.storage=new Al({method:e,cross_subdomain:t,sameSite:"Lax"})}}var ed=["LCP","CLS","FCP","INP"];class td{constructor(e,t){this._isStarted=!1,this._isLoading=!1,this._loadCallbacks=[],this._apiReady=!1,this._deferredCalls=[],this._instance=e,this._config=t}get isEnabled(){return!1!==this._config.enabled}get isStarted(){return this._isStarted}get isLoaded(){return!!this._loaded}_ensureLoaded(e){var t;if(this._loaded)e(this._loaded);else if(this._loadCallbacks.push(e),!this._isLoading){this._isLoading=!0;var n=null===(t=o.__VTiltExtensions__)||void 0===t?void 0:t.loadExternalDependency;if(!n)return I().error("feature",this.name,"loadExternalDependency not available"),this._isLoading=!1,void(this._loadCallbacks=[]);n(this._instance,this.scriptName,e=>{if(this._isLoading=!1,e)return I().error("feature",this.name,"could not load "+this.scriptName+":",e),void(this._loadCallbacks=[]);this._loaded||(this._loaded=this._createLoaded());var t=this._loaded,n=this._loadCallbacks;for(var i of(this._loadCallbacks=[],n))try{i(t)}catch(e){I().error("feature",this.name,"load callback error:",e)}})}}startIfEnabled(){this.isEnabled&&!this._isStarted&&(this._isStarted=!0,this._ensureLoaded(e=>this._onLoaded(e)))}_onLoaded(e){}stop(){this._isStarted=!1}updateConfig(e){this._config=d({},this._config,e)}_deferCall(e){this._apiReady?e():this._deferredCalls.push(e)}_markApiReady(){if(!this._apiReady){this._apiReady=!0;var e=this._deferredCalls;for(var t of(this._deferredCalls=[],e))try{t()}catch(e){I().error("feature",this.name,"deferred call error:",e)}}}_resetDeferral(){this._apiReady=!1,this._deferredCalls=[]}}class nd extends td{startIfEnabledOrStop(e){if(this.isEnabled){if(this._isStarted&&this._loaded)return;this._isStarted=!0,this._ensureLoaded(e=>this._onLoaded(e))}else this.stop()}}var id=9e5,rd="web-vitals";class sd extends td{static extractConfig(e){var t=e.capture_performance;return"boolean"==typeof t?{web_vitals:t}:"object"==typeof t&&null!==t?t:{web_vitals:!1}}constructor(e,t){super(e,null!=t?t:sd.extractConfig(e.getConfig())),this.name="WebVitals",this.scriptName="web-vitals",this._buffer=this._createEmptyBuffer()}get isEnabled(){var e=null==r?void 0:r.protocol;return("http:"===e||"https:"===e)&&!0===this._config.web_vitals}startIfEnabled(){if(this.isEnabled&&!this._isStarted&&e){var t=this._getWebVitalsCallbacks();t?(this._isStarted=!0,this._loaded=t,this._startCapturing(t)):(this._isStarted=!0,this._ensureLoaded(e=>this._onLoaded(e)))}}stop(){this._isStarted&&(this._flush(),this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0),this._isStarted=!1)}onConfigUpdate(e){var t=sd.extractConfig(e),n=this.isEnabled;this._config=t,n||!this.isEnabled||this._isStarted?n&&!this.isEnabled&&this._isStarted&&this.stop():this.startIfEnabled()}_createLoaded(){var e=this._getWebVitalsCallbacks();if(!e)throw new Error("[vTilt:web-vitals] web-vitals loaded but callbacks not registered");return e}_onLoaded(e){this._startCapturing(e)}get allowedMetrics(){return this._config.web_vitals_allowed_metrics||ed}get flushTimeoutMs(){return this._config.web_vitals_delayed_flush_ms||5e3}get maxAllowedValue(){var e=this._config.__web_vitals_max_value;return void 0===e?id:0===e?0:e<6e4?id:e}_createEmptyBuffer(){return{url:void 0,pathname:void 0,metrics:[],firstMetricTimestamp:void 0}}_getWebVitalsCallbacks(){var e;return null===(e=o.__VTiltExtensions__)||void 0===e?void 0:e.webVitalsCallbacks}_startCapturing(e){var t=this.allowedMetrics,n=this._addToBuffer.bind(this);t.includes("LCP")&&e.onLCP&&e.onLCP(n),t.includes("CLS")&&e.onCLS&&e.onCLS(n,{reportAllChanges:!0}),t.includes("FCP")&&e.onFCP&&e.onFCP(n),t.includes("INP")&&e.onINP&&e.onINP(n),t.includes("TTFB")&&e.onTTFB&&e.onTTFB(n)}_getCurrentUrl(){var t;return null===(t=null==e?void 0:e.location)||void 0===t?void 0:t.href}_getCurrentPathname(){return null==r?void 0:r.pathname}_addToBuffer(t){var n,s,a;try{if(!e||!i||!r)return;if(!(null==t?void 0:t.name)||void 0===(null==t?void 0:t.value))return void I().warn(rd,"invalid metric received",t);if(this.maxAllowedValue>0&&t.value>=this.maxAllowedValue&&"CLS"!==t.name)return void I().warn(rd,"ignoring "+t.name+" with value >= "+this.maxAllowedValue+"ms");var o=this._getCurrentUrl(),l=this._getCurrentPathname();if(!o)return void I().warn(rd,"could not determine current URL");this._buffer.url&&this._buffer.url!==o&&this._flush(),this._buffer.url||(this._buffer.url=o,this._buffer.pathname=l),this._buffer.firstMetricTimestamp||(this._buffer.firstMetricTimestamp=Date.now());var c=this._cleanAttribution(t.attribution),u=null!==(a=null===(s=(n=this._instance).getSessionId)||void 0===s?void 0:s.call(n))&&void 0!==a?a:null,h=this._getWindowId(),p=d({},t,{attribution:c,timestamp:Date.now(),$current_url:o,$session_id:u,$window_id:h}),v=this._buffer.metrics.findIndex(e=>e.name===t.name);v>=0?this._buffer.metrics[v]=p:this._buffer.metrics.push(p),this._scheduleFlush(),this._buffer.metrics.length>=this.allowedMetrics.length&&this._flush()}catch(e){I().error(rd,"error adding metric to buffer:",e)}}_cleanAttribution(e){if(e){var t=d({},e);return"interactionTargetElement"in t&&delete t.interactionTargetElement,t}}_getWindowId(){var e;try{return(null===(e=this._instance.sessionManager)||void 0===e?void 0:e.getWindowId())||null}catch(e){return null}}_scheduleFlush(){this._flushTimer&&clearTimeout(this._flushTimer),this._flushTimer=setTimeout(()=>{this._flush()},this.flushTimeoutMs)}_flush(){if(this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0),0!==this._buffer.metrics.length){try{var e={$pathname:this._buffer.pathname,$current_url:this._buffer.url};for(var t of this._buffer.metrics)e["$web_vitals_"+t.name+"_value"]=t.value,e["$web_vitals_"+t.name+"_event"]={name:t.name,value:t.value,delta:t.delta,rating:t.rating,id:t.id,navigationType:t.navigationType,attribution:t.attribution,$session_id:t.$session_id,$window_id:t.$window_id};this._instance.capture("$web_vitals",e)}catch(e){I().error(rd,"error flushing metrics:",e)}this._buffer=this._createEmptyBuffer()}}}function ad(e,t,n){try{if(!(t in e))return()=>{};var i=e[t],r=n(i);return m(r)&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__vtilt_wrapped__:{enumerable:!1,value:!0}})),e[t]=r,()=>{e[t]=i}}catch(e){return()=>{}}}class od{constructor(t,n){var i;this.name="HistoryAutocapture",this._isStarted=!1,this._instance=t,this._config=n||od.extractConfig(t.getConfig()),this._lastPathname=(null===(i=null==e?void 0:e.location)||void 0===i?void 0:i.pathname)||""}static extractConfig(e){return{enabled:!1!==e.capture_pageview}}get isEnabled(){return!1!==this._config.enabled&&!1!==this._instance.getConfig().capture_pageview}get isStarted(){return this._isStarted}startIfEnabled(){this.isEnabled&&!this._isStarted&&this._start()}stop(){this._isStarted&&(this._popstateListener&&(this._popstateListener(),this._popstateListener=void 0),this._isStarted=!1)}onConfigUpdate(e){this._config=od.extractConfig(e),this.isEnabled&&!this._isStarted?this._start():!this.isEnabled&&this._isStarted&&this.stop()}_start(){e&&r&&(this._lastPathname=r.pathname||"",this._patchHistoryMethods(),this._setupPopstateListener(),this._isStarted=!0,I().info("history-autocapture","started"))}_patchHistoryMethods(){var t,n;if(null==e?void 0:e.history){var i=this;(null===(t=e.history.pushState)||void 0===t?void 0:t.__vtilt_wrapped__)||ad(e.history,"pushState",e=>function(t,n,r){i._emitPageleaveIfPathWillChange(r),e.call(this,t,n,r),i._capturePageview("pushState")}),(null===(n=e.history.replaceState)||void 0===n?void 0:n.__vtilt_wrapped__)||ad(e.history,"replaceState",e=>function(t,n,r){i._emitPageleaveIfPathWillChange(r),e.call(this,t,n,r),i._capturePageview("replaceState")})}}_emitPageleaveIfPathWillChange(e){var t;if(r){var n=r.pathname||"",i=null!==(t=function(e){if(!r)return null;if(null==e||""===e)return r.pathname||null;try{return new URL(String(e),r.href).pathname}catch(e){return null}}(e))&&void 0!==t?t:n;i!==n&&this._instance.tryCapturePageleave("spa_transition")}}_setupPopstateListener(){if(!this._popstateListener&&e){var t=()=>{this._capturePageview("popstate")};K(e,"popstate",t),this._popstateListener=()=>{null==e||e.removeEventListener("popstate",t)}}}_capturePageview(t){this.isEnabled&&this._isStarted&&A(()=>{var n,s=null===(n=null==e?void 0:e.location)||void 0===n?void 0:n.pathname;if(s&&r&&i)if(s!==this._lastPathname){I().debug("history-autocapture",t,s),this._lastPathname=s;var a={navigation_type:t};this._instance.capture(rl,a)}else this._lastPathname=s})}}var ld=["a","button","form","input","select","textarea","label"],cd="$copy_autocapture",dd=['[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 ud(e){return e.replace(/^\s+|\s+$/g,"")}function hd(e,t){return e.indexOf(t)>-1}function pd(e){return 1===(null==e?void 0:e.nodeType)}function vd(e){return 3===(null==e?void 0:e.nodeType)}function gd(e,t){var n;return(null===(n=null==e?void 0:e.tagName)||void 0===n?void 0:n.toLowerCase())===t}function fd(e){return 11===(null==e?void 0:e.nodeType)}function _d(e){return e?ud(e).split(/\s+/):[]}function md(e){var t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className&&"string"==typeof e.className.baseVal?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return _d(t)}function yd(e){return f(e)?null:ud(e).split(/(\s+)/).filter(e=>Rd(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function bd(e){var t,n="";if(Ld(e)&&!Ud(e)&&e.childNodes&&e.childNodes.length)for(var i=0;i<e.childNodes.length;i++){var r=e.childNodes[i];vd(r)&&r.textContent&&(n+=null!==(t=yd(r.textContent))&&void 0!==t?t:"")}return ud(n)}function wd(e){var t,n="";if(e&&e.childNodes&&e.childNodes.length)for(var i=0;i<e.childNodes.length;i++){var r=e.childNodes[i];if(r&&"span"===(null===(t=r.tagName)||void 0===t?void 0:t.toLowerCase()))try{n=(n+" "+bd(r)).trim(),r.childNodes&&r.childNodes.length&&(n=(n+" "+wd(r)).trim())}catch(e){}}return n}function Cd(e){var t=bd(e);return Rd(t=(t+" "+wd(e)).trim())?t:""}function Sd(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do{t=t.previousSibling}while(t&&!pd(t));return t}function kd(e){var t=e.parentNode;return!(!t||!pd(t))&&t}function xd(t){var n=null==e?void 0:e.location.href;return!!(n&&t&&t.some(e=>n.match(e)))}var Td="(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})",Id=new RegExp("^(?:"+Td+")$"),Ed=new RegExp(Td),Ad="\\d{3}-?\\d{2}-?\\d{4}",Od=new RegExp("^("+Ad+")$"),Md=new RegExp("("+Ad+")");function Rd(e,t){if(void 0===t&&(t=!0),f(e))return!1;if(v(e)){if(e=ud(e),(t?Id:Ed).test((e||"").replace(/[- ]/g,"")))return!1;if((t?Od:Md).test(e))return!1}return!0}function Pd(e){return!!v(e)&&("_ngcontent"===e.substring(0,10)||"_nghost"===e.substring(0,7))}function Ld(e){for(var t=e;t&&t.parentNode&&!gd(t,"body");t=t.parentNode){var n=md(t);if(hd(n,"vt-sensitive")||hd(n,"vt-no-capture"))return!1}if(hd(md(e),"vt-include"))return!0;var i=e.type||"";if(v(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var r=e.name||e.id||"";if(v(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 Ud(e){return!!(gd(e,"input")&&!["button","checkbox","submit","reset","radio"].includes(e.type)||gd(e,"textarea")||"true"===e.getAttribute("contenteditable"))}function Dd(e){if(!Ld(e))return null;if(gd(e,"input")){var t=e,n=(t.type||"text").toLowerCase();if("password"===n||"hidden"===n)return null;if("checkbox"===n||"radio"===n){var i={$el_value:t.checked?"true":"false"},r=function(e){var t=e.closest("label");if(t){var n=ud(t.textContent||"");if(n&&Rd(n))return yd(n)||null}if(e.id)try{var i=null===document||void 0===document?void 0:document.querySelector('label[for="'+e.id+'"]');if(i){var r=ud(i.textContent||"");if(r&&Rd(r))return yd(r)||null}}catch(e){}return null}(t);return r?i.$selected_text=r:t.value&&Rd(t.value)&&(i.$selected_text=t.value),i}var s=t.value;if(s&&Rd(s)){var a=yd(s);if(a)return{$el_value:a}}return null}if(gd(e,"select")){var o=e,l=o.selectedIndex;if(l>=0&&o.options[l]){var c=o.options[l],d={};c.value&&Rd(c.value)&&(d.$el_value=c.value);var u=c.text;if(u&&Rd(u)){var h=yd(u);h&&(d.$selected_text=h)}if(d.$el_value||d.$selected_text)return d}return null}return gd(e,"textarea"),null}function Nd(t,n,i,r,s){if(void 0===i&&(i=void 0),!e)return{capture:!1,reason:"no_window"};if(!t)return{capture:!1,reason:"no_element"};if(gd(t,"html")||!pd(t))return{capture:!1,reason:"html_element"};if((null==i?void 0:i.url_allowlist)&&!xd(i.url_allowlist))return{capture:!1,reason:"url_allowlist_miss"};if((null==i?void 0:i.url_ignorelist)&&xd(i.url_ignorelist))return{capture:!1,reason:"url_ignorelist_hit"};if(null==i?void 0:i.dom_event_allowlist){var a=i.dom_event_allowlist;if(a&&!a.some(e=>n.type===e))return{capture:!1,reason:"dom_event_not_allowed"}}for(var o=!1,l=[t],c=!0,d=t;d.parentNode&&!gd(d,"body");)if(fd(d.parentNode))l.push(d.parentNode.host),d=d.parentNode.host;else{if(!(c=kd(d)))break;if(r||ld.indexOf(c.tagName.toLowerCase())>-1)o=!0;else{var u=e.getComputedStyle(c);u&&"pointer"===u.getPropertyValue("cursor")&&(o=!0)}l.push(c),d=c}if(!function(e,t){var n=null==t?void 0:t.element_allowlist;if(g(n))return!0;var i,r=function(e){if(n.some(t=>e.tagName.toLowerCase()===t))return{v:!0}};for(var s of e)if(i=r(s))return i.v;return!1}(l,i))return{capture:!1,reason:"element_allowlist_miss"};if(!function(e,t){var n=null==t?void 0:t.css_selector_allowlist;if(g(n))return!0;var i,r=function(e){if(n.some(t=>e.matches(t)))return{v:!0}};for(var s of e)if(i=r(s))return i.v;return!1}(l,i))return{capture:!1,reason:"css_selector_allowlist_miss"};if(function(e,t){var n=null==t?void 0:t.css_selector_ignorelist,i=void 0===n?dd:n;if(0===i.length)return!1;for(var r of e)for(var s of i)try{if(r.matches(s))return!0}catch(e){}return!1}(l,i))return{capture:!1,reason:"css_selector_ignorelist_hit"};var h=e.getComputedStyle(t);if(h&&"pointer"===h.getPropertyValue("cursor")&&"click"===n.type)return{capture:!0};var p=t.tagName.toLowerCase();switch(p){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 o?(s||["click"]).indexOf(n.type)>=0?{capture:!0}:{capture:!1,reason:"dom_event_not_allowed"}:(s||["click"]).indexOf(n.type)>=0&&(ld.indexOf(p)>-1||"true"===t.getAttribute("contenteditable"))?{capture:!0}:{capture:!1,reason:"tag_not_capturable"}}}function Bd(e,t){return t.length>e?t.slice(0,e)+"...":t}function Hd(e,t,n,i){var r=e.tagName.toLowerCase(),s={tag_name:r};ld.indexOf(r)>-1&&!n&&(s.$el_text=Bd(1024,"a"===r||"button"===r?Cd(e):bd(e)));var a=md(e);a.length>0&&(s.classes=a.filter(e=>""!==e));for(var o=0;o<e.attributes.length;o++){var l=e.attributes[o];if((!Ud(e)||-1!==["name","id","class","aria-label"].indexOf(l.name))&&(!(null==i?void 0:i.includes(l.name))&&!t&&Rd(l.value)&&!Pd(l.name))){var c=l.value;"class"===l.name&&(c=_d(c).join(" ")),s["attr__"+l.name]=Bd(1024,c)}}for(var d=1,u=1,h=e;h=Sd(h);)d++,h.tagName===e.tagName&&u++;return s.nth_child=d,s.nth_of_type=u,s}function qd(e){if(!Ld(e))return{};for(var t={},n=0;n<e.attributes.length;n++){var i=e.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&&Rd(s)&&(t[r]=s)}}return t}function Fd(e){return e.replace(/"|\\"/g,'\\"')}function jd(e){var t=e.attr__class;return t?_(t)?t:_d(t):void 0}function Wd(e){return function(e){var t=e.map(e=>{var t,n,i="";if(e.tag_name&&(i+=e.tag_name),e.attr_class)for(var r of(e.attr_class.sort(),e.attr_class))i+="."+r.replace(/"/g,"");var s=d({},e.text?{text:e.text}:{},{"nth-child":null!==(t=e.nth_child)&&void 0!==t?t:0,"nth-of-type":null!==(n=e.nth_of_type)&&void 0!==n?n:0},e.href?{href:e.href}:{},e.attr_id?{attr_id:e.attr_id}:{},e.attributes),a={};return Object.entries(s).sort((e,t)=>{var[n]=e,[i]=t;return n.localeCompare(i)}).forEach(e=>{var[t,n]=e;return a[Fd(t.toString())]=Fd(String(n))}),(i+=":")+Object.entries(a).map(e=>{var[t,n]=e;return t+'="'+n+'"'}).join("")});return t.join(";")}(function(e){return e.map(e=>{var t,n,i={text:null===(t=e.$el_text)||void 0===t?void 0:t.slice(0,400),tag_name:e.tag_name,href:null===(n=e.attr__href)||void 0===n?void 0:n.slice(0,2048),attr_class:jd(e),attr_id:e.attr__id,nth_child:e.nth_child,nth_of_type:e.nth_of_type,attributes:{}};return Object.entries(e).filter(e=>{var[t]=e;return 0===t.indexOf("attr__")}).forEach(e=>{var[t,n]=e;return i.attributes[t]=n}),i})}(e))}var $d=[25,50,75,100];function zd(e){var t;if(!e)return null;var n=e.milestones,i=!0===n||"object"==typeof n&&null!==n,r="object"==typeof n&&null!==n&&(null===(t=n.thresholds)||void 0===t?void 0:t.length)?[...n.thresholds].sort((e,t)=>e-t):[...$d],s=!0===e.pageleave;return i||s?{milestones:i,thresholds:r,pageleave:s,scroll_root_selector:e.scroll_root_selector}:null}class Vd{constructor(e){this._options=e,this._maxPctSeen=0,this._firedThresholds=new Set,this._scrollHandler=null,this._scrollTarget=null,this._rafId=null,this._pageviewUnsub=null}start(){this.stop(),this._scrollTarget=function(t){if(!e)return null;if(t){var n=Array.isArray(t)?t:[t];for(var r of n){var s=null==i?void 0:i.querySelector(r);if(s instanceof Element)return s}}return e}(this._options.scroll_root_selector),this._scrollTarget&&(this._scrollHandler=()=>this._scheduleScrollUpdate(),K(this._scrollTarget,"scroll",this._scrollHandler,{passive:!0}),this._onScroll(),this._pageviewUnsub=this._options.onPageview(()=>this.reset()))}stop(){this._pageviewUnsub&&(this._pageviewUnsub(),this._pageviewUnsub=null),null!=this._rafId&&e&&(e.cancelAnimationFrame(this._rafId),this._rafId=null),this._scrollHandler&&this._scrollTarget&&(this._scrollTarget.removeEventListener("scroll",this._scrollHandler,{passive:!0}),this._scrollHandler=null,this._scrollTarget=null)}reset(){this._maxPctSeen=0,this._firedThresholds.clear(),this._onScroll()}getMaxPct(){return this._maxPctSeen}_scheduleScrollUpdate(){e&&null==this._rafId&&(this._rafId=e.requestAnimationFrame(()=>{this._rafId=null,this._onScroll()}))}_onScroll(){if(this._scrollTarget){var t=function(t){var n,r,s,a,o,l;if(!t)return 0;if(t===e){var c=null!==(n=e.scrollY)&&void 0!==n?n:0,d=null!==(r=e.innerHeight)&&void 0!==r?r:0,u=null==i?void 0:i.documentElement,h=null==i?void 0:i.body,p=Math.max(null!==(s=null==u?void 0:u.scrollHeight)&&void 0!==s?s:0,null!==(a=null==h?void 0:h.scrollHeight)&&void 0!==a?a:0,null!==(o=null==u?void 0:u.offsetHeight)&&void 0!==o?o:0,null!==(l=null==h?void 0:h.offsetHeight)&&void 0!==l?l:0)-d;return p<=0?100:Math.round(Math.min(100,c/p*100))}var v=t,g=v.scrollHeight-v.clientHeight;return g<=0?100:Math.round(Math.min(100,v.scrollTop/g*100))}(this._scrollTarget);if(t>this._maxPctSeen&&(this._maxPctSeen=t),this._options.milestones&&this._options.isUrlAllowed())for(var n of this._options.thresholds)this._maxPctSeen>=n&&!this._firedThresholds.has(n)&&(this._firedThresholds.add(n),this._options.capture(ul,{[bl]:n,[wl]:this._maxPctSeen}))}}}function Gd(e,t){return e.indexOf(t)>-1}class Kd{constructor(){this.clicks=[],this.RAGE_CLICK_THRESHOLD_PX=30,this.RAGE_CLICK_TIMEOUT_MS=1e3,this.RAGE_CLICK_CLICK_COUNT=3}isRageClick(e,t,n){if(this.clicks=this.clicks.filter(e=>n-e.timestamp<this.RAGE_CLICK_TIMEOUT_MS),this.clicks.length>0){var i=this.clicks[this.clicks.length-1];Math.sqrt(Math.pow(e-i.x,2)+Math.pow(t-i.y,2))>this.RAGE_CLICK_THRESHOLD_PX&&(this.clicks=[])}return this.clicks.push({x:e,y:t,timestamp:n}),this.clicks.length>=this.RAGE_CLICK_CLICK_COUNT}}function Jd(t,n){for(var i,r,s,a,{e:o,maskAllElementAttributes:l,maskAllText:c,elementAttributeIgnoreList:d,elementsChainAsString:u,captureElementValues:h}=n,p=[t],v=t;v.parentNode&&!gd(v,"body");)fd(v.parentNode)?(p.push(v.parentNode.host),v=v.parentNode.host):(p.push(v.parentNode),v=v.parentNode);var g,f=[],_={},m=!1,y=!1;for(var b of p){var w=Ld(b);if("a"===b.tagName.toLowerCase()){var C=b.getAttribute("href");m=!!(w&&C&&Rd(C))&&C}Gd(md(b),"vt-no-capture")&&(y=!0),f.push(Hd(b,l,c,d));var S=qd(b);Object.assign(_,S)}if(y)return{props:{},explicitNoCapture:y};if(c||("a"===t.tagName.toLowerCase()||"button"===t.tagName.toLowerCase()?f[0].$el_text=Cd(t):f[0].$el_text=bd(t)),"change"===o.type&&h){var k=Dd(t);k&&(k.$el_value&&(f[0].$el_value=k.$el_value),k.$selected_text&&(f[0].$selected_text=k.$selected_text))}if(m){f[0].attr__href=m;var x=null===(i=Ml(m))||void 0===i?void 0:i.host,T=null===(r=null==e?void 0:e.location)||void 0===r?void 0:r.host;x&&T&&x!==T&&(g=m)}var I=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Object.assign({},...t)}({$event_type:o.type,$ce_version:1},u?{}:{$elements:f},{$elements_chain:Wd(f)},(null===(s=f[0])||void 0===s?void 0:s.$el_text)?{$el_text:null===(a=f[0])||void 0===a?void 0:a.$el_text}:{},g&&"click"===o.type?{$external_click_url:g}:{},_);return{props:I}}var Qd=["copy","cut"];class Xd{static extractConfig(e){return{enabled:!1!==e.autocapture}}constructor(e,t){this.name="Autocapture",this._initialized=!1,this._isDisabledServerSide=null,this._userOverride=null,this._elementSelectors=null,this._rageclicks=new Kd,this._elementsChainAsString=!0,this._cachedConfig=null,this._cachedConfigSource=null,this._domHandler=null,this._copyHandler=null,this._copyHandlerAttached=!1,this._scrollDepthTracker=null,this._pageviewUnsubscribe=null,this._instance=e}get _config(){var e=this._instance.getConfig().autocapture;if(e===this._cachedConfigSource&&this._cachedConfig)return this._cachedConfig;this._cachedConfigSource=e;var t=function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)?e:{};return t.url_allowlist&&(t.url_allowlist=t.url_allowlist.map(e=>"string"==typeof e?new RegExp(e):e)),t.url_ignorelist&&(t.url_ignorelist=t.url_ignorelist.map(e=>"string"==typeof e?new RegExp(e):e)),this._cachedConfig=t,t}get isEnabled(){return this._evaluateEnabled().enabled}get isStarted(){return this._initialized}startIfEnabled(){var{enabled:e,reason:t}=this._evaluateEnabled();e?this._initialized?(this._syncCopyHandler(),this._syncScrollDepthHandler()):(this._addDomEventHandlers(),this._initialized=!0,I().info("autocapture","started; listening for click/change/submit events")):this._initialized?(I().info("autocapture","stopping; reason:",null!=t?t:"unknown"),this._removeDomEventHandlers(),this._initialized=!1):(I().debug("autocapture","not started; reason:",null!=t?t:"unknown"),this._teardownScrollDepth())}stop(){this._initialized&&(this._removeDomEventHandlers(),this._initialized=!1,I().info("autocapture","stopped (DOM listeners detached)")),this._teardownScrollDepth()}getMaxScrollDepthPctForPageleave(){var e=zd(this._config.scroll_depth);return(null==e?void 0:e.pageleave)&&this._scrollDepthTracker?this._scrollDepthTracker.getMaxPct():null}onConfigUpdate(e){var t=e;"boolean"==typeof t.elementsChainAsString&&(this._elementsChainAsString=t.elementsChainAsString),void 0!==t.autocapture_opt_out&&(this._isDisabledServerSide=!!t.autocapture_opt_out),this.startIfEnabled()}updateConfig(e){void 0!==e.enabled&&(this._userOverride=e.enabled,e.enabled&&(this._isDisabledServerSide=!1),this.startIfEnabled())}getDiagnostics(){var e,t,n,{enabled:i,reason:r}=this._evaluateEnabled(),s=zd(this._config.scroll_depth);return{isEnabled:i,isStarted:this._initialized,disabledReason:i?null:r,inputs:{configAutocapture:this._instance.getConfig().autocapture,isDisabledServerSide:null!==(e=this._isDisabledServerSide)&&void 0!==e&&e,userOverride:this._userOverride,elementsChainAsString:this._elementsChainAsString,captureCopiedText:!!this._config.capture_copied_text,scrollDepthMilestones:null!==(t=null==s?void 0:s.milestones)&&void 0!==t&&t,scrollDepthPageleave:null!==(n=null==s?void 0:s.pageleave)&&void 0!==n&&n,scrollDepthListenerAttached:null!==this._scrollDepthTracker}}}setElementSelectors(e){this._elementSelectors=e}getElementSelectors(e){var t,n=[];return null===(t=this._elementSelectors)||void 0===t||t.forEach(t=>{var r=null==i?void 0:i.querySelectorAll(t);null==r||r.forEach(i=>{e===i&&n.push(t)})}),n}_evaluateEnabled(){if(!1===this._userOverride)return{enabled:!1,reason:"user_stop_called"};if(this._isDisabledServerSide)return{enabled:!1,reason:"server_opt_out"};if(!0===this._userOverride)return{enabled:!0,reason:null};var e=this._instance.getConfig().autocapture;return!1===e?{enabled:!1,reason:"config_autocapture_false"}:null==e?{enabled:!1,reason:"config_autocapture_undefined"}:{enabled:!0,reason:null}}_addDomEventHandlers(){this._isBrowserSupported()?e&&i&&(this._domHandler=t=>{var n=t||(null==e?void 0:e.event);if(n)try{this._captureEvent(n)}catch(e){I().error("autocapture","capture handler threw",e)}},K(i,"submit",this._domHandler,{capture:!0}),K(i,"change",this._domHandler,{capture:!0}),K(i,"click",this._domHandler,{capture:!0}),this._syncCopyHandler(),this._syncScrollDepthHandler()):I().warn("autocapture","browser unsupported (no querySelectorAll)")}_removeDomEventHandlers(){i&&(this._domHandler&&(i.removeEventListener("submit",this._domHandler,!0),i.removeEventListener("change",this._domHandler,!0),i.removeEventListener("click",this._domHandler,!0),this._domHandler=null),this._copyHandler&&this._copyHandlerAttached&&(i.removeEventListener("copy",this._copyHandler,!0),i.removeEventListener("cut",this._copyHandler,!0),this._copyHandlerAttached=!1,this._copyHandler=null),this._teardownScrollDepth())}_syncScrollDepthHandler(){var t,n=zd(this._config.scroll_depth),i=this.isEnabled&&null!==n&&null!==zd(null==(t=this._config)?void 0:t.scroll_depth);i&&!this._scrollDepthTracker?(this._scrollDepthTracker=new Vd({milestones:n.milestones,pageleave:n.pageleave,thresholds:n.thresholds,scroll_root_selector:n.scroll_root_selector,capture:(e,t)=>this._instance.capture(e,t),isUrlAllowed:()=>{return t=this._config,!(!e||(null==t?void 0:t.url_allowlist)&&!xd(t.url_allowlist)||(null==t?void 0:t.url_ignorelist)&&xd(t.url_ignorelist));var t},onPageview:e=>(this._pageviewUnsubscribe&&this._pageviewUnsubscribe(),this._pageviewUnsubscribe=this._instance.on(U,t=>{(null==t?void 0:t.event)===rl&&e()}),()=>{var e;null===(e=this._pageviewUnsubscribe)||void 0===e||e.call(this),this._pageviewUnsubscribe=null})}),this._scrollDepthTracker.start(),I().info("autocapture","scroll depth tracking started",{milestones:n.milestones,pageleave:n.pageleave})):i||this._teardownScrollDepth()}_teardownScrollDepth(){this._scrollDepthTracker&&(this._scrollDepthTracker.stop(),this._scrollDepthTracker=null,I().info("autocapture","scroll depth tracking stopped")),this._pageviewUnsubscribe&&(this._pageviewUnsubscribe(),this._pageviewUnsubscribe=null)}_syncCopyHandler(){if(i){var t=!!this._config.capture_copied_text;t&&!this._copyHandlerAttached?(this._copyHandler=t=>{var n=t||(null==e?void 0:e.event);if(n)try{this._captureEvent(n,cd)}catch(e){I().error("autocapture","copy handler threw",e)}},K(i,"copy",this._copyHandler,{capture:!0}),K(i,"cut",this._copyHandler,{capture:!0}),this._copyHandlerAttached=!0):!t&&this._copyHandlerAttached&&this._copyHandler&&(i.removeEventListener("copy",this._copyHandler,!0),i.removeEventListener("cut",this._copyHandler,!0),this._copyHandlerAttached=!1,this._copyHandler=null)}}_captureEvent(t,n){var i,r,s,a,o,l,c,d;if(void 0===n&&(n="$autocapture"),this.isEnabled)if(t.isTrusted){var u=function(e){var t;return g(e.target)?e.srcElement||null:(null===(t=e.target)||void 0===t?void 0:t.shadowRoot)?e.composedPath()[0]||null:e.target||null}(t);if(vd(u)&&(u=u.parentNode||null),"$autocapture"===n&&"click"===t.type&&t instanceof MouseEvent)this._instance.getConfig().rageclick&&(null===(i=this._rageclicks)||void 0===i?void 0:i.isRageClick(t.clientX,t.clientY,(new Date).getTime()))&&(I().info("autocapture","$rageclick detected"),this._captureEvent(t,"$rageclick"));var h=n===cd;if(u){var p=Nd(u,t,this._config,h,h?[...Qd]:void 0);if(p.capture){var v=this._instance.getConfig(),{props:f,explicitNoCapture:_}=Jd(u,{e:t,maskAllElementAttributes:null!==(a=v.mask_all_element_attributes)&&void 0!==a&&a,maskAllText:null!==(o=v.mask_all_text)&&void 0!==o&&o,elementAttributeIgnoreList:this._config.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString,captureElementValues:null!==(l=this._config.capture_element_values)&&void 0!==l&&l});if(_)return I().debug("autocapture","skip: vt-no-capture class on element chain",{tag:null===(c=u.tagName)||void 0===c?void 0:c.toLowerCase()}),!1;var m=this.getElementSelectors(u);if(m&&m.length>0&&(f.$element_selectors=m),n===cd){var y=yd(null===(d=null==e?void 0:e.getSelection())||void 0===d?void 0:d.toString()),b=t.type||"clipboard";if(!y)return I().debug("autocapture","skip copy: empty selection"),!1;f.$selected_content=y,f.$copy_type=b}return this._instance.capture(n,f),!0}I().debug("autocapture","skip:",null!==(r=p.reason)&&void 0!==r?r:"unknown",{type:t.type,tag:null===(s=u.tagName)||void 0===s?void 0:s.toLowerCase()})}else I().debug("autocapture","skip: no event target",{type:t.type})}else I().debug("autocapture","skip: synthetic event (isTrusted=false)",{type:t.type})}_isBrowserSupported(){return m(null==i?void 0:i.querySelectorAll)}}var Yd="replay";class Zd extends nd{constructor(e,t){super(e,t||Zd.extractConfig(e.getConfig())),this.name="SessionRecording",this.scriptName="recorder"}static extractConfig(e){var t,n,i,r=e.session_recording||{};return{enabled:null!==(t=r.enabled)&&void 0!==t&&t,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 t,n=this._instance.getConfig(),i=null!==(t=this._config.enabled)&&void 0!==t&&t,r=!n.disable_session_recording;return!!e&&i&&r}get isStarted(){var e;return this._isStarted&&!!(null===(e=this._loaded)||void 0===e?void 0:e.isStarted)}startIfEnabled(){this.startIfEnabledOrStop("recording_initialized")}startIfEnabledOrStop(e){var t;if(!this.isEnabled||!(null===(t=this._loaded)||void 0===t?void 0:t.isStarted)){var n=void 0!==Object.assign&&void 0!==Array.from;this.isEnabled&&n?(this._isStarted=!0,this._ensureLoaded(t=>this._onLoaded(t,e)),I().info(Yd,"starting")):this.stop()}}stop(){A(()=>{var e;null===(e=this._loaded)||void 0===e||e.stop(),this._isStarted=!1})}onConfigUpdate(e){var t;this._config=Zd.extractConfig(e),null===(t=this._loaded)||void 0===t||t.updateConfig(this._config),this.startIfEnabledOrStop("config_updated")}_createLoaded(){var e,t=null===(e=o.__VTiltExtensions__)||void 0===e?void 0:e.initSessionRecording;if(!t)throw new Error("[vTilt:replay] initSessionRecording not available after script load");return t(this._instance,this._config)}_onLoaded(e,t){e.start(t)}get started(){return this.isStarted}get status(){var e;return(null===(e=this._loaded)||void 0===e?void 0:e.status)||"lazy_loading"}get sessionId(){var e;return(null===(e=this._loaded)||void 0===e?void 0:e.sessionId)||""}stopRecording(){this.stop()}log(e,t){var n;void 0===t&&(t="log"),(null===(n=this._loaded)||void 0===n?void 0:n.log)?this._loaded.log(e,t):I().warn(Yd,"log called before recorder was ready")}updateConfig(e){var t;this._config=d({},this._config,e),null===(t=this._loaded)||void 0===t||t.updateConfig(this._config)}}var eu=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(eu||{});eu.MouseMove,eu.MouseInteraction,eu.Scroll,eu.ViewportResize,eu.Input,eu.TouchMove,eu.MediaInteraction,eu.Drag;var tu=Uint8Array,nu=Uint16Array,iu=Int32Array,ru=new tu([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]),su=new tu([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]),au=new tu([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ou=function(e,t){for(var n=new nu(31),i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new iu(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}},lu=ou(ru,2),cu=lu.b,du=lu.r;cu[28]=258,du[258]=28;for(var uu=ou(su,0).r,hu=new nu(32768),pu=0;pu<32768;++pu){var vu=(43690&pu)>>1|(21845&pu)<<1;vu=(61680&(vu=(52428&vu)>>2|(13107&vu)<<2))>>4|(3855&vu)<<4,hu[pu]=((65280&vu)>>8|(255&vu)<<8)>>1}var gu=function(e,t,n){for(var i=e.length,r=0,s=new nu(t);r<i;++r)e[r]&&++s[e[r]-1];var a,o=new nu(t);for(r=1;r<t;++r)o[r]=o[r-1]+s[r-1]<<1;if(n){a=new nu(1<<t);var l=15-t;for(r=0;r<i;++r)if(e[r])for(var c=r<<4|e[r],d=t-e[r],u=o[e[r]-1]++<<d,h=u|(1<<d)-1;u<=h;++u)a[hu[u]>>l]=c}else for(a=new nu(i),r=0;r<i;++r)e[r]&&(a[r]=hu[o[e[r]-1]++]>>15-e[r]);return a},fu=new tu(288);for(pu=0;pu<144;++pu)fu[pu]=8;for(pu=144;pu<256;++pu)fu[pu]=9;for(pu=256;pu<280;++pu)fu[pu]=7;for(pu=280;pu<288;++pu)fu[pu]=8;var _u=new tu(32);for(pu=0;pu<32;++pu)_u[pu]=5;var mu=gu(fu,9,0),yu=gu(_u,5,0),bu=function(e){return(e+7)/8|0},wu=function(e,t,n){return(null==n||n>e.length)&&(n=e.length),new tu(e.subarray(t,n))},Cu=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8},Su=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8,e[i+2]|=n>>16},ku=function(e,t){for(var n=[],i=0;i<e.length;++i)e[i]&&n.push({s:i,f:e[i]});var r=n.length,s=n.slice();if(!r)return{t:Mu,l:0};if(1==r){var a=new tu(n[0].s+1);return a[n[0].s]=1,{t:a,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var o=n[0],l=n[1],c=0,d=1,u=2;for(n[0]={s:-1,f:o.f+l.f,l:o,r:l};d!=r-1;)o=n[n[c].f<n[u].f?c++:u++],l=n[c!=d&&n[c].f<n[u].f?c++:u++],n[d++]={s:-1,f:o.f+l.f,l:o,r:l};var h=s[0].s;for(i=1;i<r;++i)s[i].s>h&&(h=s[i].s);var p=new nu(h+1),v=xu(n[d-1],p,0);if(v>t){i=0;var g=0,f=v-t,_=1<<f;for(s.sort(function(e,t){return p[t.s]-p[e.s]||e.f-t.f});i<r;++i){var m=s[i].s;if(!(p[m]>t))break;g+=_-(1<<v-p[m]),p[m]=t}for(g>>=f;g>0;){var y=s[i].s;p[y]<t?g-=1<<t-p[y]++-1:++i}for(;i>=0&&g;--i){var b=s[i].s;p[b]==t&&(--p[b],++g)}v=t}return{t:new tu(p),l:v}},xu=function(e,t,n){return-1==e.s?Math.max(xu(e.l,t,n+1),xu(e.r,t,n+1)):t[e.s]=n},Tu=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new nu(++t),i=0,r=e[0],s=1,a=function(e){n[i++]=e},o=1;o<=t;++o)if(e[o]==r&&o!=t)++s;else{if(!r&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(r),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(r);s=1,r=e[o]}return{c:n.subarray(0,i),n:t}},Iu=function(e,t){for(var n=0,i=0;i<t.length;++i)n+=e[i]*t[i];return n},Eu=function(e,t,n){var i=n.length,r=bu(t+2);e[r]=255&i,e[r+1]=i>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var s=0;s<i;++s)e[r+s+4]=n[s];return 8*(r+4+i)},Au=function(e,t,n,i,r,s,a,o,l,c,d){Cu(t,d++,n),++r[256];for(var u=ku(r,15),h=u.t,p=u.l,v=ku(s,15),g=v.t,f=v.l,_=Tu(h),m=_.c,y=_.n,b=Tu(g),w=b.c,C=b.n,S=new nu(19),k=0;k<m.length;++k)++S[31&m[k]];for(k=0;k<w.length;++k)++S[31&w[k]];for(var x=ku(S,7),T=x.t,I=x.l,E=19;E>4&&!T[au[E-1]];--E);var A,O,M,R,P=c+5<<3,L=Iu(r,fu)+Iu(s,_u)+a,U=Iu(r,h)+Iu(s,g)+a+14+3*E+Iu(S,T)+2*S[16]+3*S[17]+7*S[18];if(l>=0&&P<=L&&P<=U)return Eu(t,d,e.subarray(l,l+c));if(Cu(t,d,1+(U<L)),d+=2,U<L){A=gu(h,p,0),O=h,M=gu(g,f,0),R=g;var D=gu(T,I,0);Cu(t,d,y-257),Cu(t,d+5,C-1),Cu(t,d+10,E-4),d+=14;for(k=0;k<E;++k)Cu(t,d+3*k,T[au[k]]);d+=3*E;for(var N=[m,w],B=0;B<2;++B){var H=N[B];for(k=0;k<H.length;++k){var q=31&H[k];Cu(t,d,D[q]),d+=T[q],q>15&&(Cu(t,d,H[k]>>5&127),d+=H[k]>>12)}}}else A=mu,O=fu,M=yu,R=_u;for(k=0;k<o;++k){var F=i[k];if(F>255){Su(t,d,A[(q=F>>18&31)+257]),d+=O[q+257],q>7&&(Cu(t,d,F>>23&31),d+=ru[q]);var j=31&F;Su(t,d,M[j]),d+=R[j],j>3&&(Su(t,d,F>>5&8191),d+=su[j])}else Su(t,d,A[F]),d+=O[F]}return Su(t,d,A[256]),d+O[256]},Ou=new iu([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Mu=new tu(0),Ru=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var n=t,i=9;--i;)n=(1&n&&-306674912)^n>>>1;e[t]=n}return e}(),Pu=function(e,t,n,i,r){if(!r&&(r={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),a=new tu(s.length+e.length);a.set(s),a.set(e,s.length),e=a,r.w=s.length}return function(e,t,n,i,r,s){var a=s.z||e.length,o=new tu(i+a+5*(1+Math.ceil(a/7e3))+r),l=o.subarray(i,o.length-r),c=s.l,d=7&(s.r||0);if(t){d&&(l[0]=s.r>>3);for(var u=Ou[t-1],h=u>>13,p=8191&u,v=(1<<n)-1,g=s.p||new nu(32768),f=s.h||new nu(v+1),_=Math.ceil(n/3),m=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<m)&v},b=new iu(25e3),w=new nu(288),C=new nu(32),S=0,k=0,x=s.i||0,T=0,I=s.w||0,E=0;x+2<a;++x){var A=y(x),O=32767&x,M=f[A];if(g[O]=M,f[A]=O,I<=x){var R=a-x;if((S>7e3||T>24576)&&(R>423||!c)){d=Au(e,l,0,b,w,C,k,T,E,x-E,d),T=S=k=0,E=x;for(var P=0;P<286;++P)w[P]=0;for(P=0;P<30;++P)C[P]=0}var L=2,U=0,D=p,N=O-M&32767;if(R>2&&A==y(x-N))for(var B=Math.min(h,R)-1,H=Math.min(32767,x),q=Math.min(258,R);N<=H&&--D&&O!=M;){if(e[x+L]==e[x+L-N]){for(var F=0;F<q&&e[x+F]==e[x+F-N];++F);if(F>L){if(L=F,U=N,F>B)break;var j=Math.min(N,F-2),W=0;for(P=0;P<j;++P){var $=x-N+P&32767,z=$-g[$]&32767;z>W&&(W=z,M=$)}}}N+=(O=M)-(M=g[O])&32767}if(U){b[T++]=268435456|du[L]<<18|uu[U];var V=31&du[L],G=31&uu[U];k+=ru[V]+su[G],++w[257+V],++C[G],I=x+L,++S}else b[T++]=e[x],++w[e[x]]}}for(x=Math.max(x,I);x<a;++x)b[T++]=e[x],++w[e[x]];d=Au(e,l,c,b,w,C,k,T,E,x-E,d),c||(s.r=7&d|l[d/8|0]<<3,d-=7,s.h=f,s.p=g,s.i=x,s.w=I)}else{for(x=s.w||0;x<a+c;x+=65535){var K=x+65535;K>=a&&(l[d/8|0]=c,K=a),d=Eu(l,d+1,e.subarray(x,K))}s.i=a}return wu(o,0,i+bu(d)+r)}(e,null==t.level?6:t.level,null==t.mem?r.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,n,i,r)},Lu=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function Uu(e,t){t||(t={});var n=function(){var e=-1;return{p:function(t){for(var n=e,i=0;i<t.length;++i)n=Ru[255&n^t[i]]^n>>>8;e=n},d:function(){return~e}}}(),i=e.length;n.p(e);var r=Pu(e,t,function(e){return 10+(e.filename?e.filename.length+1:0)}(t),8),s=r.length;return function(e,t){var n=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=t.level<2?4:9==t.level?2:0,e[9]=3,0!=t.mtime&&Lu(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),n){e[3]=8;for(var i=0;i<=n.length;++i)e[i+10]=n.charCodeAt(i)}}(r,t),Lu(r,s-8,n.d()),Lu(r,s-4,i),r}var Du="undefined"!=typeof TextEncoder&&new TextEncoder,Nu="undefined"!=typeof TextDecoder&&new TextDecoder;try{Nu.decode(Mu,{stream:!0})}catch(e){}var Bu="chat";class Hu extends td{constructor(e,t){super(e,t||Hu.extractConfig(e.getConfig())),this.name="Chat",this.scriptName="chat",this._serverConfig=null,this._configFetched=!1,this._loadError=null,this._bubbleDragHandle=null,this._pendingMessages=[],this._pendingCallbacks=[],this._messageCallbacks=[],this._typingCallbacks=[],this._connectionCallbacks=[],this._bubbleExplicitShow=!1,this._unreadPollIntervalId=null,this._onVisibilityChange=()=>{if("visible"===document.visibilityState)return this._fetchUnreadForBubble(),void this._startUnreadPoll();this._stopUnreadPoll()}}static extractConfig(e){var t,n=e.chat||{};return{enabled:n.enabled,autoConfig:null===(t=n.autoConfig)||void 0===t||t,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 e;return!1!==this._config.enabled&&(!0===this._config.enabled||!this._instance.getConfig().disable_chat&&!0===(null===(e=this._serverConfig)||void 0===e?void 0:e.enabled))}startIfEnabled(){I().debug(Bu,"startIfEnabled"),this._startAsync().catch(e=>{I().error(Bu,"error starting:",e)})}stop(){this.destroy(),this._isStarted=!1}onConfigUpdate(e){var t,n;this._config=Hu.extractConfig(e),this._isBubbleDraggable()||this._syncBubbleLayout(),this._loaded&&(null===(n=(t=this._loaded).updateConfig)||void 0===n||n.call(t,this.getMergedConfig()))}_createLoaded(){var t,n,i,r=null===(t=o.__VTiltExtensions__)||void 0===t?void 0:t.initChat;if(!r)throw new Error("[vTilt:chat] initChat not available after script load");var s=this.getMergedConfig(),a=r(this._instance,s);this._bubbleExplicitShow&&a.show(),this._messageCallbacks.forEach(e=>a.onMessage(e)),this._typingCallbacks.forEach(e=>a.onTyping(e)),this._connectionCallbacks.forEach(e=>a.onConnectionChange(e)),null===(n=this._bubbleDragHandle)||void 0===n||n.destroy(),this._bubbleDragHandle=null;var l=null===(i=null==e?void 0:e.document)||void 0===i?void 0:i.getElementById("vtilt-chat-bubble");return l&&!l.closest("#vtilt-chat-container")&&l.remove(),a}_onLoaded(e){this._pendingCallbacks.forEach(e=>e()),this._pendingCallbacks=[],e.isOpen||(this._fetchUnreadForBubble(),this._startUnreadPoll()),I().info(Bu,"loaded and ready")}_startAsync(){var e=this;return c(function*(){var t,n;try{if(!1===e._config.enabled)return void I().info(Bu,"disabled by code config");if(e._instance.getConfig().disable_chat)return void I().info(Bu,"disabled by disable_chat config");if(!1!==e._config.autoConfig&&(yield e._fetchServerSettings()),!e.isEnabled)return void I().info(Bu,"not enabled (check dashboard settings)");I().debug(Bu,"startIfEnabled enabled"),e._isStarted=!0,!0===e._config.preload&&e._schedulePreload();var i=e.getMergedConfig();(null===(t=e._serverConfig)||void 0===t?void 0:t.enabled)&&!1!==(null===(n=i.bubble)||void 0===n?void 0:n.visible)&&e._showBubble(),I().info(Bu,"ready (lazy-load on demand)")}finally{e._markApiReady()}})()}get isOpen(){var e,t;return null!==(t=null===(e=this._loaded)||void 0===e?void 0:e.isOpen)&&void 0!==t&&t}get isConnected(){var e,t;return null!==(t=null===(e=this._loaded)||void 0===e?void 0:e.isConnected)&&void 0!==t&&t}get isLoading(){var e,t;return this._isLoading||null!==(t=null===(e=this._loaded)||void 0===e?void 0:e.isLoading)&&void 0!==t&&t}get unreadCount(){var e,t;return null!==(t=null===(e=this._loaded)||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0}get channel(){var e,t;return null!==(t=null===(e=this._loaded)||void 0===e?void 0:e.channel)&&void 0!==t?t:null}get channels(){var e,t;return null!==(t=null===(e=this._loaded)||void 0===e?void 0:e.channels)&&void 0!==t?t:[]}get currentView(){var e,t;return null!==(t=null===(e=this._loaded)||void 0===e?void 0:e.currentView)&&void 0!==t?t:"list"}open(){this._deferCall(()=>{this._stopUnreadPoll(),this._lazyLoadAndThen(()=>{var e;return null===(e=this._loaded)||void 0===e?void 0:e.open()})})}close(){this._deferCall(()=>{this._loaded?(this._loaded.close(),this._fetchUnreadForBubble(),this._startUnreadPoll()):this._lazyLoadAndThen(()=>{var e;null===(e=this._loaded)||void 0===e||e.close(),this._fetchUnreadForBubble(),this._startUnreadPoll()})})}toggle(){this._deferCall(()=>{this._loaded?this._loaded.toggle():this.open()})}show(){this._deferCall(()=>{this._bubbleExplicitShow=!0,this._loaded?this._loaded.show():this._isStarted&&this._showBubble()})}hide(){this._deferCall(()=>{var t;if(this._bubbleExplicitShow=!1,this._loaded)this._loaded.hide();else{var n=null===(t=null==e?void 0:e.document)||void 0===t?void 0:t.getElementById("vtilt-chat-bubble");n&&(n.style.display="none")}})}getChannels(){this._deferCall(()=>{this._lazyLoadAndThen(()=>{var e;return null===(e=this._loaded)||void 0===e?void 0:e.getChannels()})})}selectChannel(e){this._deferCall(()=>{this._lazyLoadAndThen(()=>{var t;return null===(t=this._loaded)||void 0===t?void 0:t.selectChannel(e)})})}createChannel(){this._deferCall(()=>{this._lazyLoadAndThen(()=>{var e;return null===(e=this._loaded)||void 0===e?void 0:e.createChannel()})})}goToChannelList(){this._deferCall(()=>{this._loaded?this._loaded.goToChannelList():this._lazyLoadAndThen(()=>{var e;return null===(e=this._loaded)||void 0===e?void 0:e.goToChannelList()})})}sendMessage(e,t){return this._loaded?this._loaded.sendMessage(e,t):new Promise((n,i)=>{this._deferCall(()=>{this._loaded?this._loaded.sendMessage(e,t).then(n).catch(i):(this._pendingMessages.push({content:e,options:t,resolve:n,reject:i}),this._lazyLoadAndThen(()=>{var e,t=this._pendingMessages;for(var n of(this._pendingMessages=[],t))null===(e=this._loaded)||void 0===e||e.sendMessage(n.content,n.options).then(n.resolve).catch(n.reject)}))})})}markAsRead(){this._deferCall(()=>{this._loaded?this._loaded.markAsRead():this._lazyLoadAndThen(()=>{var e;return null===(e=this._loaded)||void 0===e?void 0:e.markAsRead()})})}registerWidget(e){this._deferCall(()=>{var t,n;this._loaded?null===(n=(t=this._loaded).registerWidget)||void 0===n||n.call(t,e):this._lazyLoadAndThen(()=>{var t,n;null===(n=null===(t=this._loaded)||void 0===t?void 0:t.registerWidget)||void 0===n||n.call(t,e)})})}onMessage(e){return this._messageCallbacks.push(e),this._loaded?this._loaded.onMessage(e):()=>{var t=this._messageCallbacks.indexOf(e);t>-1&&this._messageCallbacks.splice(t,1)}}onTyping(e){return this._typingCallbacks.push(e),this._loaded?this._loaded.onTyping(e):()=>{var t=this._typingCallbacks.indexOf(e);t>-1&&this._typingCallbacks.splice(t,1)}}onConnectionChange(e){return this._connectionCallbacks.push(e),this._loaded?this._loaded.onConnectionChange(e):()=>{var t=this._connectionCallbacks.indexOf(e);t>-1&&this._connectionCallbacks.splice(t,1)}}_isBubbleDraggable(){var e;return!0===(null===(e=this.getMergedConfig().bubble)||void 0===e?void 0:e.draggable)}getMergedConfig(){var e,t,n,i,r,s,a,o,l,c,d,u,h,p,v,g,f,_,m,y,b,w,C,S,k,x=this._serverConfig,T=this._config;return{enabled:null!==(t=null!==(e=T.enabled)&&void 0!==e?e:null==x?void 0:x.enabled)&&void 0!==t&&t,autoConfig:null===(n=T.autoConfig)||void 0===n||n,position:null!==(r=null!==(i=T.position)&&void 0!==i?i:null==x?void 0:x.position)&&void 0!==r?r:"bottom-right",greeting:null!==(s=T.greeting)&&void 0!==s?s:null==x?void 0:x.greeting,color:null!==(o=null!==(a=T.color)&&void 0!==a?a:null==x?void 0:x.color)&&void 0!==o?o:"#6366f1",aiMode:null===(c=null!==(l=T.aiMode)&&void 0!==l?l:null==x?void 0:x.ai_enabled)||void 0===c||c,aiGreeting:null!==(d=T.aiGreeting)&&void 0!==d?d:null==x?void 0:x.ai_greeting,preload:null!==(u=T.preload)&&void 0!==u&&u,theme:null!==(h=T.theme)&&void 0!==h?h:{primaryColor:null!==(v=null!==(p=T.color)&&void 0!==p?p:null==x?void 0:x.color)&&void 0!==v?v:"#6366f1"},offlineMessage:null!==(g=T.offlineMessage)&&void 0!==g?g:null==x?void 0:x.offline_message,collectEmailOffline:null===(_=null!==(f=T.collectEmailOffline)&&void 0!==f?f:null==x?void 0:x.collect_email_offline)||void 0===_||_,bubble:{draggable:null!==(b=null!==(y=null===(m=T.bubble)||void 0===m?void 0:m.draggable)&&void 0!==y?y:null==x?void 0:x.bubble_draggable)&&void 0!==b&&b,visible:null===(S=null!==(C=null===(w=T.bubble)||void 0===w?void 0:w.visible)&&void 0!==C?C:null==x?void 0:x.bubble_visible)||void 0===S||S,offset:null===(k=T.bubble)||void 0===k?void 0:k.offset}}}_syncBubbleLayout(){var e,t,n=this.getMergedConfig(),i=null!==(e=n.position)&&void 0!==e?e:"bottom-right",r=Sn(null===(t=n.bubble)||void 0===t?void 0:t.offset),s=document.getElementById("vtilt-chat-bubble");s&&kn(s,i,r)}destroy(){A(()=>{var t,n,i;this._stopUnreadPoll(),document.removeEventListener("visibilitychange",this._onVisibilityChange),null===(t=this._loaded)||void 0===t||t.destroy(),this._loaded=void 0,this._bubbleExplicitShow=!1,this._pendingMessages=[],this._pendingCallbacks=[],this._messageCallbacks=[],this._typingCallbacks=[],this._connectionCallbacks=[],this._resetDeferral(),null===(n=this._bubbleDragHandle)||void 0===n||n.destroy(),this._bubbleDragHandle=null;var r=null===(i=null==e?void 0:e.document)||void 0===i?void 0:i.getElementById("vtilt-chat-bubble");r&&r.remove()})}_fetchServerSettings(){var e=this;return c(function*(){if(!e._configFetched){var t=e._instance.getConfig();if(!t.token)return I().warn(Bu,"cannot fetch settings: missing token"),void(e._configFetched=!0);try{var n=h(t,"/api/chat/settings"),i=yield fetch(n,{headers:p(t)});if(!i.ok)return I().warn(Bu,"failed to fetch settings: "+i.status),void(e._configFetched=!0);e._serverConfig=yield i.json(),e._configFetched=!0,I().info(Bu,"loaded settings from dashboard")}catch(t){I().warn(Bu,"error fetching settings:",t),e._configFetched=!0}}})()}_fetchUnreadForBubble(){var e=this;return c(function*(){var t,n,i,r,s,a,o=e._instance.getConfig(),l=o.token,c=null!==(i=null===(n=(t=e._instance).getDistinctId)||void 0===n?void 0:n.call(t))&&void 0!==i?i:"";if(I().debug("chat","fetchUnread","distinctId",c?c.slice(0,12)+"...":"empty"),l&&c)try{var d=h(o,"/api/chat/widget/unread"),u=d.includes("?")?"&":"?",v=""+d+u+"distinct_id="+encodeURIComponent(c),g=yield fetch(v,{headers:p(o)});if(!g.ok)return;var f=yield g.json(),_=Number(null!==(r=f.unread_count)&&void 0!==r?r:0);null===(a=null===(s=e._loaded)||void 0===s?void 0:s.applyPolledUnreadCount)||void 0===a||a.call(s,_);var m=document.getElementById("vtilt-chat-bubble");if(!m)return;var y=m.querySelector(".vtilt-chat-bubble-badge");if(!y)return;_>0?(y.style.display="flex",y.textContent=_>99?"99+":String(_)):y.style.display="none"}catch(e){}else{var b=l?"missing distinctId":"missing token";I().debug("chat","fetchUnread skip","reason",b)}})()}_showBubble(){var t,n,i,r;if(null==e?void 0:e.document){var s=document.getElementById("vtilt-chat-bubble");if(s)return s.style.display="flex",void this._syncBubbleLayout();var a=this.getMergedConfig(),o=null!==(t=a.position)&&void 0!==t?t:"bottom-right",l=Sn(null===(n=a.bubble)||void 0===n?void 0:n.offset),c=a.color||"#6366f1",d=document.createElement("div");d.id="vtilt-chat-bubble",d.setAttribute("style",("\n position: fixed;\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background: "+c+";\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()),kn(d,o,l),d.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 u=!0===(null===(i=a.bubble)||void 0===i?void 0:i.draggable);u||(d.addEventListener("mouseenter",()=>{d.style.transform="scale(1.05)",d.style.boxShadow="0 6px 16px rgba(0, 0, 0, 0.2)"}),d.addEventListener("mouseleave",()=>{d.style.transform="scale(1)",d.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.15)"})),d.addEventListener("click",()=>{this.open()}),document.body.appendChild(d),u&&(null===(r=this._bubbleDragHandle)||void 0===r||r.destroy(),this._bubbleDragHandle=An(d)),this._fetchUnreadForBubble(),this._startUnreadPoll(),document.addEventListener("visibilitychange",this._onVisibilityChange)}}_shouldPollUnread(){return"undefined"!=typeof document&&("visible"===document.visibilityState&&(!!document.getElementById("vtilt-chat-bubble")||!(!this._loaded||this._loaded.isOpen)))}_startUnreadPoll(){this._shouldPollUnread()&&null===this._unreadPollIntervalId&&(this._unreadPollIntervalId=setInterval(()=>{this._fetchUnreadForBubble()},3e4))}_stopUnreadPoll(){null!==this._unreadPollIntervalId&&(clearInterval(this._unreadPollIntervalId),this._unreadPollIntervalId=null)}_schedulePreload(){"undefined"!=typeof requestIdleCallback?requestIdleCallback(()=>this._ensureLoaded(()=>{}),{timeout:5e3}):setTimeout(()=>this._ensureLoaded(()=>{}),3e3)}_lazyLoadAndThen(e){this._loaded?e():(this._pendingCallbacks.push(e),this._ensureLoaded(e=>this._onLoaded(e)))}}function qu(e,t){e("js",new Date);var{tagIds:n,configParams:i,sendPageView:r,debugMode:s,conversionLinker:a,linkerDomains:o}=t,l=d({},i||{});for(var c of(!1===r&&(l.send_page_view=!1),s&&(l.debug_mode=!0),!1===a&&(l.conversion_linker=!1),o&&o.length>0&&(l.linker={domains:o,decorate_forms:!0}),n))c&&e("config",c,l)}function Fu(t,n){var i,r=(t.tagIds||[]).filter(e=>!!e);if(0===r.length)return null;var s,a,o,l=null!==(i=t.proxyMode)&&void 0!==i?i:"proxied";if("direct"===l)s=Wu,a=Wu,o="";else{var c=function(t){var n,i=void 0!==e&&(null===(n=null==e?void 0:e.location)||void 0===n?void 0:n.origin)?e.location.origin:"";if(!t)return i?{base:i,absoluteBase:i}:null;var r=t.replace(/\/+$/g,"");if(!r)return i?{base:i,absoluteBase:i}:null;try{var s=new URL(r),a=s.pathname.replace(/\/$/,""),o=""+s.origin+a;return{base:o,absoluteBase:o}}catch(e){}if(r.startsWith("/"))return{base:r,absoluteBase:i?""+i+r:r};return i?{base:i,absoluteBase:i}:null}(n);if(!c)return null;s=c.base,a=c.absoluteBase,o=ju}var d={};if("direct"!==l){var u=function(e){if(!e)return"";var t=e.startsWith("/")?e:"/"+e;return t.replace(/\/$/,"")}(o);d.transport_url=""+a.replace(/\/$/,"")+u}return{origin:s,gatewayPath:o,primaryTagId:r.find(e=>e.startsWith("G-"))||r[0]||"",tagIds:r,configParams:d,sendPageView:!1!==t.capturePageview,debugMode:!!t.debugMode,conversionLinker:!1!==t.conversionLinker,linkerDomains:t.linkerDomains}}var ju="/gt",Wu="https://www.googletagmanager.com";function $u(e,t){var n=!0===e.advertising,i={ad_storage:n?"granted":"denied",ad_user_data:n?"granted":"denied",ad_personalization:n?"granted":"denied",analytics_storage:!0===e.analytics?"granted":"denied"};if(!t)return i;var r=d({},i);return Object.keys(i).forEach(n=>{var i=t[n];void 0!==i&&(r[n]=function(e,t){return"granted"===t?"granted":"denied"===t?"denied":"follow_advertising"===t?!0===e.advertising?"granted":"denied":"follow_analytics"===t&&!0===e.analytics?"granted":"denied"}(e,i))}),r}function zu(e){if(null==e)return null;var t=String(e).trim().toLowerCase();return t||null}function Vu(e,t){if(e&&t){var n=t.split("."),i=e;for(var r of n){if(null==i||"object"!=typeof i)return;i=i[r]}return i}}function Gu(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){var t=Number(e);if(Number.isFinite(t))return t}}function Ku(e){if(null!=e)return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function Ju(e){var{mapping:t,payload:n}=e,i={send_to:t.send_to},r=t.value_param_path||"value",s=t.currency_param_path||"currency",a=Gu(Vu(n,r));void 0!==a&&(i.value=a);var o=Ku(Vu(n,s))||t.default_currency||void 0;if(o&&(i.currency=o),!1!==t.send_transaction_id){var l=Ku(Vu(n,t.transaction_id_param_path||"transaction_id"));l&&(i.transaction_id=l)}return{send_to:t.send_to,params:i}}var Qu=[{source:"$pageview",destination:"page_view",buildParams:e=>{var t,n={},i=Ku(e.$current_url);i&&(n.page_location=i);var r=Ku(e.$pathname);r&&(n.page_path=r);var s=null!==(t=Ku(e.title))&&void 0!==t?t:Ku(e.$title);s&&(n.page_title=s);var a=Ku(e.$referrer);return a&&(n.page_referrer=a),n}},{source:"$pageleave",destination:"user_engagement",buildParams:e=>{var t,n,i={},r=Gu(null!==(n=null!==(t=e.$dwell_time_ms)&&void 0!==t?t:e.engagement_time_msec)&&void 0!==n?n:e.$time_on_page_ms);return void 0!==r&&(i.engagement_time_msec=Math.round(r)),i}}];function Xu(e,t,n){var i=t.split(".").filter(Boolean);if(0!==i.length)if(1!==i.length){for(var r=e,s=0;s<i.length-1;s++){var a=i[s],o=i[s+1];if(null==r||"object"!=typeof r||Array.isArray(r))return;var l=r;if(/^\d+$/.test(o)){var c=Array.isArray(l[a])?l[a]:[];Array.isArray(l[a])||(l[a]=c);for(var d=parseInt(o,10);c.length<=d;)c.push({});if(s+1===i.length-1)return void(c[d]=n);var u=c[d];u&&"object"==typeof u&&!Array.isArray(u)||(u={},c[d]=u),r=u,s++}else{var h=l[a];h&&"object"==typeof h&&!Array.isArray(h)||(h={},l[a]=h),r=h}}var p=i[i.length-1];r&&"object"==typeof r&&!Array.isArray(r)&&(r[p]=n)}else e[i[0]]=n}var Yu=new Set(["client_id","user_id","first_visit","session_start"]);function Zu(e,t,n,i){if(!function(e,t){return!(t&&(Array.isArray(t.exclude)&&t.exclude.includes(e)||Array.isArray(t.include)&&t.include.length>0&&!t.include.includes(e)))}(t,i.eventFilter))return{fired:!1};var r=(i.eventMappings||[]).find(e=>(null==e?void 0:e.source)===t);if(r&&r.destination){var{name:s,params:a}=function(e,t){var n={},i=Array.isArray(e.param_mappings)?e.param_mappings:[];for(var r of i){var s=null==r?void 0:r.source,a=null==r?void 0:r.destination;if(s&&a){var o=Vu(t,s);void 0!==o&&(a.includes(".")?Xu(n,a,o):n[a]=o)}}return{name:e.destination,params:n}}(r,n);return e("event",s,a),{fired:!0,eventName:s,params:a,source:"mapping"}}if(!1===i.autoForward)return{fired:!1};var o=Qu.find(e=>e.source===t);if(o){var l=o.buildParams(n);return e("event",o.destination,l),{fired:!0,eventName:o.destination,params:l,source:"preset"}}if(t.startsWith("$"))return{fired:!1};var c=function(e){var t={};for(var[n,i]of Object.entries(e))n.startsWith("$")||Yu.has(n)||void 0!==i&&(t[n]=i);return t}(n);return e("event",t,c),{fired:!0,eventName:t,params:c,source:"auto"}}function eh(){var e=null,t=[],n=[];return{call:function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];if((e=>{n.push(e),n.length>50&&n.shift()})(r),e)try{e(...r)}catch(e){}else t.push(r)},flush(n){for(e=n;t.length;){var i=t.shift();try{n(...i)}catch(e){}}},getRecentCalls:()=>n.slice()}}function th(e){return nh.apply(this,arguments)}function nh(){return nh=c(function*(e){try{var t="undefined"!=typeof crypto&&crypto.subtle?crypto.subtle:null;if(!t)return null;var n=(new TextEncoder).encode(e),i=yield t.digest("SHA-256",n),r=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("");return r}catch(e){return null}}),nh.apply(this,arguments)}function ih(){return(ih=c(function*(e){var t={},n=function(e){if(!e)return null;var t=String(e).trim().toLowerCase();if(!t)return null;if(!t.includes("@"))return null;var[n,i]=t.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}(e.email),i=function(e){if(!e)return null;var t=String(e).trim();if(!t)return null;if(t.startsWith("+")){var n=t.slice(1).replace(/\D/g,"");return n?"+"+n:null}return null}(e.phone),r=zu(e.first_name),s=zu(e.last_name),a=zu(e.street),o=zu(e.city),l=zu(e.region),c=function(e){if(!e)return null;var t=String(e).trim().toUpperCase().replace(/\s+/g,"");return t||null}(e.postal_code),d=zu(e.country);if(n){var u=yield th(n);u&&(t.sha256_email_address=u)}if(i){var h=yield th(i);h&&(t.sha256_phone_number=h)}var p={};if(r){var v=yield th(r);v&&(p.sha256_first_name=v)}if(s){var g=yield th(s);g&&(p.sha256_last_name=g)}if(a){var f=yield th(a);f&&(p.sha256_street=f)}return o&&(p.city=o),l&&(p.region=l),c&&(p.postal_code=c),d&&(p.country=d),Object.keys(p).length>0&&(t.address=p),0===Object.keys(t).length?null:t})).apply(this,arguments)}class rh{constructor(e){void 0===e&&(e=Number.POSITIVE_INFINITY),this._maxItems=e,this._items=[]}get length(){return this._items.length}enqueue(e){return!(this._items.length>=this._maxItems)&&(this._items.push(e),!0)}takeAll(){if(0===this._items.length)return[];var e=this._items;return this._items=[],e}clear(){this._items=[]}}var sh="google-tag";class ah{constructor(e,t){this.name="GoogleTagGateway",this._isStarted=!1,this._scriptInjected=!1,this._scriptLoaded=!1,this._consentDefaultsPushed=!1,this._gtag=null,this._loaderOptions=null,this._unsubscribeCaptured=null,this._unsubscribeConsent=null,this._deliveryLog=[],this._maxDeliveryLog=100,this._pendingCaptures=new rh(100),this._instance=e,this._config=t||ah.extractConfig(e.getConfig()),this._publicApi=eh(),this._subscribeCaptured()}static extractConfig(e){if(e.disable_google_tag)return{enabled:!1};var t=e.google_tag;return t?{enabled:(t.tagIds||[]).some(e=>!!e),remote:t}:{enabled:!1}}get isEnabled(){return!1!==this._config.enabled&&!!this._config.remote}get isStarted(){return this._isStarted}get gtag(){return this._publicApi.call}get deliveryLog(){return this._deliveryLog.slice()}startIfEnabled(){this._isStarted||this.isEnabled&&this._instance.getConfig().__remote_config_loaded&&this._start()}stop(){var e;this._isStarted&&(null===(e=this._unsubscribeConsent)||void 0===e||e.call(this),this._unsubscribeConsent=null,this._isStarted=!1)}onConfigUpdate(e){var t=ah.extractConfig(e),n=this.isEnabled;this._config=t;var i=!0===e.__remote_config_loaded;if(n&&!this.isEnabled)this.stop();else if(this._isStarted&&t.remote&&this._loaderOptions){var r=Fu(t.remote,this._instance.getConfig().api_host);r&&(this._loaderOptions=r,qu(this._gtag,r))}i&&!this.isEnabled&&this._pendingCaptures.clear(),i&&this.isEnabled&&!this._isStarted&&this.startIfEnabled()}setUserData(e){var t=this;return c(function*(){var n=t._config.remote;if(n&&n.enhancedConversions){var i=yield function(e){return ih.apply(this,arguments)}(e);i&&t._publicApi.call("set","user_data",i)}})()}getRecentPublicCalls(){return this._publicApi.getRecentCalls()}_start(){var t=this._config.remote;if(t){var n=Fu(t,this._instance.getConfig().api_host);if(n){this._loaderOptions=n;var{gtag:i}=function(){var e,t,n=o,i=null!==(e=(t=n).dataLayer)&&void 0!==e?e:t.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._gtag=i,this._publicApi.flush(i),this._pushConsentDefaultsOnce(),qu(i,n),this._scriptInjected||(this._scriptInjected=!0,function(t,n,i){var r=null==e?void 0:e.document;if(!r)return null;var{origin:s,gatewayPath:a,primaryTagId:o}=t;if(!s||!o)return null;var l=""+s.replace(/\/$/,"")+(a?a.startsWith("/")?a.replace(/\/$/,""):"/"+a.replace(/\/$/,""):"")+"/gtag/js?id="+encodeURIComponent(o)+"&l=dataLayer",c=r.querySelector('script[data-vtilt-gtag-loader="'+o+'"]');if(c)return c;var d=r.createElement("script");d.async=!0,d.src=l,d.setAttribute("data-vtilt-gtag-loader",o),d.onload=()=>null==n?void 0:n(),d.onerror=()=>{var e=new Error("[GoogleTagGateway] failed to load "+l);null==i||i(e)},(r.head||r.body||r.documentElement).appendChild(d)}(n,()=>{this._scriptLoaded=!0},e=>{I().warn(sh,e.message)})),this._subscribeConsent(),this._isStarted=!0,this._drainPending()}else I().warn(sh,"skipped — missing tag_ids or resolvable origin")}}_drainPending(){for(var e of this._pendingCaptures.takeAll())this._handleCaptured(e.event,e.payload)}_pushConsentDefaultsOnce(){var e;if(!this._consentDefaultsPushed&&this._gtag){var t=A(()=>this._instance.consentManager.getConsent());!function(e,t,n){e("consent","default",d({},$u(t,n),{wait_for_update:500}))}(this._gtag,t||{},null===(e=this._config.remote)||void 0===e?void 0:e.consentOverride),this._consentDefaultsPushed=!0}}_subscribeCaptured(){if(!this._unsubscribeCaptured){this._unsubscribeCaptured=this._instance._emitter.on(U,e=>{var t=e;t&&"string"==typeof t.event&&this._handleCaptured(t.event,t.payload||{})})}}_handleCaptured(e,t){var n=this._instance.getConfig();if(!n.disable_google_tag)if(n.__remote_config_loaded){if(this.isEnabled&&(this._isStarted||this.startIfEnabled(),this._gtag&&this._config.remote&&this._isStarted)){var i=this._config.remote,r=i.tagIds||[],s=Zu(this._gtag,e,t,i);if(s.fired&&s.eventName&&this._record({ts:Date.now(),tag_ids:r,event_name:e,send_to:"ga4:"+s.eventName,status:"fired",reason:s.source}),!1!==i.sendAdsConversions){var a=function(e,t,n,i){var r=(i.conversions||[]).filter(e=>e.event_name===t);if(0===r.length)return[];var s=[];for(var a of r){var o=Ju({mapping:a,payload:n});e("event","conversion",o.params),s.push(o)}return s}(this._gtag,e,t,i);for(var o of a)this._record({ts:Date.now(),tag_ids:r,event_name:e,send_to:o.send_to,status:"fired"})}}}else this._pendingCaptures.enqueue({event:e,payload:t})}_subscribeConsent(){if(!this._unsubscribeConsent){this._unsubscribeConsent=this._instance._emitter.on(L,e=>{var t;if(this._gtag){var n,i,r,s=e;n=this._gtag,i=s.consent||{},r=null===(t=this._config.remote)||void 0===t?void 0:t.consentOverride,n("consent","update",$u(i,r))}})}}_record(e){this._deliveryLog.push(e),this._deliveryLog.length>this._maxDeliveryLog&&this._deliveryLog.shift()}}var oh="vtd-overlay";class lh{constructor(e,t){this.name="VtdOverlay",this._isStarted=!1,this._destinationUrl=null,this._originalUrl=null,this._isLoading=!0,this._container=null,this._iframe=null,this._loadingEl=null,this._instance=e,this._config=t||lh.extractConfig(e.getConfig())}static extractConfig(e){return{enabled:!1!==e.vtd_overlay}}get isEnabled(){return!1!==this._config.enabled}get isStarted(){return this._isStarted}startIfEnabled(){}stop(){this._isStarted&&A(()=>{this._destroyOverlay(),this._isStarted=!1})}onConfigUpdate(e){this._config=lh.extractConfig(e),!this.isEnabled&&this._isStarted&&this.stop()}setDestinationUrl(t){var n;if(this.isEnabled)if(null==t?void 0:t.trim()){var i=t;try{i=decodeURIComponent(t)}catch(e){i=t}if(this._isValidUrl(i)){var r=this._toEmbedUrl(i);this._originalUrl=i,this._destinationUrl=r,this._isLoading=!0,this._showOverlay(),this._isStarted=!0,this._instance.capture("$vtd_view",{$vtd_url:i,$vtd_embed_url:r!==i?r:void 0,$current_url:null===(n=null==e?void 0:e.location)||void 0===n?void 0:n.href})}else I().warn(oh,"invalid URL: "+i)}else I().warn(oh,"empty URL provided");else I().warn(oh,"feature is disabled")}getDestinationUrl(){return this._destinationUrl}close(){this._instance.capture("$vtd_close",{$vtd_url:this._originalUrl}),this._container?(this._container.classList.add("vtilt-vtd-closing"),setTimeout(()=>{this._destroyOverlay(),this._isStarted=!1,this._destinationUrl=null,this._originalUrl=null},200)):(this._destroyOverlay(),this._isStarted=!1,this._destinationUrl=null,this._originalUrl=null)}_isValidUrl(e){try{var t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch(e){return!1}}_toEmbedUrl(e){try{var t=new URL(e),n=t.hostname.toLowerCase();if("youtube.com"===n||"www.youtube.com"===n||"m.youtube.com"===n){var i=t.searchParams.get("v");if(i){var r=t.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 a=t.pathname.slice(1);if(a){var o=t.searchParams.get("t"),l="https://www.youtube.com/embed/"+a+"?autoplay=1";return o&&(l+="&start="+o.replace("s","")),l}}if("vimeo.com"===n||"www.vimeo.com"===n){var c=t.pathname.match(/^\/(\d+)/);if(c)return"https://player.vimeo.com/video/"+c[1]+"?autoplay=1"}if("loom.com"===n||"www.loom.com"===n){var d=t.pathname.match(/^\/share\/([a-zA-Z0-9]+)/);if(d)return"https://www.loom.com/embed/"+d[1]+"?autoplay=1"}if(n.endsWith("wistia.com")){var u=t.pathname.match(/^\/medias\/([a-zA-Z0-9]+)/);if(u)return"https://fast.wistia.net/embed/iframe/"+u[1]+"?autoplay=1"}if("dailymotion.com"===n||"www.dailymotion.com"===n){var h=t.pathname.match(/^\/video\/([a-zA-Z0-9]+)/);if(h)return"https://www.dailymotion.com/embed/video/"+h[1]+"?autoplay=1"}if("open.spotify.com"===n){var p=t.pathname.match(/^\/(track|album|playlist|episode|show)\/([a-zA-Z0-9]+)/);if(p)return"https://open.spotify.com/embed/"+p[1]+"/"+p[2]}return"drive.google.com"===n&&t.pathname.includes("/view")?e.replace("/view","/preview"):e}catch(t){return e}}_getHostname(e){try{return new URL(e).hostname}catch(t){return e}}_getFaviconUrl(e){try{return"https://www.google.com/s2/favicons?domain="+new URL(e).hostname+"&sz=32"}catch(e){return""}}_showOverlay(){if(i&&this._destinationUrl){this._destroyOverlay(),this._container=i.createElement("div"),this._container.id="vtilt-vtd-overlay",this._container.className="vtilt-vtd-opening",this._container.setAttribute("style",this._getBackdropStyles());var e=i.createElement("div");e.className="vtilt-vtd-modal",e.setAttribute("style",this._getModalStyles());var t=i.createElement("div");t.className="vtilt-vtd-header",t.setAttribute("style",this._getHeaderStyles()),t.innerHTML=this._getHeaderHTML(),e.appendChild(t);var n=i.createElement("div");n.className="vtilt-vtd-iframe-wrapper",n.setAttribute("style",this._getIframeWrapperStyles()),this._loadingEl=i.createElement("div"),this._loadingEl.className="vtilt-vtd-loading",this._loadingEl.setAttribute("style",this._getLoadingStyles()),this._loadingEl.innerHTML=this._getLoadingHTML(),n.appendChild(this._loadingEl),this._iframe=i.createElement("iframe"),this._iframe.id="vtilt-vtd-iframe",this._iframe.className="vtilt-vtd-iframe",this._iframe.setAttribute("style",this._getIframeStyles()),this._iframe.setAttribute("frameborder","0"),this._iframe.setAttribute("allowfullscreen","true"),this._iframe.setAttribute("allow","accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share");var r=()=>{this._isLoading=!1,this._loadingEl&&(this._loadingEl.style.opacity="0",setTimeout(()=>{var e;(null===(e=this._loadingEl)||void 0===e?void 0:e.parentNode)&&(this._loadingEl.style.display="none")},300)),this._iframe&&(this._iframe.style.opacity="1")};this._iframe.onload=r,this._iframe.onerror=r,setTimeout(()=>{this._isLoading&&r()},5e3),n.appendChild(this._iframe),this._iframe.src=this._destinationUrl,e.appendChild(n),this._container.appendChild(e);var s=i.createElement("style");s.id="vtilt-vtd-styles",s.textContent=this._getGlobalStyles(),i.head.appendChild(s),i.body.appendChild(this._container),this._attachEventListeners(),i.body.style.overflow="hidden"}}_destroyOverlay(){var e;(null===(e=this._container)||void 0===e?void 0:e.parentNode)&&(this._container.parentNode.removeChild(this._container),this._container=null,this._iframe=null,this._loadingEl=null);var t=null==i?void 0:i.getElementById("vtilt-vtd-styles");(null==t?void 0:t.parentNode)&&t.parentNode.removeChild(t),(null==i?void 0:i.body)&&(i.body.style.overflow="")}_attachEventListeners(){var t,n,r,s=null===(t=this._container)||void 0===t?void 0:t.querySelector(".vtilt-vtd-close");null==s||s.addEventListener("click",()=>this.close());var a=null===(n=this._container)||void 0===n?void 0:n.querySelector(".vtilt-vtd-open");null==a||a.addEventListener("click",()=>{this._originalUrl&&(null==e||e.open(this._originalUrl,"_blank"))}),null===(r=this._container)||void 0===r||r.addEventListener("click",e=>{e.target===this._container&&this.close()});var o=e=>{"Escape"===e.key&&(this.close(),null==i||i.removeEventListener("keydown",o))};null==i||i.addEventListener("keydown",o)}_getBackdropStyles(){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 '}_getModalStyles(){return"\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n background: #0a0a0a;\n overflow: hidden;\n "}_getHeaderStyles(){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 "}_getHeaderHTML(){var e=this._originalUrl||this._destinationUrl,t=e?this._getHostname(e):"";return'\n <div style="display: flex; align-items: center; gap: 12px; flex: 1; min-width: 0;">\n <img \n src="'+(e?this._getFaviconUrl(e):"")+'" \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._escapeHtml(t)+'</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._escapeHtml(this._truncateUrl(e||"",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 '}_getIframeWrapperStyles(){return"\n flex: 1;\n position: relative;\n background: #000;\n overflow: hidden;\n "}_getLoadingStyles(){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 "}_getLoadingHTML(){var e=this._originalUrl||this._destinationUrl,t=e?this._getHostname(e):"";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._escapeHtml(t)+'...</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 '}_getIframeStyles(){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 "}_getGlobalStyles(){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 "}_truncateUrl(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}_escapeHtml(e){if(void 0===i)return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;");var t=i.createElement("div");return t.textContent=e,t.innerHTML}}var ch,dh="text/plain",uh=61440;!function(e){e.GZipJS="gzip-js",e.Base64="base64",e.None="none"}(ch||(ch={}));var hh=function(e,t){void 0===t&&(t="binary");var{data:n,compression:i}=e;if(n){var r=(e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t))(n),s=new Blob([r]).size;if(i===ch.GZipJS&&s>=1024)try{var a=Uu(function(e,t){if(Du)return Du.encode(e);for(var n=e.length,i=new tu(e.length+(e.length>>1)),r=0,s=function(e){i[r++]=e},a=0;a<n;++a){if(r+5>i.length){var o=new tu(r+8+(n-a<<1));o.set(i),i=o}var l=e.charCodeAt(a);l<128||t?s(l):l<2048?(s(192|l>>6),s(128|63&l)):l>55295&&l<57344?(s(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++a))>>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 wu(i,0,r)}(r),{mtime:0});if("text-base64"===t){var o=function(e){if("undefined"==typeof btoa)throw new Error("btoa is not available in this environment");for(var t="",n=0;n<e.length;n+=32768){var i=Math.min(n+32768,e.length),r=e.subarray(n,i);t+=String.fromCharCode.apply(null,r)}return btoa(t)}(a);if(o.length>0&&o.length<.95*s)return{contentType:dh,body:o,estimatedSize:o.length,compressionApplied:ch.Base64}}else{var l=new Blob([a],{type:dh});if(l.size>0&&l.size<.95*s)return{contentType:dh,body:l,estimatedSize:l.size,compressionApplied:ch.GZipJS}}}catch(e){}return{contentType:"application/json",body:r,estimatedSize:s,compressionApplied:null}}};function ph(e,t){return t.compressionApplied?(n=e.url,i=t.compressionApplied,r=n.includes("?")?"&":"?",""+n+r+"compression="+i):e.url;var n,i,r}function vh(e,t){var n={};return t&&(n["Content-Type"]=t),e.headers&&Object.assign(n,e.headers),e.projectToken&&(n[u]=e.projectToken),n}var gh=[{name:"fetch",isAvailable:()=>"undefined"!=typeof fetch,method:e=>{var t=hh(e,"binary");if(t){var{contentType:n,body:i,estimatedSize:r}=t,s=ph(e,t),a=vh(e,n),o=new AbortController,l=e.timeout?setTimeout(()=>o.abort(),e.timeout):null;fetch(s,{method:e.method||"POST",headers:a,body:i,keepalive:r<uh,signal:o.signal}).then(function(){var t=c(function*(t){var n,i=yield t.text(),r={statusCode:t.status,text:i};if(200===t.status){j();try{r.json=JSON.parse(i)}catch(e){}}null===(n=e.callback)||void 0===n||n.call(e,r)});return function(e){return t.apply(this,arguments)}}()).catch(()=>{var t;F("capture"),null===(t=e.callback)||void 0===t||t.call(e,{statusCode:0})}).finally(()=>{l&&clearTimeout(l)})}}},{name:"XHR",isAvailable:()=>"undefined"!=typeof XMLHttpRequest,method:e=>{var t=hh(e,"binary");if(t){var{contentType:n,body:i}=t,r=ph(e,t),s=vh(e,n),a=new XMLHttpRequest;for(var[o,l]of(a.open(e.method||"POST",r,!0),Object.entries(s)))a.setRequestHeader(o,l);e.timeout&&(a.timeout=e.timeout),a.onreadystatechange=()=>{var t;if(4===a.readyState){var n={statusCode:a.status,text:a.responseText};if(200===a.status){j();try{n.json=JSON.parse(a.responseText)}catch(e){}}null===(t=e.callback)||void 0===t||t.call(e,n)}},a.onerror=()=>{var t;F("capture"),null===(t=e.callback)||void 0===t||t.call(e,{statusCode:0})},a.send(i)}}},{name:"sendBeacon",isAvailable:()=>"undefined"!=typeof navigator&&!!navigator.sendBeacon,method:e=>{var t=hh(e,"text-base64");if(t){var{contentType:n,body:i,estimatedSize:r}=t;if(0!==r){var s=ph(e,t),a=e.projectToken?function(e,t){if(!t||/[?&]token=/.test(e))return e;var n=e.includes("?")?"&":"?";return""+e+n+"token="+t}(s,e.projectToken):s;if(r<=uh)try{var o="string"==typeof i?new Blob([i],{type:n}):i;if("undefined"!=typeof navigator&&navigator.sendBeacon)if(navigator.sendBeacon(a,o))return}catch(e){}try{var l="string"==typeof i?new Blob([i],{type:n}):i,c=d({"Content-Type":n},e.headers||{});fetch(a,{method:e.method||"POST",headers:c,body:l,keepalive:r<uh}).catch(()=>{})}catch(e){}}}}}],fh=e=>{var t,n;if(W())null===(t=e.callback)||void 0===t||t.call(e,{statusCode:0});else{var i=e.transport||"fetch",r=gh.find(e=>e.name===i&&e.isAvailable())||gh.find(e=>e.isAvailable());if(!r)return I().error("request","no available transport method"),void(null===(n=e.callback)||void 0===n||n.call(e,{statusCode:0}));r.method(e)}};class _h{constructor(e,t){var n,i,r,s;this._isPaused=!0,this._queue=[],this._flushTimeoutMs=(n=(null==t?void 0:t.flush_interval_ms)||3e3,i=250,r=5e3,s=3e3,"number"!=typeof n||isNaN(n)?s:Math.min(Math.max(n,i),r)),this._sendRequest=e}get length(){return this._queue.length}enqueue(e){this._queue.push(e),this._flushTimeout||this._setFlushTimeout()}unload(){if(this._clearFlushTimeout(),0!==this._queue.length){var e=this._formatQueue();for(var t in e){var n=e[t];this._sendRequest(d({},n,{transport:"sendBeacon"}))}}}enable(){this._isPaused=!1,this._setFlushTimeout()}pause(){this._isPaused=!0,this._clearFlushTimeout()}flush(){this._clearFlushTimeout(),this._flushNow(),this._setFlushTimeout()}_setFlushTimeout(){this._isPaused||(this._flushTimeout=setTimeout(()=>{this._clearFlushTimeout(),this._flushNow(),this._queue.length>0&&this._setFlushTimeout()},this._flushTimeoutMs))}_clearFlushTimeout(){this._flushTimeout&&(clearTimeout(this._flushTimeout),this._flushTimeout=void 0)}_flushNow(){if(0!==this._queue.length){var e=this._formatQueue(),t=Date.now();for(var n in e){var i=e[n];i.events.forEach(e=>{var n=new Date(e.timestamp).getTime();e.$offset=Math.abs(n-t)}),this._sendRequest(i)}}}_formatQueue(){var e={};return this._queue.forEach(t=>{var n=t.batchKey||t.url;e[n]||(e[n]={url:t.url,events:[],batchKey:t.batchKey}),e[n].events.push(t.event)}),this._queue=[],e}}class mh{constructor(t){this._isPolling=!1,this._pollIntervalMs=3e3,this._queue=[],this._areWeOnline=!0,this._sendRequest=t.sendRequest,this._sendBeacon=t.sendBeacon,e&&void 0!==n&&"onLine"in n&&(this._areWeOnline=n.onLine,K(e,"online",()=>{this._areWeOnline=!0,this._flush()}),K(e,"offline",()=>{this._areWeOnline=!1}))}get length(){return this._queue.length}enqueue(e,t){if(void 0===t&&(t=0),t>=10)I().error("retry","request failed after 10 retries, giving up");else if(!W()){var n=function(e){var t=3e3*Math.pow(2,e),n=t/2,i=Math.min(18e5,t),r=(Math.random()-.5)*(i-n);return Math.ceil(i+r)}(t),i=Date.now()+n;this._queue.push({retryAt:i,request:e,retriesPerformedSoFar:t+1});var r="enqueued failed request for retry in "+Math.round(n/1e3)+"s";this._areWeOnline||(r+=" (browser is offline)"),I().warn("retry",r),this._isPolling||(this._isPolling=!0,this._poll())}}retriableRequest(e){var t=this;return c(function*(){try{var n=yield t._sendRequest(e);200!==n.statusCode&&(n.statusCode<400||n.statusCode>=500)&&t.enqueue(e,0)}catch(n){t.enqueue(e,0)}})()}_poll(){this._poller&&clearTimeout(this._poller),this._poller=setTimeout(()=>{this._areWeOnline&&this._queue.length>0&&this._flush(),this._queue.length>0?this._poll():this._isPolling=!1},this._pollIntervalMs)}_flush(){var e=this,t=Date.now(),n=[],i=[];this._queue.forEach(e=>{e.retryAt<t?i.push(e):n.push(e)}),this._queue=n,i.forEach(function(){var t=c(function*(t){var{request:n,retriesPerformedSoFar:i}=t;try{var r=yield e._sendRequest(n);200!==r.statusCode&&(r.statusCode<400||r.statusCode>=500)&&e.enqueue(n,i)}catch(t){e.enqueue(n,i)}});return function(e){return t.apply(this,arguments)}}())}unload(){this._poller&&(clearTimeout(this._poller),this._poller=void 0),this._queue.forEach(e=>{var{request:t}=e;try{this._sendBeacon(t)}catch(e){I().error("retry","failed to send beacon on unload",e)}}),this._queue=[]}}var yh="vt_rate_limit";class bh{constructor(e){var t,n;void 0===e&&(e={}),this.lastEventRateLimited=!1,this.eventsPerSecond=null!==(t=e.eventsPerSecond)&&void 0!==t?t:10,this.eventsBurstLimit=Math.max(null!==(n=e.eventsBurstLimit)&&void 0!==n?n:10*this.eventsPerSecond,this.eventsPerSecond),this.persistence=e.persistence,this.captureWarning=e.captureWarning,this.lastEventRateLimited=this.checkRateLimit(!0).isRateLimited}checkRateLimit(e){var t,n,i,r;void 0===e&&(e=!1);var s=Date.now(),a=null!==(n=null===(t=this.persistence)||void 0===t?void 0:t.get(yh))&&void 0!==n?n:{tokens:this.eventsBurstLimit,last:s},o=(s-a.last)/1e3;a.tokens+=o*this.eventsPerSecond,a.last=s,a.tokens>this.eventsBurstLimit&&(a.tokens=this.eventsBurstLimit);var l=a.tokens<1;return l||e||(a.tokens=Math.max(0,a.tokens-1)),!l||this.lastEventRateLimited||e||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(yh,a),{isRateLimited:l,remainingTokens:a.tokens}}shouldAllowEvent(){return!this.checkRateLimit(!1).isRateLimited}getRemainingTokens(){return this.checkRateLimit(!0).remainingTokens}}class wh{constructor(e){this._remoteConfig=null,this._initConfig=null,this._host=e}get config(){return this._remoteConfig}onApply(e){this._onApply=e}onLoad(e){this._onLoad=e}load(){var t,n=this._host.getConfig();if(n.token){if(this._initConfig||(this._initConfig=d({},n)),null===(t=n.bootstrap)||void 0===t?void 0:t.remoteConfig)return this._remoteConfig=n.bootstrap.remoteConfig,this._apply(this._remoteConfig),void this._fetch();var i=A(()=>e.__VTILT_BOOTSTRAP__);if(null==i?void 0:i.remoteConfig)return this._remoteConfig=i.remoteConfig,this._apply(this._remoteConfig),void this._fetch();A(()=>{var e=localStorage.getItem(Qo+"_"+n.token);e&&(this._remoteConfig=JSON.parse(e),this._apply(this._remoteConfig,!0))}),this._fetch()}}_fetch(){var e=this._host.getConfig();if(e.token)if(W())this._host.updateConfig({__remote_config_loaded:!0});else{var t=this._host.buildEndpointUrl("/api/d"),n=new AbortController,i=setTimeout(()=>n.abort(),3e3);(s||fetch)(t,{method:"GET",signal:n.signal,headers:d({Accept:"application/json"},p(e))}).then(e=>e.json()).then(t=>{var n;clearTimeout(i),j(),this._remoteConfig=t,A(()=>{localStorage.setItem(Qo+"_"+e.token,JSON.stringify(t))}),this._apply(t),null===(n=this._onLoad)||void 0===n||n.call(this,t)}).catch(()=>{clearTimeout(i),F("config"),this._host.updateConfig({__remote_config_loaded:!0})})}}_apply(e,t){var n,i,r,s;void 0===t&&(t=!1);var a=this._initConfig||this._host.getConfig(),o={};for(var[,l]of this._host.featureManager.getDescriptors())if(l.remoteConfig&&l.configKey){var c=e[l.remoteConfig.key];c&&void 0===a[l.configKey]&&(o[l.configKey]=l.remoteConfig.map(c))}if(e.analytics&&!t&&(void 0!==e.analytics.capturePageview&&void 0===a.capture_pageview&&(o.capture_pageview=e.analytics.capturePageview),void 0!==e.analytics.capturePageleave&&void 0===a.capture_pageleave&&(o.capture_pageleave=!!e.analytics.capturePageleave),void 0!==e.analytics.capturePerformance&&void 0===a.capture_performance&&(o.capture_performance=e.analytics.capturePerformance),void 0===a.autocapture)){var u=e.analytics.autocapture,h=e.analytics.scrollDepthMilestones,p=e.analytics.scrollDepthPageleave;void 0!==u&&(o.autocapture=u&&(h||p)?{scroll_depth:d({},h?{milestones:!0}:{},p?{pageleave:!0}:{})}:u)}t||(o.__remote_config_loaded=!0),void 0!==(null===(n=e.privacy)||void 0===n?void 0:n.respectDnt)&&void 0===a.respect_dnt&&(o.respect_dnt=e.privacy.respectDnt),void 0!==(null===(i=e.privacy)||void 0===i?void 0:i.requireConsent)&&void 0===a.require_consent&&(o.require_consent=e.privacy.requireConsent),void 0!==e.autocapture_opt_out&&(o.autocapture_opt_out=e.autocapture_opt_out),void 0!==e.elementsChainAsString&&(o.elementsChainAsString=e.elementsChainAsString),(null===(r=e.diagnostics)||void 0===r?void 0:r.defaultLogLevel)&&I().setLevelFromRemote(e.diagnostics.defaultLogLevel),Object.keys(o).length>0&&this._host.updateConfig(o),null===(s=this._onApply)||void 0===s||s.call(this,e)}}var Ch=["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 Sh(e,t){if(void 0===t&&(t=[]),!e)return!1;var n=e.toLowerCase();return[...Ch,...t].some(e=>-1!==n.indexOf(e.toLowerCase()))}function kh(e,t){var n;if(void 0===t&&(t=[]),!e)return!1;var i=e.userAgent;if(i&&Sh(i,t))return!0;try{var r=e.userAgentData;if(null===(n=null==r?void 0:r.brands)||void 0===n?void 0:n.some(e=>Sh(null==e?void 0:e.brand,t)))return!0}catch(e){}return!!e.webdriver}var xh=36e5;function Th(){var t,n,i;return null!==(i=null===(n=null===(t=null==e?void 0:e.performance)||void 0===t?void 0:t.now)||void 0===n?void 0:n.call(t))&&void 0!==i?i:Date.now()}class Ih{constructor(){this._pageEnterPerf=Th(),this._lastCapturePerf=null,this._bootPerf=Th(),this._prevUrl="",this._prevPathname="",this._prevTitle="",this._leaveEmittedForPageKey=""}onAfterPageview(){var e=Th();this._pageEnterPerf=e,this._lastCapturePerf=e,this._leaveEmittedForPageKey="",r&&(this._prevUrl=r.href||"",this._prevPathname=r.pathname||""),i&&(this._prevTitle=i.title||"")}peekEngagementSinceLastCaptureMs(){var e,t=Th(),n=null!==(e=this._lastCapturePerf)&&void 0!==e?e:this._bootPerf,i=Math.round(t-n);return i<1&&(i=1),i>xh&&(i=xh),i}commitCaptureClock(){this._lastCapturePerf=Th()}_pageKey(){return this._prevUrl+"\0"+this._prevPathname}clearLeaveDedupe(){this._leaveEmittedForPageKey=""}tryCapturePageleave(e,t,n,i){if(function(e){var t=e.capture_pageleave;return!1!==t&&(!0===t||!1!==e.capture_pageview)}(e)){var r=this._pageKey();if((this._prevUrl||this._prevPathname)&&r&&this._leaveEmittedForPageKey!==r){this._leaveEmittedForPageKey=r;var s=Th(),a=Math.round(s-this._pageEnterPerf);a<1&&(a=1),a>xh&&(a=xh);var o={navigation_type:n,engagement_time_msec:a,[gl]:this._prevUrl,[fl]:this._prevPathname,[_l]:Math.round(a/1e3),[ml]:this._prevPathname,[yl]:this._prevUrl},l=this._prevUrl?function(e){try{return new URL(e).host}catch(e){return""}}(this._prevUrl):"";l&&(o.$host=l),this._prevTitle&&(o.title=this._prevTitle),i&&Object.assign(o,i),t(sl,o,{skip_engagement:!0})}}}}var Eh=[al,ol,ll,sl,hl,pl,cl,vl],Ah=new Set([al,ol,ll]),Oh=new Set([sl,vl,hl,pl,cl]);class Mh{constructor(e){this._set_once_properties_sent=!1,this._initial_pageview_captured=!1,this._visibility_state_listener=null,this._vt_person_id=null,this._pageLifecycle=new Ih,this._host=e}setVtPersonId(e){this._vt_person_id=e}capture(e,t,i){var r,s,a;this._host.sessionManager.setSessionId();var o=this._host.getConfig();if(o.opt_out_useragent_filter||!kh(n,null!==(r=o.custom_blocked_useragents)&&void 0!==r?r:[]))if((null==n?void 0:n.userAgent)&&function(e){return!(e&&"string"==typeof e&&e.length>500)}(n.userAgent))if((null==i?void 0:i.skip_client_rate_limiting)||Eh.includes(e)||this._host.rateLimiter.shouldAllowEvent())if(!this._host.getConfig().require_consent||Ah.has(e)||(null===(s=this._host.consentManager)||void 0===s?void 0:s.hasConsent())){var l=this._host.buildUrl(),c=!0===(null==i?void 0:i.skip_engagement)||Oh.has(e),u=d({},t);c||"number"==typeof u.engagement_time_msec||(u=d({},u,{engagement_time_msec:this._pageLifecycle.peekEngagementSinceLastCaptureMs()}));var h=d({},this._buildEventPayload(e,u),o.globalAttributes),p=JSON.stringify(h);if(!(v=p)||"string"!=typeof v||v.length<2||v.length>V)I().debug("capture","dropped",e,{reason:"payload_invalid_size",bytes:p.length,limitBytes:V,hint:e===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 v,g=e===al?this._host.userManager.getAnonymousId():null!==(a=this._host.userManager.getDistinctId())&&void 0!==a?a:this._host.userManager.getAnonymousId(),f={timestamp:(new Date).toISOString(),event:e,payload:h,distinct_id:g,anonymous_id:this._host.userManager.getAnonymousId()};this._host.bufferEvent(e,l,f),I().debug("capture","enqueued",e,d({distinct_id:g,$current_url:h.$current_url,$session_id:h.$session_id,$debug:h.$debug},e===dl&&"object"==typeof h&&null!==h?{$event_type:h.$event_type}:{})),this._vt_person_id&&(this._vt_person_id=null),e===rl?this._pageLifecycle.onAfterPageview():this._pageLifecycle.commitCaptureClock()}}else I().debug("capture","dropped",e,{reason:"require_consent_and_no_consent"});else I().debug("capture","dropped",e,{reason:"client_rate_limited",hint:"Token bucket (~10/s, burst ~100). $autocapture counts toward the same limit as custom events."});else I().debug("capture","dropped",e,{reason:"invalid_or_missing_user_agent"});else I().debug("capture","dropped",e,{reason:"bot"})}captureInternal(e,t){this.capture(e,t,{skip_client_rate_limiting:!0})}captureInitialPageview(){i&&("visible"===i.visibilityState?this._initial_pageview_captured||(this._initial_pageview_captured=!0,setTimeout(()=>{i&&r&&!1!==this._host.getConfig().capture_pageview&&this.capture(rl,{navigation_type:"initial_load"})},300),this._visibility_state_listener&&(i.removeEventListener("visibilitychange",this._visibility_state_listener),this._visibility_state_listener=null)):this._visibility_state_listener||(this._visibility_state_listener=()=>this.captureInitialPageview(),K(i,"visibilitychange",this._visibility_state_listener)))}tryCapturePageleave(e,t){this._pageLifecycle.tryCapturePageleave(this._host.getConfig(),(e,t,n)=>this.capture(e,t,n),e,t)}resetPageleaveDedupe(){this._pageLifecycle.clearLeaveDedupe()}_isDebugMode(){if(this._host.getConfig().debug)return!0;try{if(null==r?void 0:r.search)if("1"===new URLSearchParams(r.search).get("vtilt_debug"))return!0}catch(e){}return!1}_buildEventPayload(e,t){var n,r,s=this._host.getConfig(),a=s.mask_personal_data_properties,o=s.custom_personal_data_properties,l=Yc(a,o),c=X(function(e,t,n){if(!i)return{};var r=t?Q([],Fc,n||[]):[];return J({},$c(Ul(i.URL,r,Wc)))}(0,a,o)),u=this._host.userManager.getUserProperties(),h=this._host.userManager.get_initial_props(),p=this._host.sessionManager.getSessionId(),v=this._host.sessionManager.getWindowId(),g={};!this._set_once_properties_sent&&Object.keys(h).length>0&&Object.assign(g,h),t.$set_once&&Object.assign(g,t.$set_once);var f=d({},l,c,u,null!==(r=null===(n=this._host.consentManager)||void 0===n?void 0:n.getConsentProperties())&&void 0!==r?r:{},{$session_id:p,$window_id:v},this._vt_person_id?{$vt:this._vt_person_id}:{},Object.keys(g).length>0?{$set_once:g}:{},t.$set?{$set:t.$set}:{},t);!this._set_once_properties_sent&&Object.keys(h).length>0&&(this._set_once_properties_sent=!0),e===rl&&i&&(f.title=i.title),this._isDebugMode()&&(f.$debug=!0);var _=this._host.sessionManager.consumeSessionStart(),m=this._host.userManager.consumeFirstVisit();return _&&(f.$session_start=!0),m&&(f.$first_visit=!0),f}}var Rh=["null","undefined","false","true","anonymous","anon","user","test","guest","visitor","unknown","none","demo","example","sample","placeholder"];function Ph(e){return!(!e||"string"!=typeof e)&&Rh.includes(e.toLowerCase().trim())}class Lh{constructor(e){this._lastIdentifyHash=null,this._lastSetPropertiesHash=null,this._host=e}identify(e,t,n){var i;if("number"==typeof e&&(e=String(e),I().warn("identify","first argument should be a string, not a number")),e)if(Ph(e))I().error("identify",'"'+e+'" appears to be a hardcoded string');else if("COOKIELESS_SENTINEL_VALUE"!==e){var r=JSON.stringify([e,t,n]);if(this._lastIdentifyHash!==r){var s=this._host.userManager,a=s.getDistinctId(),o=s.getAnonymousId(),l=s.getDeviceId();if(!("identified"===s.getUserState())&&o!==e||e!==a){this._host.capture(al,{distinct_id:e,$set:t||{},$set_once:n||{}});var c={user_state:"identified",distinct_id:e,properties_set:t,properties_set_once:n};if(!l){var u=a||o;c.device_id=u,c.properties_set=d({$had_persisted_distinct_id:!0,$device_id:u},c.properties_set||{})}s.applyUpdate(c),null===(i=this._host._emitter)||void 0===i||i.emit("user:identified",{distinctId:e})}else(t||n)&&this.setUserProperties(t,n);this._lastIdentifyHash=r}}else I().error("identify","cannot use sentinel value as distinct_id");else I().error("identify","unique user id is required")}setUserProperties(e,t){var n,i;if(e||t){var r=this._host.userManager,s=JSON.stringify([null!==(n=r.getDistinctId())&&void 0!==n?n:r.getAnonymousId(),e,t]);this._lastSetPropertiesHash!==s&&(r.applyUpdate({properties_set:e,properties_set_once:t}),this._host.capture(ll,{$set:e||{},$set_once:t||{}}),null===(i=this._host._emitter)||void 0===i||i.emit("user:properties_set",{properties:e}),this._lastSetPropertiesHash=s)}}resetUser(e){var t;this._host.sessionManager.resetSessionId(),this._host.userManager.reset(e),this._lastIdentifyHash=null,this._lastSetPropertiesHash=null,null===(t=this._host._emitter)||void 0===t||t.emit("user:reset")}alias(e,t){var n;if(e&&!Ph(e)){var i=this._host.userManager,r=null!==(n=null!=t?t:i.getDistinctId())&&void 0!==n?n:i.getAnonymousId();r&&!Ph(r)?e!==r?this._host.capture(ol,{$original_id:r,$alias_id:e}):this.identify(e):I().warn("alias","invalid original distinct ID")}else I().warn("alias","invalid alias")}getUserIdentity(){return this._host.userManager.getUserIdentity()}getDeviceId(){return this._host.userManager.getDeviceId()}getUserState(){return this._host.userManager.getUserState()}getDistinctId(){var e;return null!==(e=this._host.userManager.getDistinctId())&&void 0!==e?e:this._host.userManager.getAnonymousId()}getAnonymousId(){return this._host.userManager.getAnonymousId()}}var Uh="_vtilt_consent";class Dh{constructor(e){this._state={},this._hasBeenSet=!1,this._host=e,this._readFromCookie()}setConsent(e){var t;this._state=d({},this._state,e),this._hasBeenSet=!0,this._writeToCookie(),null===(t=this._host._emitter)||void 0===t||t.emit("consent:updated",{consent:this._state})}getConsent(){return d({},this._state)}hasConsent(){return this._hasBeenSet}setDefaultGranted(){this._hasBeenSet||(this._state={analytics:!0,marketing:!0,advertising:!0},this._hasBeenSet=!0)}getConsentProperties(){var e={};return void 0!==this._state.analytics&&(e.$consent_analytics=this._state.analytics),void 0!==this._state.marketing&&(e.$consent_marketing=this._state.marketing),void 0!==this._state.advertising&&(e.$consent_advertising=this._state.advertising),e}reset(){this._state={},this._hasBeenSet=!1,this._removeCookie()}_readFromCookie(){if(void 0!==i&&(null==i?void 0:i.cookie)){var e=Uh+"=";for(var t of i.cookie.split(";")){var n=t.trim();if(n.startsWith(e)){try{var r=decodeURIComponent(n.slice(15)),s=JSON.parse(r);s&&"object"==typeof s&&(this._state=s,this._hasBeenSet=!0)}catch(e){}return}}}}_writeToCookie(){if(void 0!==i){var e=encodeURIComponent(JSON.stringify(this._state)),t="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";i.cookie=Uh+"="+e+"; Max-Age=31536000; path=/; SameSite=Lax"+t}}_removeCookie(){void 0!==i&&(i.cookie=Uh+"=; Max-Age=0; path=/")}}class Nh{constructor(e){this._descriptors=new Map,this._instances=new Map,this._host=e}register(e){this._descriptors.set(e.name,e)}createInstances(){var e=this,t=this._host.getConfig(),n=function(n,i){return e._instances.has(n)||e._isHardDisabled(t,i)?0:void A(()=>{var r=i.FeatureClass.extractConfig(t),s=new i.FeatureClass(e._host,r);e._instances.set(n,s)})};for(var[i,r]of this._descriptors)n(i,r)}initAll(){this.createInstances();var e=function(e){A(()=>{e.isStarted||e.startIfEnabled()})};for(var[,t]of this._instances)e(t)}notifyAll(e){var t=function(t){t.onConfigUpdate&&A(()=>t.onConfigUpdate(e))};for(var[,n]of this._instances)t(n)}get(e){return this._instances.get(e)}set(e,t){this._instances.set(e,t)}getDescriptors(){return this._descriptors}_isHardDisabled(e,t){if(t.disableKey&&!0===e[t.disableKey])return!0;if(t.configKey){var n=e[t.configKey];if(n&&"object"==typeof n&&!1===n.enabled)return!0}return!1}}class Bh{constructor(e){this._queue=new rh,this._ready=!1,this._configReady=!1,this._host=e,this._checkReady(),this._ready||(this._safetyTimer=setTimeout(()=>this.forceFlush(),5e3))}push(e){this._ready?this._process(e):this._queue.enqueue(e)}markConfigReady(){this._configReady||(this._configReady=!0,this._tryFlush())}forceFlush(){this._clearSafetyTimer(),this._flush(),this._ready=!0}_checkReady(){this._ready=this._configReady}_tryFlush(){this._checkReady(),this._ready&&(this._clearSafetyTimer(),this._flush())}_flush(){var e=this._queue.takeAll();for(var t of e)this._process(t);e.length>0&&this._host.requestQueue.flush()}_process(e){if(this._configReady){if(this._isDisabledByConfig(e.name))return}else this._tagConfigPending(e.event);this._host.sendRequest(e.url,e.event)}_isDisabledByConfig(e){var t=this._host.getConfig();switch(e){case rl:return!1===t.capture_pageview;case sl:return!1===t.capture_pageleave;case cl:return!1===t.capture_performance;case dl:case ul:return!1===t.autocapture;default:return!1}}_tagConfigPending(e){"object"==typeof e.payload&&null!==e.payload&&(e.payload.$config_pending=!0)}_clearSafetyTimer(){void 0!==this._safetyTimer&&(clearTimeout(this._safetyTimer),this._safetyTimer=void 0)}}var Hh="vt";class qh{constructor(e){void 0===e&&(e={}),this.version=Wo,this.__loaded=!1,this._has_warned_about_config=!1,this._booted=!1,this._pendingCalls=[],this._postBootInitDone=!1,I().debug("ctor","start"),this._emitter=new O,this.configManager=new kl(e);var t=this.configManager.getConfig();E(t),this.sessionManager=new Ol(t.storage||"cookie",t.cross_subdomain_cookie),this.userManager=new Zc(t.persistence||"localStorage+cookie",t.cross_subdomain_cookie),this.rateLimiter=new bh({eventsPerSecond:10,eventsBurstLimit:100,captureWarning:e=>{this._captureManager.captureInternal(vl,{$$client_ingestion_warning_message:e})}}),this.retryQueue=new mh({sendRequest:e=>this._send_http_request(e),sendBeacon:e=>this._send_beacon_request(e)}),this.requestQueue=new _h(e=>this._send_batched_request(e),{flush_interval_ms:3e3}),this.consentManager=new Dh(this),this._captureManager=new Mh(this),this._identityManager=new Lh(this),this._featureManager=new Nh(this),this._remoteConfigManager=new wh(this),this._registerFeatures(),this._remoteConfigManager.onLoad(e=>{this._emitter.emit(P,{config:e})}),this._installBootGate(),I().debug("ctor","boot gate installed")}_registerFeatures(){this._featureManager.register({name:"HistoryAutocapture",configKey:"capture_pageview",FeatureClass:od}),this._featureManager.register({name:"Autocapture",configKey:"autocapture",FeatureClass:Xd}),this._featureManager.register({name:"WebVitals",configKey:"capture_performance",FeatureClass:sd}),this._featureManager.register({name:"SessionRecording",configKey:"session_recording",disableKey:"disable_session_recording",remoteConfig:{key:"sessionRecording",map:e=>({enabled:e.enabled,sampleRate:e.sampleRate,minimumDurationMs:e.minimumDurationMs,fullSnapshotIntervalMs:e.fullSnapshotIntervalMs,maskAllInputs:e.maskAllInputs,captureConsole:e.captureConsole,captureCanvas:e.captureCanvas})},FeatureClass:Zd}),this._featureManager.register({name:"Chat",configKey:"chat",disableKey:"disable_chat",remoteConfig:{key:"chat",map:e=>({enabled:e.enabled,position:e.widgetPosition,color:e.widgetColor})},FeatureClass:Hu}),this._featureManager.register({name:"GoogleTagGateway",configKey:"google_tag",disableKey:"disable_google_tag",remoteConfig:{key:"googleTag",map:e=>e},FeatureClass:ah})}_installBootGate(){var e=this,t=function(t){var n=e[t];e[t]=function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];if(e._booted)return n.apply(e,r);e._pendingCalls.push([t,...r])}};for(var n of qh.BOOT_GATED_METHODS)t(n)}_boot(){if(!this._booted){for(var e of(this._booted=!0,I().debug("boot","start"),qh.BOOT_GATED_METHODS))delete this[e];I().debug("boot","gate removed"),this.__loaded&&!this._postBootInitDone?(I().debug("boot","running _runPostBootInit"),this._runPostBootInit()):I().debug("boot","skipping _runPostBootInit","loaded?",this.__loaded,"postBootDone?",this._postBootInitDone),I().debug("boot","flush pendingCalls",this._pendingCalls.length),this._execute_array(this._pendingCalls),this._pendingCalls=[]}}init(e,t,n){var i;if(n&&n!==Hh){var r=null!==(i=Wh[n])&&void 0!==i?i:new qh;return r._init(e,t,n),Wh[n]=r,Wh[Hh][n]=r,r}return this._init(e,t,n)}_init(e,t,n){if(void 0===t&&(t={}),this.__loaded)return I().warn("init","already initialized; re-initializing is a no-op"),this;this.configManager.updateConfig(d({},t,{token:e||t.token,name:n}));var r=this.configManager.getConfig();return E(r),this.__loaded=!0,I().debug("init","start","token present?",!!r.token,"name",null!=n?n:"vt"),this._featureManager.createInstances(),this._booted||void 0===i||"interactive"!==i.readyState&&"complete"!==i.readyState||(I().debug("init","self-boot?",i.readyState),this._boot()),this._booted&&!this._postBootInitDone&&this._runPostBootInit(),I().debug("init","postBootInitDone",this._postBootInitDone),this}_runPostBootInit(){if(!this._postBootInitDone){this._postBootInitDone=!0,I().debug("postBoot","start");var e=this.configManager.getConfig();this.sessionManager=new Ol(e.storage||"cookie",e.cross_subdomain_cookie),this.sessionManager.hydrateFromStorage(),I().debug("postBoot","sessionManager hydrated");var t=e.persistence||"localStorage+cookie";this.userManager.updateStorageMethod(t,e.cross_subdomain_cookie),this.userManager.hydrateFromStorage(),I().debug("postBoot","userManager hydrated"),e.require_consent||this.consentManager.hasConsent()||this.consentManager.setDefaultGranted(),!0===this.consentManager.getConsent().advertising&&ql(),this._emitter.on("consent:updated",e=>{var t=e.consent;!0===t.advertising?ql():!1===t.advertising&&void 0!==i&&(i.cookie=Dl+"=; Max-Age=0; path=/",i.cookie=Nl+"=; Max-Age=0; path=/")}),this._read_vt_param_from_url(),this.userManager.set_initial_person_info(e.mask_personal_data_properties,e.custom_personal_data_properties),this._eventBuffer=new Bh({sendRequest:(e,t)=>this.sendRequest(e,t),requestQueue:this.requestQueue,getConfig:()=>this.configManager.getConfig()}),this._featureManager.initAll(),I().debug("postBoot","features inited"),this._remoteConfigManager.load(),this._setup_unload_handler(),this._start_queue_if_opted_in();var n=this.configManager.getConfig();!1!==n.capture_pageview&&this._captureManager.captureInitialPageview(),this._featureManager.notifyAll(n),this._emitter.emit(M,{config:n}),I().debug("postBoot","done"),I().info("init","SDK ready")}}startAutocapture(){var e=this._featureManager.get("Autocapture");if(!e){var t=Xd.extractConfig(this.configManager.getConfig());e=new Xd(this,t),this._featureManager.set("Autocapture",e)}e.updateConfig({enabled:!0})}stopAutocapture(){var e=this._featureManager.get("Autocapture");e&&e.updateConfig({enabled:!1})}isAutocaptureActive(){var e,t;return null!==(t=null===(e=this._featureManager.get("Autocapture"))||void 0===e?void 0:e.isStarted)&&void 0!==t&&t}getAutocaptureDiagnostics(){var e,t;return null!==(t=null===(e=this._featureManager.get("Autocapture"))||void 0===e?void 0:e.getDiagnostics())&&void 0!==t?t:null}startSessionRecording(){var e=this._featureManager.get("SessionRecording");e||(e=new Zd(this),this._featureManager.set("SessionRecording",e)),e.updateConfig({enabled:!0}),e.startIfEnabledOrStop("recording_initialized"),this._emitter.emit(D)}stopSessionRecording(){var e;null===(e=this._featureManager.get("SessionRecording"))||void 0===e||e.stop(),this._emitter.emit(N)}isRecordingActive(){var e;return"active"===(null===(e=this._featureManager.get("SessionRecording"))||void 0===e?void 0:e.status)}getSessionRecordingId(){var e;return(null===(e=this._featureManager.get("SessionRecording"))||void 0===e?void 0:e.sessionId)||null}openChat(){var e=this._featureManager.get("Chat");e?e.open():I().warn("chat","openChat: feature not available")}closeChat(){var e=this._featureManager.get("Chat");e?e.close():I().warn("chat","closeChat: feature not available")}toggleChat(){var e=this._featureManager.get("Chat");e?e.toggle():I().warn("chat","toggleChat: feature not available")}showChat(){var e=this._featureManager.get("Chat");e?e.show():I().warn("chat","showChat: feature not available")}hideChat(){var e=this._featureManager.get("Chat");e?e.hide():I().warn("chat","hideChat: feature not available")}sendChatMessage(e,t){var n=this._featureManager.get("Chat");return n?n.sendMessage(e,t):(I().warn("chat","sendChatMessage: feature not available"),Promise.resolve())}gtag(){for(var e=this._featureManager.get("GoogleTagGateway"),t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];e?e.gtag(...n):this._pendingCalls.push(["gtag",...n])}setGoogleUserData(e){var t=this._featureManager.get("GoogleTagGateway");return t?t.setUserData(e):Promise.resolve()}get featureManager(){return this._featureManager}on(e,t){return this._emitter.on(e,t)}once(e,t){return this._emitter.once(e,t)}off(e){this._emitter.off(e)}_is_bot(){var e,t=this.getConfig();return!t.opt_out_useragent_filter&&kh(n,null!==(e=t.custom_blocked_useragents)&&void 0!==e?e:[])}capture(e,t,n){this._captureManager.capture(e,t,n),this._emitter.emit(U,{event:e,payload:t})}tryCapturePageleave(e){var t,n=null===(t=this._featureManager.get("Autocapture"))||void 0===t?void 0:t.getMaxScrollDepthPctForPageleave(),i=null!=n?{[Cl]:n}:void 0;this._captureManager.tryCapturePageleave(e,i)}identify(e,t,n){this._identityManager.identify(e,t,n)}setUserProperties(e,t){this._identityManager.setUserProperties(e,t)}resetUser(e){this._identityManager.resetUser(e)}alias(e,t){this._identityManager.alias(e,t)}setConsent(e){this.consentManager.setConsent(e)}getConsent(){return this.consentManager.getConsent()}getUserIdentity(){return this._identityManager.getUserIdentity()}getDeviceId(){return this._identityManager.getDeviceId()}getUserState(){return this._identityManager.getUserState()}getConfig(){return this.configManager.getConfig()}getRemoteConfig(){return this._remoteConfigManager.config}getSessionId(){return this.sessionManager.getSessionId()}getDistinctId(){return this._identityManager.getDistinctId()}getAnonymousId(){return this._identityManager.getAnonymousId()}toString(){var e,t=null!==(e=this.configManager.getConfig().name)&&void 0!==e?e:Hh;return t!==Hh&&(t="vt."+t),t}updateConfig(e){var t,n=this.configManager.getConfig();this.configManager.updateConfig(e);var i=this.configManager.getConfig();!n.__remote_config_loaded&&i.__remote_config_loaded&&(null===(t=this._eventBuffer)||void 0===t||t.markConfigReady()),this._featureManager.notifyAll(i),this._emitter.emit(R,{config:i})}buildUrl(){return this.buildEndpointUrl("/api/e")}buildEndpointUrl(e){return h(this.configManager.getConfig(),e)}sendRequest(e,t){this._is_configured()&&this.requestQueue.enqueue({url:e,event:t})}bufferEvent(e,t,n){e!==hl&&e!==pl?this._eventBuffer.push({name:e,url:t,event:n}):this.sendRequest(t,n)}_is_configured(){return!!this.configManager.getConfig().token||(this._has_warned_about_config||(I().warn("config","token is required for tracking"),this._has_warned_about_config=!0),!1)}_send_batched_request(e){"sendBeacon"!==e.transport?this.retryQueue.retriableRequest(e):this._send_beacon_request(e)}_send_http_request(e){return new Promise(t=>{var{url:n,events:i}=e,r=this.configManager.getConfig(),s=1===i.length?i[0]:{events:i},a=r.disable_compression?ch.None:ch.GZipJS;fh({url:n,data:s,method:"POST",transport:"XHR",compression:a,projectToken:r.token,callback:e=>t({statusCode:e.statusCode})})})}_send_beacon_request(e){var{url:t,events:n}=e,i=this.configManager.getConfig(),r=1===n.length?n[0]:{events:n},s=i.disable_compression?ch.None:ch.GZipJS;fh({url:t,data:r,method:"POST",transport:"sendBeacon",compression:s,projectToken:i.token})}_send_retriable_request(e){this.sendRequest(e.url,e.event)}_setup_unload_handler(){if(e){var t=()=>{this._eventBuffer.forceFlush(),this.requestQueue.unload(),this.retryQueue.unload()};K(e,"beforeunload",t),K(e,"pagehide",()=>{this._captureManager.tryCapturePageleave("pagehide"),t()}),i&&K(i,"visibilitychange",()=>{i&&("hidden"===i.visibilityState?this._captureManager.tryCapturePageleave("visibility_hidden"):"visible"===i.visibilityState&&this._captureManager.resetPageleaveDedupe())})}}_start_queue_if_opted_in(){this.requestQueue.enable()}_read_vt_param_from_url(){A(()=>{var t,n;if(void 0!==r&&r.search){var i=new URL(r.href),s=i.searchParams.get("vt"),a=i.searchParams.get("vtd");if((null==s?void 0:s.trim())&&(this._captureManager.setVtPersonId(s.trim()),i.searchParams.delete("vt")),(null==a?void 0:a.trim())&&(this._initVtdOverlay(a.trim()),i.searchParams.delete("vtd")),(null==s?void 0:s.trim())||(null==a?void 0:a.trim())){var o=i.pathname+(i.search||"")+i.hash;null===(n=null===(t=null==e?void 0:e.history)||void 0===t?void 0:t.replaceState)||void 0===n||n.call(t,{},"",o)}}})}_initVtdOverlay(e){this.vtdOverlay||(this.vtdOverlay=new lh(this),this.vtdOverlay.setDestinationUrl(e))}_execute_array(e){_(e)&&e.forEach(e=>{if(e&&_(e)&&e.length>0){var t=e[0],n=e.slice(1);"function"==typeof this[t]&&A(()=>this[t](...n))}})}_dom_loaded(){this._start_queue_if_opted_in()}}qh.BOOT_GATED_METHODS=["capture","identify","setUserProperties","resetUser","alias","setConsent","startAutocapture","stopAutocapture","startSessionRecording","stopSessionRecording","openChat","closeChat","toggleChat","showChat","hideChat","sendChatMessage"];var Fh,jh,Wh={};Fh=Wh[Hh]=new qh,(jh=o.vt)&&G(jh._i,function(e){if(e&&_(e)){var t=Fh.init(e[0],e[1],e[2]),n=jh[e[2]||"vt"]||jh;t&&t._execute_array(n)}}),o.vt=Fh,function(){function t(){if(!t.done){t.done=!0,I().debug("dom","handler fired");var e=Object.keys(Wh);I().debug("boot","instance count",e.length),G(Wh,(e,t)=>{I().debug("boot","instance",t),e._boot(),e._dom_loaded()})}}if(i&&"function"==typeof i.addEventListener)return I().debug("dom","readyState",i.readyState),void("complete"===i.readyState||"interactive"===i.readyState?(I().debug("dom","running handler sync"),t()):(I().debug("dom","registered DOMContentLoaded listener"),K(i,"DOMContentLoaded",t,{capture:!1})));e&&I().error("dom","browser doesn't support document.addEventListener")}()}();
2
+ //# sourceMappingURL=array.chat.no-external.js.map