@truly-you/trulyyou-web-sdk 0.1.17 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -5,5 +5,5 @@ function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"de
5
5
  *
6
6
  * Copyright 2020, Pusher
7
7
  * Released under the MIT licence.
8
- */window,t=function(){return function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(i,r,function(t){return e[t]}.bind(null,r));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=2)}([function(e,t,n){var i,r=this&&this.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},i(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0});var o=256,s=function(){function e(e){void 0===e&&(e="="),this._paddingCharacter=e}return e.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(8*e+5)/6|0},e.prototype.encode=function(e){for(var t="",n=0;n<e.length-2;n+=3){var i=e[n]<<16|e[n+1]<<8|e[n+2];t+=this._encodeByte(i>>>18&63),t+=this._encodeByte(i>>>12&63),t+=this._encodeByte(i>>>6&63),t+=this._encodeByte(i>>>0&63)}var r=e.length-n;return r>0&&(i=e[n]<<16|(2===r?e[n+1]<<8:0),t+=this._encodeByte(i>>>18&63),t+=this._encodeByte(i>>>12&63),t+=2===r?this._encodeByte(i>>>6&63):this._paddingCharacter||"",t+=this._paddingCharacter||""),t},e.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(6*e+7)/8|0},e.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},e.prototype.decode=function(e){if(0===e.length)return new Uint8Array(0);for(var t=this._getPaddingLength(e),n=e.length-t,i=new Uint8Array(this.maxDecodedLength(n)),r=0,s=0,a=0,c=0,h=0,l=0,d=0;s<n-4;s+=4)c=this._decodeChar(e.charCodeAt(s+0)),h=this._decodeChar(e.charCodeAt(s+1)),l=this._decodeChar(e.charCodeAt(s+2)),d=this._decodeChar(e.charCodeAt(s+3)),i[r++]=c<<2|h>>>4,i[r++]=h<<4|l>>>2,i[r++]=l<<6|d,a|=c&o,a|=h&o,a|=l&o,a|=d&o;if(s<n-1&&(c=this._decodeChar(e.charCodeAt(s)),h=this._decodeChar(e.charCodeAt(s+1)),i[r++]=c<<2|h>>>4,a|=c&o,a|=h&o),s<n-2&&(l=this._decodeChar(e.charCodeAt(s+2)),i[r++]=h<<4|l>>>2,a|=l&o),s<n-3&&(d=this._decodeChar(e.charCodeAt(s+3)),i[r++]=l<<6|d,a|=d&o),0!==a)throw new Error("Base64Coder: incorrect characters for decoding");return i},e.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-15,t+=62-e>>>8&3,String.fromCharCode(t)},e.prototype._decodeChar=function(e){var t=o;return t+=(42-e&e-44)>>>8&-256+e-43+62,t+=(46-e&e-48)>>>8&-256+e-47+63,t+=(47-e&e-58)>>>8&-256+e-48+52,t+=(64-e&e-91)>>>8&-256+e-65+0,t+=(96-e&e-123)>>>8&-256+e-97+26},e.prototype._getPaddingLength=function(e){var t=0;if(this._paddingCharacter){for(var n=e.length-1;n>=0&&e[n]===this._paddingCharacter;n--)t++;if(e.length<4||t>2)throw new Error("Base64Coder: incorrect padding")}return t},e}();t.Coder=s;var a=new s;t.encode=function(e){return a.encode(e)},t.decode=function(e){return a.decode(e)};var c=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return r(t,e),t.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-13,t+=62-e>>>8&49,String.fromCharCode(t)},t.prototype._decodeChar=function(e){var t=o;return t+=(44-e&e-46)>>>8&-256+e-45+62,t+=(94-e&e-96)>>>8&-256+e-95+63,t+=(47-e&e-58)>>>8&-256+e-48+52,t+=(64-e&e-91)>>>8&-256+e-65+0,t+=(96-e&e-123)>>>8&-256+e-97+26},t}(s);t.URLSafeCoder=c;var h=new c;t.encodeURLSafe=function(e){return h.encode(e)},t.decodeURLSafe=function(e){return h.decode(e)},t.encodedLength=function(e){return a.encodedLength(e)},t.maxDecodedLength=function(e){return a.maxDecodedLength(e)},t.decodedLength=function(e){return a.decodedLength(e)}},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var i="utf8: invalid string",r="utf8: invalid source encoding";function o(e){for(var t=0,n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128)t+=1;else if(r<2048)t+=2;else if(r<55296)t+=3;else{if(!(r<=57343))throw new Error(i);if(n>=e.length-1)throw new Error(i);n++,t+=4}}return t}t.encode=function(e){for(var t=new Uint8Array(o(e)),n=0,i=0;i<e.length;i++){var r=e.charCodeAt(i);r<128?t[n++]=r:r<2048?(t[n++]=192|r>>6,t[n++]=128|63&r):r<55296?(t[n++]=224|r>>12,t[n++]=128|r>>6&63,t[n++]=128|63&r):(i++,r=(1023&r)<<10,r|=1023&e.charCodeAt(i),r+=65536,t[n++]=240|r>>18,t[n++]=128|r>>12&63,t[n++]=128|r>>6&63,t[n++]=128|63&r)}return t},t.encodedLength=o,t.decode=function(e){for(var t=[],n=0;n<e.length;n++){var i=e[n];if(128&i){var o=void 0;if(i<224){if(n>=e.length)throw new Error(r);if(128!=(192&(s=e[++n])))throw new Error(r);i=(31&i)<<6|63&s,o=128}else if(i<240){if(n>=e.length-1)throw new Error(r);var s=e[++n],a=e[++n];if(128!=(192&s)||128!=(192&a))throw new Error(r);i=(15&i)<<12|(63&s)<<6|63&a,o=2048}else{if(!(i<248))throw new Error(r);if(n>=e.length-2)throw new Error(r);s=e[++n],a=e[++n];var c=e[++n];if(128!=(192&s)||128!=(192&a)||128!=(192&c))throw new Error(r);i=(15&i)<<18|(63&s)<<12|(63&a)<<6|63&c,o=65536}if(i<o||i>=55296&&i<=57343)throw new Error(r);if(i>=65536){if(i>1114111)throw new Error(r);i-=65536,t.push(String.fromCharCode(55296|i>>10)),i=56320|1023&i}}t.push(String.fromCharCode(i))}return t.join("")}},function(e,t,n){e.exports=n(3).default},function(e,t,n){n.r(t);class i{constructor(e,t){this.lastId=0,this.prefix=e,this.name=t}create(e){this.lastId++;var t=this.lastId,n=this.prefix+t,i=this.name+"["+t+"]",r=!1,o=function(){r||(e.apply(null,arguments),r=!0)};return this[t]=o,{number:t,id:n,name:i,callback:o}}remove(e){delete this[e.number]}}var r=new i("_pusher_script_","Pusher.ScriptReceivers"),o={VERSION:"8.4.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""},s=new i("_pusher_dependencies","Pusher.DependenciesReceivers"),a=new class{constructor(e){this.options=e,this.receivers=e.receivers||r,this.loading={}}load(e,t,n){var i=this;if(i.loading[e]&&i.loading[e].length>0)i.loading[e].push(n);else{i.loading[e]=[n];var r=ht.createScriptRequest(i.getPath(e,t)),o=i.receivers.create(function(t){if(i.receivers.remove(o),i.loading[e]){var n=i.loading[e];delete i.loading[e];for(var s=function(e){e||r.cleanup()},a=0;a<n.length;a++)n[a](t,s)}});r.send(o)}}getRoot(e){var t=ht.getDocument().location.protocol;return(e&&e.useTLS||"https:"===t?this.options.cdn_https:this.options.cdn_http).replace(/\/*$/,"")+"/"+this.options.version}getPath(e,t){return this.getRoot(t)+"/"+e+this.options.suffix+".js"}}({cdn_http:o.cdn_http,cdn_https:o.cdn_https,version:o.VERSION,suffix:o.dependency_suffix,receivers:s});const c={baseUrl:"https://pusher.com",urls:{authenticationEndpoint:{path:"/docs/channels/server_api/authenticating_users"},authorizationEndpoint:{path:"/docs/channels/server_api/authorizing-users/"},javascriptQuickStart:{path:"/docs/javascript_quick_start"},triggeringClientEvents:{path:"/docs/client_api_guide/client_events#trigger-events"},encryptedChannelSupport:{fullUrl:"https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support"}}};var h,l=function(e){const t=c.urls[e];if(!t)return"";let n;return t.fullUrl?n=t.fullUrl:t.path&&(n=c.baseUrl+t.path),n?`See: ${n}`:""};!function(e){e.UserAuthentication="user-authentication",e.ChannelAuthorization="channel-authorization"}(h||(h={}));class d extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class u extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class p extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class g extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class f extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class m extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class b extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class v extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class y extends Error{constructor(e,t){super(t),this.status=e,Object.setPrototypeOf(this,new.target.prototype)}}var w=function(e,t,n,i,r){const o=ht.createXHR();for(var s in o.open("POST",n.endpoint,!0),o.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),n.headers)o.setRequestHeader(s,n.headers[s]);if(null!=n.headersProvider){let e=n.headersProvider();for(var s in e)o.setRequestHeader(s,e[s])}return o.onreadystatechange=function(){if(4===o.readyState)if(200===o.status){let e,t=!1;try{e=JSON.parse(o.responseText),t=!0}catch(e){r(new y(200,`JSON returned from ${i.toString()} endpoint was invalid, yet status code was 200. Data was: ${o.responseText}`),null)}t&&r(null,e)}else{let e="";switch(i){case h.UserAuthentication:e=l("authenticationEndpoint");break;case h.ChannelAuthorization:e=`Clients must be authorized to join private or presence channels. ${l("authorizationEndpoint")}`}r(new y(o.status,`Unable to retrieve auth string from ${i.toString()} endpoint - received status: ${o.status} from ${n.endpoint}. ${e}`),null)}},o.send(t),o},S=String.fromCharCode,C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",k=function(e){var t=e.charCodeAt(0);return t<128?e:t<2048?S(192|t>>>6)+S(128|63&t):S(224|t>>>12&15)+S(128|t>>>6&63)+S(128|63&t)},_=function(e){return e.replace(/[^\x00-\x7F]/g,k)},x=function(e){var t=[0,2,1][e.length%3],n=e.charCodeAt(0)<<16|(e.length>1?e.charCodeAt(1):0)<<8|(e.length>2?e.charCodeAt(2):0);return[C.charAt(n>>>18),C.charAt(n>>>12&63),t>=2?"=":C.charAt(n>>>6&63),t>=1?"=":C.charAt(63&n)].join("")},T=window.btoa||function(e){return e.replace(/[\s\S]{1,3}/g,x)},E=class{constructor(e,t,n,i){this.clear=t,this.timer=e(()=>{this.timer&&(this.timer=i(this.timer))},n)}isRunning(){return null!==this.timer}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}};function I(e){window.clearTimeout(e)}function P(e){window.clearInterval(e)}class D extends E{constructor(e,t){super(setTimeout,I,e,function(e){return t(),null})}}class O extends E{constructor(e,t){super(setInterval,P,e,function(e){return t(),e})}}var A={now:()=>Date.now?Date.now():(new Date).valueOf(),defer:e=>new D(0,e),method(e,...t){var n=Array.prototype.slice.call(arguments,1);return function(t){return t[e].apply(t,n.concat(arguments))}}},R=A;function L(e,...t){for(var n=0;n<t.length;n++){var i=t[n];for(var r in i)i[r]&&i[r].constructor&&i[r].constructor===Object?e[r]=L(e[r]||{},i[r]):e[r]=i[r]}return e}function N(){for(var e=["Pusher"],t=0;t<arguments.length;t++)"string"==typeof arguments[t]?e.push(arguments[t]):e.push(J(arguments[t]));return e.join(" : ")}function U(e,t){var n=Array.prototype.indexOf;if(null===e)return-1;if(n&&e.indexOf===n)return e.indexOf(t);for(var i=0,r=e.length;i<r;i++)if(e[i]===t)return i;return-1}function K(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(e[n],n,e)}function j(e){var t=[];return K(e,function(e,n){t.push(n)}),t}function $(e,t,n){for(var i=0;i<e.length;i++)t.call(n||window,e[i],i,e)}function M(e,t){for(var n=[],i=0;i<e.length;i++)n.push(t(e[i],i,e,n));return n}function H(e,t){t=t||function(e){return!!e};for(var n=[],i=0;i<e.length;i++)t(e[i],i,e,n)&&n.push(e[i]);return n}function F(e,t){var n={};return K(e,function(i,r){(t&&t(i,r,e,n)||Boolean(i))&&(n[r]=i)}),n}function B(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1}function z(e){return t=function(e){return"object"==typeof e&&(e=J(e)),encodeURIComponent((t=e.toString(),T(_(t))));var t},n={},K(e,function(e,i){n[i]=t(e)}),n;var t,n}function q(e){var t,n,i=F(e,function(e){return void 0!==e});return M((t=z(i),n=[],K(t,function(e,t){n.push([t,e])}),n),R.method("join","=")).join("&")}function J(e){try{return JSON.stringify(e)}catch(i){return JSON.stringify((t=[],n=[],function e(i,r){var o,s,a;switch(typeof i){case"object":if(!i)return null;for(o=0;o<t.length;o+=1)if(t[o]===i)return{$ref:n[o]};if(t.push(i),n.push(r),"[object Array]"===Object.prototype.toString.apply(i))for(a=[],o=0;o<i.length;o+=1)a[o]=e(i[o],r+"["+o+"]");else for(s in a={},i)Object.prototype.hasOwnProperty.call(i,s)&&(a[s]=e(i[s],r+"["+JSON.stringify(s)+"]"));return a;case"number":case"string":case"boolean":return i}}(e,"$")))}var t,n}var W=new class{constructor(){this.globalLog=e=>{window.console&&window.console.log&&window.console.log(e)}}debug(...e){this.log(this.globalLog,e)}warn(...e){this.log(this.globalLogWarn,e)}error(...e){this.log(this.globalLogError,e)}globalLogWarn(e){window.console&&window.console.warn?window.console.warn(e):this.globalLog(e)}globalLogError(e){window.console&&window.console.error?window.console.error(e):this.globalLogWarn(e)}log(e,...t){var n=N.apply(this,arguments);Pt.log?Pt.log(n):Pt.logToConsole&&e.bind(this)(n)}},X=function(e,t,n,i,r){void 0===n.headers&&null==n.headersProvider||W.warn(`To send headers with the ${i.toString()} request, you must use AJAX, rather than JSONP.`);var o=e.nextAuthCallbackID.toString();e.nextAuthCallbackID++;var s=e.getDocument(),a=s.createElement("script");e.auth_callbacks[o]=function(e){r(null,e)};var c="Pusher.auth_callbacks['"+o+"']";a.src=n.endpoint+"?callback="+encodeURIComponent(c)+"&"+t;var h=s.getElementsByTagName("head")[0]||s.documentElement;h.insertBefore(a,h.firstChild)};class G{constructor(e){this.src=e}send(e){var t=this,n="Error loading "+t.src;t.script=document.createElement("script"),t.script.id=e.id,t.script.src=t.src,t.script.type="text/javascript",t.script.charset="UTF-8",t.script.addEventListener?(t.script.onerror=function(){e.callback(n)},t.script.onload=function(){e.callback(null)}):t.script.onreadystatechange=function(){"loaded"!==t.script.readyState&&"complete"!==t.script.readyState||e.callback(null)},void 0===t.script.async&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(t.errorScript=document.createElement("script"),t.errorScript.id=e.id+"_error",t.errorScript.text=e.name+"('"+n+"');",t.script.async=t.errorScript.async=!1):t.script.async=!0;var i=document.getElementsByTagName("head")[0];i.insertBefore(t.script,i.firstChild),t.errorScript&&i.insertBefore(t.errorScript,t.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class Q{constructor(e,t){this.url=e,this.data=t}send(e){if(!this.request){var t=q(this.data),n=this.url+"/"+e.number+"?"+t;this.request=ht.createScriptRequest(n),this.request.send(e)}}cleanup(){this.request&&this.request.cleanup()}}var Y={name:"jsonp",getAgent:function(e,t){return function(n,i){var o="http"+(t?"s":"")+"://"+(e.host||e.options.host)+e.options.path,s=ht.createJSONPRequest(o,n),a=ht.ScriptReceivers.create(function(t,n){r.remove(a),s.cleanup(),n&&n.host&&(e.host=n.host),i&&i(t,n)});s.send(a)}}};function V(e,t,n){return e+(t.useTLS?"s":"")+"://"+(t.useTLS?t.hostTLS:t.hostNonTLS)+n}function Z(e,t){return"/app/"+e+"?protocol="+o.PROTOCOL+"&client=js&version="+o.VERSION+(t?"&"+t:"")}var ee={getInitial:function(e,t){return V("ws",t,(t.httpPath||"")+Z(e,"flash=false"))}},te={getInitial:function(e,t){return V("http",t,(t.httpPath||"/pusher")+Z(e))}},ne={getInitial:function(e,t){return V("http",t,t.httpPath||"/pusher")},getPath:function(e,t){return Z(e)}};class ie{constructor(){this._callbacks={}}get(e){return this._callbacks[re(e)]}add(e,t,n){var i=re(e);this._callbacks[i]=this._callbacks[i]||[],this._callbacks[i].push({fn:t,context:n})}remove(e,t,n){if(e||t||n){var i=e?[re(e)]:j(this._callbacks);t||n?this.removeCallback(i,t,n):this.removeAllCallbacks(i)}else this._callbacks={}}removeCallback(e,t,n){$(e,function(e){this._callbacks[e]=H(this._callbacks[e]||[],function(e){return t&&t!==e.fn||n&&n!==e.context}),0===this._callbacks[e].length&&delete this._callbacks[e]},this)}removeAllCallbacks(e){$(e,function(e){delete this._callbacks[e]},this)}}function re(e){return"_"+e}class oe{constructor(e){this.callbacks=new ie,this.global_callbacks=[],this.failThrough=e}bind(e,t,n){return this.callbacks.add(e,t,n),this}bind_global(e){return this.global_callbacks.push(e),this}unbind(e,t,n){return this.callbacks.remove(e,t,n),this}unbind_global(e){return e?(this.global_callbacks=H(this.global_callbacks||[],t=>t!==e),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(e,t,n){for(var i=0;i<this.global_callbacks.length;i++)this.global_callbacks[i](e,t);var r=this.callbacks.get(e),o=[];if(n?o.push(t,n):t&&o.push(t),r&&r.length>0)for(i=0;i<r.length;i++)r[i].fn.apply(r[i].context||window,o);else this.failThrough&&this.failThrough(e,t);return this}}class se extends oe{constructor(e,t,n,i,r){super(),this.initialize=ht.transportConnectionInitializer,this.hooks=e,this.name=t,this.priority=n,this.key=i,this.options=r,this.state="new",this.timeline=r.timeline,this.activityTimeout=r.activityTimeout,this.id=this.timeline.generateUniqueID()}handlesActivityChecks(){return Boolean(this.hooks.handlesActivityChecks)}supportsPing(){return Boolean(this.hooks.supportsPing)}connect(){if(this.socket||"initialized"!==this.state)return!1;var e=this.hooks.urls.getInitial(this.key,this.options);try{this.socket=this.hooks.getSocket(e,this.options)}catch(e){return R.defer(()=>{this.onError(e),this.changeState("closed")}),!1}return this.bindListeners(),W.debug("Connecting",{transport:this.name,url:e}),this.changeState("connecting"),!0}close(){return!!this.socket&&(this.socket.close(),!0)}send(e){return"open"===this.state&&(R.defer(()=>{this.socket&&this.socket.send(e)}),!0)}ping(){"open"===this.state&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(e){this.emit("error",{type:"WebSocketError",error:e}),this.timeline.error(this.buildTimelineMessage({error:e.toString()}))}onClose(e){e?this.changeState("closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(e){this.emit("message",e)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=e=>{this.onError(e)},this.socket.onclose=e=>{this.onClose(e)},this.socket.onmessage=e=>{this.onMessage(e)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(e,t){this.state=e,this.timeline.info(this.buildTimelineMessage({state:e,params:t})),this.emit(e,t)}buildTimelineMessage(e){return L({cid:this.id},e)}}class ae{constructor(e){this.hooks=e}isSupported(e){return this.hooks.isSupported(e)}createConnection(e,t,n,i){return new se(this.hooks,e,t,n,i)}}var ce=new ae({urls:ee,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return Boolean(ht.getWebSocketAPI())},isSupported:function(){return Boolean(ht.getWebSocketAPI())},getSocket:function(e){return ht.createWebSocket(e)}}),he={urls:te,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},le=L({getSocket:function(e){return ht.HTTPFactory.createStreamingSocket(e)}},he),de=L({getSocket:function(e){return ht.HTTPFactory.createPollingSocket(e)}},he),ue={isSupported:function(){return ht.isXHRSupported()}},pe={ws:ce,xhr_streaming:new ae(L({},le,ue)),xhr_polling:new ae(L({},de,ue))},ge=new ae({file:"sockjs",urls:ne,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return void 0!==window.SockJS},getSocket:function(e,t){return new window.SockJS(e,null,{js_path:a.getPath("sockjs",{useTLS:t.useTLS}),ignore_null_origin:t.ignoreNullOrigin})},beforeOpen:function(e,t){e.send(JSON.stringify({path:t}))}}),fe={isSupported:function(e){return ht.isXDRSupported(e.useTLS)}},me=new ae(L({},le,fe)),be=new ae(L({},de,fe));pe.xdr_streaming=me,pe.xdr_polling=be,pe.sockjs=ge;var ve=pe,ye=new class extends oe{constructor(){super();var e=this;void 0!==window.addEventListener&&(window.addEventListener("online",function(){e.emit("online")},!1),window.addEventListener("offline",function(){e.emit("offline")},!1))}isOnline(){return void 0===window.navigator.onLine||window.navigator.onLine}};class we{constructor(e,t,n){this.manager=e,this.transport=t,this.minPingDelay=n.minPingDelay,this.maxPingDelay=n.maxPingDelay,this.pingDelay=void 0}createConnection(e,t,n,i){i=L({},i,{activityTimeout:this.pingDelay});var r=this.transport.createConnection(e,t,n,i),o=null,s=function(){r.unbind("open",s),r.bind("closed",a),o=R.now()},a=e=>{if(r.unbind("closed",a),1002===e.code||1003===e.code)this.manager.reportDeath();else if(!e.wasClean&&o){var t=R.now()-o;t<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(t/2,this.minPingDelay))}};return r.bind("open",s),r}isSupported(e){return this.manager.isAlive()&&this.transport.isSupported(e)}}const Se={decodeMessage:function(e){try{var t=JSON.parse(e.data),n=t.data;if("string"==typeof n)try{n=JSON.parse(t.data)}catch(e){}var i={event:t.event,channel:t.channel,data:n};return t.user_id&&(i.user_id=t.user_id),i}catch(t){throw{type:"MessageParseError",error:t,data:e.data}}},encodeMessage:function(e){return JSON.stringify(e)},processHandshake:function(e){var t=Se.decodeMessage(e);if("pusher:connection_established"===t.event){if(!t.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:t.data.socket_id,activityTimeout:1e3*t.data.activity_timeout}}if("pusher:error"===t.event)return{action:this.getCloseAction(t.data),error:this.getCloseError(t.data)};throw"Invalid handshake"},getCloseAction:function(e){return e.code<4e3?e.code>=1002&&e.code<=1004?"backoff":null:4e3===e.code?"tls_only":e.code<4100?"refused":e.code<4200?"backoff":e.code<4300?"retry":"refused"},getCloseError:function(e){return 1e3!==e.code&&1001!==e.code?{type:"PusherError",data:{code:e.code,message:e.reason||e.message}}:null}};var Ce=Se;class ke extends oe{constructor(e,t){super(),this.id=e,this.transport=t,this.activityTimeout=t.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(e){return this.transport.send(e)}send_event(e,t,n){var i={event:e,data:t};return n&&(i.channel=n),W.debug("Event sent",i),this.send(Ce.encodeMessage(i))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var e={message:e=>{var t;try{t=Ce.decodeMessage(e)}catch(t){this.emit("error",{type:"MessageParseError",error:t,data:e.data})}if(void 0!==t){switch(W.debug("Event recd",t),t.event){case"pusher:error":this.emit("error",{type:"PusherError",data:t.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong")}this.emit("message",t)}},activity:()=>{this.emit("activity")},error:e=>{this.emit("error",e)},closed:e=>{t(),e&&e.code&&this.handleCloseEvent(e),this.transport=null,this.emit("closed")}},t=()=>{K(e,(e,t)=>{this.transport.unbind(t,e)})};K(e,(e,t)=>{this.transport.bind(t,e)})}handleCloseEvent(e){var t=Ce.getCloseAction(e),n=Ce.getCloseError(e);n&&this.emit("error",n),t&&this.emit(t,{action:t,error:n})}}class _e{constructor(e,t){this.transport=e,this.callback=t,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=e=>{var t;this.unbindListeners();try{t=Ce.processHandshake(e)}catch(e){return this.finish("error",{error:e}),void this.transport.close()}"connected"===t.action?this.finish("connected",{connection:new ke(t.id,this.transport),activityTimeout:t.activityTimeout}):(this.finish(t.action,{error:t.error}),this.transport.close())},this.onClosed=e=>{this.unbindListeners();var t=Ce.getCloseAction(e)||"backoff",n=Ce.getCloseError(e);this.finish(t,{error:n})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(e,t){this.callback(L({transport:this.transport,action:e},t))}}class xe{constructor(e,t){this.timeline=e,this.options=t||{}}send(e,t){this.timeline.isEmpty()||this.timeline.send(ht.TimelineTransport.getAgent(this,e),t)}}class Te extends oe{constructor(e,t){super(function(t,n){W.debug("No callbacks on "+e+" for "+t)}),this.name=e,this.pusher=t,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(e,t){return t(null,{auth:""})}trigger(e,t){if(0!==e.indexOf("client-"))throw new d("Event '"+e+"' does not start with 'client-'");if(!this.subscribed){var n=l("triggeringClientEvents");W.warn(`Client event triggered before channel 'subscription_succeeded' event . ${n}`)}return this.pusher.send_event(e,t,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(e){var t=e.event,n=e.data;"pusher_internal:subscription_succeeded"===t?this.handleSubscriptionSucceededEvent(e):"pusher_internal:subscription_count"===t?this.handleSubscriptionCountEvent(e):0!==t.indexOf("pusher_internal:")&&this.emit(t,n,{})}handleSubscriptionSucceededEvent(e){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",e.data)}handleSubscriptionCountEvent(e){e.data.subscription_count&&(this.subscriptionCount=e.data.subscription_count),this.emit("pusher:subscription_count",e.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(e,t)=>{e?(this.subscriptionPending=!1,W.error(e.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:e.message},e instanceof y?{status:e.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:t.auth,channel_data:t.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class Ee extends Te{authorize(e,t){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:e},t)}}class Ie{constructor(){this.reset()}get(e){return Object.prototype.hasOwnProperty.call(this.members,e)?{id:e,info:this.members[e]}:null}each(e){K(this.members,(t,n)=>{e(this.get(n))})}setMyID(e){this.myID=e}onSubscription(e){this.members=e.presence.hash,this.count=e.presence.count,this.me=this.get(this.myID)}addMember(e){return null===this.get(e.user_id)&&this.count++,this.members[e.user_id]=e.user_info,this.get(e.user_id)}removeMember(e){var t=this.get(e.user_id);return t&&(delete this.members[e.user_id],this.count--),t}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Pe=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}c((i=i.apply(e,t||[])).next())})};class De extends Ee{constructor(e,t){super(e,t),this.members=new Ie}authorize(e,t){super.authorize(e,(e,n)=>Pe(this,void 0,void 0,function*(){if(!e)if(null!=n.channel_data){var i=JSON.parse(n.channel_data);this.members.setMyID(i.user_id)}else{if(yield this.pusher.user.signinDonePromise,null==this.pusher.user.user_data){let e=l("authorizationEndpoint");return W.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${e}, or the user should be signed in.`),void t("Invalid auth response")}this.members.setMyID(this.pusher.user.user_data.id)}t(e,n)}))}handleEvent(e){var t=e.event;if(0===t.indexOf("pusher_internal:"))this.handleInternalEvent(e);else{var n=e.data,i={};e.user_id&&(i.user_id=e.user_id),this.emit(t,n,i)}}handleInternalEvent(e){var t=e.event,n=e.data;switch(t){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(e);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(e);break;case"pusher_internal:member_added":var i=this.members.addMember(n);this.emit("pusher:member_added",i);break;case"pusher_internal:member_removed":var r=this.members.removeMember(n);r&&this.emit("pusher:member_removed",r)}}handleSubscriptionSucceededEvent(e){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(e.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Oe=n(1),Ae=n(0);class Re extends Ee{constructor(e,t,n){super(e,t),this.key=null,this.nacl=n}authorize(e,t){super.authorize(e,(e,n)=>{if(e)return void t(e,n);let i=n.shared_secret;i?(this.key=Object(Ae.decode)(i),delete n.shared_secret,t(null,n)):t(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null)})}trigger(e,t){throw new m("Client events are not currently supported for encrypted channels")}handleEvent(e){var t=e.event,n=e.data;0!==t.indexOf("pusher_internal:")&&0!==t.indexOf("pusher:")?this.handleEncryptedEvent(t,n):super.handleEvent(e)}handleEncryptedEvent(e,t){if(!this.key)return void W.debug("Received encrypted event before key has been retrieved from the authEndpoint");if(!t.ciphertext||!t.nonce)return void W.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+t);let n=Object(Ae.decode)(t.ciphertext);if(n.length<this.nacl.secretbox.overheadLength)return void W.error(`Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${n.length}`);let i=Object(Ae.decode)(t.nonce);if(i.length<this.nacl.secretbox.nonceLength)return void W.error(`Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${i.length}`);let r=this.nacl.secretbox.open(n,i,this.key);if(null===r)return W.debug("Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint..."),void this.authorize(this.pusher.connection.socket_id,(t,o)=>{t?W.error(`Failed to make a request to the authEndpoint: ${o}. Unable to fetch new key, so dropping encrypted event`):(r=this.nacl.secretbox.open(n,i,this.key),null!==r?this.emit(e,this.getDataToEmit(r)):W.error("Failed to decrypt event with new key. Dropping encrypted event"))});this.emit(e,this.getDataToEmit(r))}getDataToEmit(e){let t=Object(Oe.decode)(e);try{return JSON.parse(t)}catch(e){return t}}}class Le extends oe{constructor(e,t){super(),this.state="initialized",this.connection=null,this.key=e,this.options=t,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var n=ht.getNetwork();n.bind("online",()=>{this.timeline.info({netinfo:"online"}),"connecting"!==this.state&&"unavailable"!==this.state||this.retryIn(0)}),n.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}connect(){this.connection||this.runner||(this.strategy.isSupported()?(this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()):this.updateState("failed"))}send(e){return!!this.connection&&this.connection.send(e)}send_event(e,t,n){return!!this.connection&&this.connection.send_event(e,t,n)}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var e=(t,n)=>{t?this.runner=this.strategy.connect(0,e):"error"===n.action?(this.emit("error",{type:"HandshakeError",error:n.error}),this.timeline.error({handshakeError:n.error})):(this.abortConnecting(),this.handshakeCallbacks[n.action](n))};this.runner=this.strategy.connect(0,e)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection&&this.abandonConnection().close()}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(e){this.timeline.info({action:"retry",delay:e}),e>0&&this.emit("connecting_in",Math.round(e/1e3)),this.retryTimer=new D(e||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new D(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new D(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new D(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(e){return L({},e,{message:e=>{this.resetActivityCheck(),this.emit("message",e)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:e=>{this.emit("error",e)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(e){return L({},e,{connected:e=>{this.activityTimeout=Math.min(this.options.activityTimeout,e.activityTimeout,e.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(e.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let e=e=>t=>{t.error&&this.emit("error",{type:"WebSocketError",error:t.error}),e(t)};return{tls_only:e(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:e(()=>{this.disconnect()}),backoff:e(()=>{this.retryIn(1e3)}),retry:e(()=>{this.retryIn(0)})}}setConnection(e){for(var t in this.connection=e,this.connectionCallbacks)this.connection.bind(t,this.connectionCallbacks[t]);this.resetActivityCheck()}abandonConnection(){if(this.connection){for(var e in this.stopActivityCheck(),this.connectionCallbacks)this.connection.unbind(e,this.connectionCallbacks[e]);var t=this.connection;return this.connection=null,t}}updateState(e,t){var n=this.state;if(this.state=e,n!==e){var i=e;"connected"===i&&(i+=" with new socket ID "+t.socket_id),W.debug("State changed",n+" -> "+i),this.timeline.info({state:e,params:t}),this.emit("state_change",{previous:n,current:e}),this.emit(e,t)}}shouldRetry(){return"connecting"===this.state||"connected"===this.state}}class Ne{constructor(){this.channels={}}add(e,t){return this.channels[e]||(this.channels[e]=function(e,t){if(0===e.indexOf("private-encrypted-")){if(t.config.nacl)return Ke.createEncryptedChannel(e,t,t.config.nacl);let n="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",i=l("encryptedChannelSupport");throw new m(`${n}. ${i}`)}if(0===e.indexOf("private-"))return Ke.createPrivateChannel(e,t);if(0===e.indexOf("presence-"))return Ke.createPresenceChannel(e,t);if(0===e.indexOf("#"))throw new u('Cannot create a channel with name "'+e+'".');return Ke.createChannel(e,t)}(e,t)),this.channels[e]}all(){return function(e){var t=[];return K(e,function(e){t.push(e)}),t}(this.channels)}find(e){return this.channels[e]}remove(e){var t=this.channels[e];return delete this.channels[e],t}disconnect(){K(this.channels,function(e){e.disconnect()})}}var Ue={createChannels:()=>new Ne,createConnectionManager:(e,t)=>new Le(e,t),createChannel:(e,t)=>new Te(e,t),createPrivateChannel:(e,t)=>new Ee(e,t),createPresenceChannel:(e,t)=>new De(e,t),createEncryptedChannel:(e,t,n)=>new Re(e,t,n),createTimelineSender:(e,t)=>new xe(e,t),createHandshake:(e,t)=>new _e(e,t),createAssistantToTheTransportManager:(e,t,n)=>new we(e,t,n)},Ke=Ue;class je{constructor(e){this.options=e||{},this.livesLeft=this.options.lives||1/0}getAssistant(e){return Ke.createAssistantToTheTransportManager(this,e,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class $e{constructor(e,t){this.strategies=e,this.loop=Boolean(t.loop),this.failFast=Boolean(t.failFast),this.timeout=t.timeout,this.timeoutLimit=t.timeoutLimit}isSupported(){return B(this.strategies,R.method("isSupported"))}connect(e,t){var n=this.strategies,i=0,r=this.timeout,o=null,s=(a,c)=>{c?t(null,c):(i+=1,this.loop&&(i%=n.length),i<n.length?(r&&(r*=2,this.timeoutLimit&&(r=Math.min(r,this.timeoutLimit))),o=this.tryStrategy(n[i],e,{timeout:r,failFast:this.failFast},s)):t(!0))};return o=this.tryStrategy(n[i],e,{timeout:r,failFast:this.failFast},s),{abort:function(){o.abort()},forceMinPriority:function(t){e=t,o&&o.forceMinPriority(t)}}}tryStrategy(e,t,n,i){var r=null,o=null;return n.timeout>0&&(r=new D(n.timeout,function(){o.abort(),i(!0)})),o=e.connect(t,function(e,t){e&&r&&r.isRunning()&&!n.failFast||(r&&r.ensureAborted(),i(e,t))}),{abort:function(){r&&r.ensureAborted(),o.abort()},forceMinPriority:function(e){o.forceMinPriority(e)}}}}class Me{constructor(e){this.strategies=e}isSupported(){return B(this.strategies,R.method("isSupported"))}connect(e,t){return function(e,t,n){var i=M(e,function(e,i,r,o){return e.connect(t,n(i,o))});return{abort:function(){$(i,He)},forceMinPriority:function(e){$(i,function(t){t.forceMinPriority(e)})}}}(this.strategies,e,function(e,n){return function(i,r){n[e].error=i,i?function(e){return function(e,t){for(var n=0;n<e.length;n++)if(!t(e[n],n,e))return!1;return!0}(e,function(e){return Boolean(e.error)})}(n)&&t(!0):($(n,function(e){e.forceMinPriority(r.transport.priority)}),t(null,r))}})}}function He(e){e.error||e.aborted||(e.abort(),e.aborted=!0)}class Fe{constructor(e,t,n){this.strategy=e,this.transports=t,this.ttl=n.ttl||18e5,this.usingTLS=n.useTLS,this.timeline=n.timeline}isSupported(){return this.strategy.isSupported()}connect(e,t){var n=this.usingTLS,i=function(e){var t=ht.getLocalStorage();if(t)try{var n=t[Be(e)];if(n)return JSON.parse(n)}catch(t){ze(e)}return null}(n),r=i&&i.cacheSkipCount?i.cacheSkipCount:0,o=[this.strategy];if(i&&i.timestamp+this.ttl>=R.now()){var s=this.transports[i.transport];s&&(["ws","wss"].includes(i.transport)||r>3?(this.timeline.info({cached:!0,transport:i.transport,latency:i.latency}),o.push(new $e([s],{timeout:2*i.latency+1e3,failFast:!0}))):r++)}var a=R.now(),c=o.pop().connect(e,function i(s,h){s?(ze(n),o.length>0?(a=R.now(),c=o.pop().connect(e,i)):t(s)):(function(e,t,n,i){var r=ht.getLocalStorage();if(r)try{r[Be(e)]=J({timestamp:R.now(),transport:t,latency:n,cacheSkipCount:i})}catch(e){}}(n,h.transport.name,R.now()-a,r),t(null,h))});return{abort:function(){c.abort()},forceMinPriority:function(t){e=t,c&&c.forceMinPriority(t)}}}}function Be(e){return"pusherTransport"+(e?"TLS":"NonTLS")}function ze(e){var t=ht.getLocalStorage();if(t)try{delete t[Be(e)]}catch(e){}}class qe{constructor(e,{delay:t}){this.strategy=e,this.options={delay:t}}isSupported(){return this.strategy.isSupported()}connect(e,t){var n,i=this.strategy,r=new D(this.options.delay,function(){n=i.connect(e,t)});return{abort:function(){r.ensureAborted(),n&&n.abort()},forceMinPriority:function(t){e=t,n&&n.forceMinPriority(t)}}}}class Je{constructor(e,t,n){this.test=e,this.trueBranch=t,this.falseBranch=n}isSupported(){return(this.test()?this.trueBranch:this.falseBranch).isSupported()}connect(e,t){return(this.test()?this.trueBranch:this.falseBranch).connect(e,t)}}class We{constructor(e){this.strategy=e}isSupported(){return this.strategy.isSupported()}connect(e,t){var n=this.strategy.connect(e,function(e,i){i&&n.abort(),t(e,i)});return n}}function Xe(e){return function(){return e.isSupported()}}var Ge,Qe=function(e,t,n){var i={};function r(t,r,o,s,a){var c=n(e,t,r,o,s,a);return i[t]=c,c}var o,s=Object.assign({},t,{hostNonTLS:e.wsHost+":"+e.wsPort,hostTLS:e.wsHost+":"+e.wssPort,httpPath:e.wsPath}),a=Object.assign({},s,{useTLS:!0}),c=Object.assign({},t,{hostNonTLS:e.httpHost+":"+e.httpPort,hostTLS:e.httpHost+":"+e.httpsPort,httpPath:e.httpPath}),h={loop:!0,timeout:15e3,timeoutLimit:6e4},l=new je({minPingDelay:1e4,maxPingDelay:e.activityTimeout}),d=new je({lives:2,minPingDelay:1e4,maxPingDelay:e.activityTimeout}),u=r("ws","ws",3,s,l),p=r("wss","ws",3,a,l),g=r("sockjs","sockjs",1,c),f=r("xhr_streaming","xhr_streaming",1,c,d),m=r("xdr_streaming","xdr_streaming",1,c,d),b=r("xhr_polling","xhr_polling",1,c),v=r("xdr_polling","xdr_polling",1,c),y=new $e([u],h),w=new $e([p],h),S=new $e([g],h),C=new $e([new Je(Xe(f),f,m)],h),k=new $e([new Je(Xe(b),b,v)],h),_=new $e([new Je(Xe(C),new Me([C,new qe(k,{delay:4e3})]),k)],h),x=new Je(Xe(_),_,S);return o=t.useTLS?new Me([y,new qe(x,{delay:2e3})]):new Me([y,new qe(w,{delay:2e3}),new qe(x,{delay:5e3})]),new Fe(new We(new Je(Xe(u),o,x)),i,{ttl:18e5,timeline:t.timeline,useTLS:t.useTLS})},Ye={getRequest:function(e){var t=new window.XDomainRequest;return t.ontimeout=function(){e.emit("error",new p),e.close()},t.onerror=function(t){e.emit("error",t),e.close()},t.onprogress=function(){t.responseText&&t.responseText.length>0&&e.onChunk(200,t.responseText)},t.onload=function(){t.responseText&&t.responseText.length>0&&e.onChunk(200,t.responseText),e.emit("finished",200),e.close()},t},abortRequest:function(e){e.ontimeout=e.onerror=e.onprogress=e.onload=null,e.abort()}};class Ve extends oe{constructor(e,t,n){super(),this.hooks=e,this.method=t,this.url=n}start(e){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},ht.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(e)}close(){this.unloader&&(ht.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(e,t){for(;;){var n=this.advanceBuffer(t);if(!n)break;this.emit("chunk",{status:e,data:n})}this.isBufferTooLong(t)&&this.emit("buffer_too_long")}advanceBuffer(e){var t=e.slice(this.position),n=t.indexOf("\n");return-1!==n?(this.position+=n+1,t.slice(0,n)):null}isBufferTooLong(e){return this.position===e.length&&e.length>262144}}!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.OPEN=1]="OPEN",e[e.CLOSED=3]="CLOSED"}(Ge||(Ge={}));var Ze=Ge,et=1;function tt(e){var t=-1===e.indexOf("?")?"?":"&";return e+t+"t="+ +new Date+"&n="+et++}function nt(e){return ht.randomInt(e)}var it,rt=class{constructor(e,t){this.hooks=e,this.session=nt(1e3)+"/"+function(e){for(var t=[],n=0;n<e;n++)t.push(nt(32).toString(32));return t.join("")}(8),this.location=function(e){var t=/([^\?]*)\/*(\??.*)/.exec(e);return{base:t[1],queryString:t[2]}}(t),this.readyState=Ze.CONNECTING,this.openStream()}send(e){return this.sendRaw(JSON.stringify([e]))}ping(){this.hooks.sendHeartbeat(this)}close(e,t){this.onClose(e,t,!0)}sendRaw(e){if(this.readyState!==Ze.OPEN)return!1;try{return ht.createSocketRequest("POST",tt((t=this.location,n=this.session,t.base+"/"+n+"/xhr_send"))).start(e),!0}catch(e){return!1}var t,n}reconnect(){this.closeStream(),this.openStream()}onClose(e,t,n){this.closeStream(),this.readyState=Ze.CLOSED,this.onclose&&this.onclose({code:e,reason:t,wasClean:n})}onChunk(e){var t;if(200===e.status)switch(this.readyState===Ze.OPEN&&this.onActivity(),e.data.slice(0,1)){case"o":t=JSON.parse(e.data.slice(1)||"{}"),this.onOpen(t);break;case"a":t=JSON.parse(e.data.slice(1)||"[]");for(var n=0;n<t.length;n++)this.onEvent(t[n]);break;case"m":t=JSON.parse(e.data.slice(1)||"null"),this.onEvent(t);break;case"h":this.hooks.onHeartbeat(this);break;case"c":t=JSON.parse(e.data.slice(1)||"[]"),this.onClose(t[0],t[1],!0)}}onOpen(e){var t,n,i;this.readyState===Ze.CONNECTING?(e&&e.hostname&&(this.location.base=(t=this.location.base,n=e.hostname,(i=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(t))[1]+n+i[3])),this.readyState=Ze.OPEN,this.onopen&&this.onopen()):this.onClose(1006,"Server lost session",!0)}onEvent(e){this.readyState===Ze.OPEN&&this.onmessage&&this.onmessage({data:e})}onActivity(){this.onactivity&&this.onactivity()}onError(e){this.onerror&&this.onerror(e)}openStream(){this.stream=ht.createSocketRequest("POST",tt(this.hooks.getReceiveURL(this.location,this.session))),this.stream.bind("chunk",e=>{this.onChunk(e)}),this.stream.bind("finished",e=>{this.hooks.onFinished(this,e)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(e){R.defer(()=>{this.onError(e),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}},ot={getReceiveURL:function(e,t){return e.base+"/"+t+"/xhr_streaming"+e.queryString},onHeartbeat:function(e){e.sendRaw("[]")},sendHeartbeat:function(e){e.sendRaw("[]")},onFinished:function(e,t){e.onClose(1006,"Connection interrupted ("+t+")",!1)}},st={getReceiveURL:function(e,t){return e.base+"/"+t+"/xhr"+e.queryString},onHeartbeat:function(){},sendHeartbeat:function(e){e.sendRaw("[]")},onFinished:function(e,t){200===t?e.reconnect():e.onClose(1006,"Connection interrupted ("+t+")",!1)}},at={getRequest:function(e){var t=new(ht.getXHRAPI());return t.onreadystatechange=t.onprogress=function(){switch(t.readyState){case 3:t.responseText&&t.responseText.length>0&&e.onChunk(t.status,t.responseText);break;case 4:t.responseText&&t.responseText.length>0&&e.onChunk(t.status,t.responseText),e.emit("finished",t.status),e.close()}},t},abortRequest:function(e){e.onreadystatechange=null,e.abort()}},ct={createStreamingSocket(e){return this.createSocket(ot,e)},createPollingSocket(e){return this.createSocket(st,e)},createSocket:(e,t)=>new rt(e,t),createXHR(e,t){return this.createRequest(at,e,t)},createRequest:(e,t,n)=>new Ve(e,t,n),createXDR:function(e,t){return this.createRequest(Ye,e,t)}},ht={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:r,DependenciesReceivers:s,getDefaultStrategy:Qe,Transports:ve,transportConnectionInitializer:function(){var e=this;e.timeline.info(e.buildTimelineMessage({transport:e.name+(e.options.useTLS?"s":"")})),e.hooks.isInitialized()?e.changeState("initialized"):e.hooks.file?(e.changeState("initializing"),a.load(e.hooks.file,{useTLS:e.options.useTLS},function(t,n){e.hooks.isInitialized()?(e.changeState("initialized"),n(!0)):(t&&e.onError(t),e.onClose(),n(!1))})):e.onClose()},HTTPFactory:ct,TimelineTransport:Y,getXHRAPI:()=>window.XMLHttpRequest,getWebSocketAPI:()=>window.WebSocket||window.MozWebSocket,setup(e){window.Pusher=e;var t=()=>{this.onDocumentBody(e.ready)};window.JSON?t():a.load("json2",{},t)},getDocument:()=>document,getProtocol(){return this.getDocument().location.protocol},getAuthorizers:()=>({ajax:w,jsonp:X}),onDocumentBody(e){document.body?e():setTimeout(()=>{this.onDocumentBody(e)},0)},createJSONPRequest:(e,t)=>new Q(e,t),createScriptRequest:e=>new G(e),getLocalStorage(){try{return window.localStorage}catch(e){return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){return new(this.getXHRAPI())},createMicrosoftXHR:()=>new ActiveXObject("Microsoft.XMLHTTP"),getNetwork:()=>ye,createWebSocket(e){return new(this.getWebSocketAPI())(e)},createSocketRequest(e,t){if(this.isXHRSupported())return this.HTTPFactory.createXHR(e,t);if(this.isXDRSupported(0===t.indexOf("https:")))return this.HTTPFactory.createXDR(e,t);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var e=this.getXHRAPI();return Boolean(e)&&void 0!==(new e).withCredentials},isXDRSupported(e){var t=e?"https:":"http:",n=this.getProtocol();return Boolean(window.XDomainRequest)&&n===t},addUnloadListener(e){void 0!==window.addEventListener?window.addEventListener("unload",e,!1):void 0!==window.attachEvent&&window.attachEvent("onunload",e)},removeUnloadListener(e){void 0!==window.addEventListener?window.removeEventListener("unload",e,!1):void 0!==window.detachEvent&&window.detachEvent("onunload",e)},randomInt:e=>Math.floor((window.crypto||window.msCrypto).getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)*e)};!function(e){e[e.ERROR=3]="ERROR",e[e.INFO=6]="INFO",e[e.DEBUG=7]="DEBUG"}(it||(it={}));var lt=it;class dt{constructor(e,t,n){this.key=e,this.session=t,this.events=[],this.options=n||{},this.sent=0,this.uniqueID=0}log(e,t){e<=this.options.level&&(this.events.push(L({},t,{timestamp:R.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(e){this.log(lt.ERROR,e)}info(e){this.log(lt.INFO,e)}debug(e){this.log(lt.DEBUG,e)}isEmpty(){return 0===this.events.length}send(e,t){var n=L({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],e(n,(e,n)=>{e||this.sent++,t&&t(e,n)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class ut{constructor(e,t,n,i){this.name=e,this.priority=t,this.transport=n,this.options=i||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(e,t){if(!this.isSupported())return pt(new v,t);if(this.priority<e)return pt(new g,t);var n=!1,i=this.transport.createConnection(this.name,this.priority,this.options.key,this.options),r=null,o=function(){i.unbind("initialized",o),i.connect()},s=function(){r=Ke.createHandshake(i,function(e){n=!0,h(),t(null,e)})},a=function(e){h(),t(e)},c=function(){var e;h(),e=J(i),t(new f(e))},h=function(){i.unbind("initialized",o),i.unbind("open",s),i.unbind("error",a),i.unbind("closed",c)};return i.bind("initialized",o),i.bind("open",s),i.bind("error",a),i.bind("closed",c),i.initialize(),{abort:()=>{n||(h(),r?r.close():i.close())},forceMinPriority:e=>{n||this.priority<e&&(r?r.close():i.close())}}}}function pt(e,t){return R.defer(function(){t(e)}),{abort:function(){},forceMinPriority:function(){}}}const{Transports:gt}=ht;var ft=function(e,t,n,i,r,o){var s,a=gt[n];if(!a)throw new b(n);return e.enabledTransports&&-1===U(e.enabledTransports,t)||e.disabledTransports&&-1!==U(e.disabledTransports,t)?s=mt:(r=Object.assign({ignoreNullOrigin:e.ignoreNullOrigin},r),s=new ut(t,i,o?o.getAssistant(a):a,r)),s},mt={isSupported:function(){return!1},connect:function(e,t){var n=R.defer(function(){t(new v)});return{abort:function(){n.ensureAborted()},forceMinPriority:function(){}}}},bt=e=>{if(void 0===ht.getAuthorizers()[e.transport])throw`'${e.transport}' is not a recognized auth transport`;return(t,n)=>{const i=((e,t)=>{var n="socket_id="+encodeURIComponent(e.socketId);for(var i in t.params)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(t.params[i]);if(null!=t.paramsProvider){let e=t.paramsProvider();for(var i in e)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(e[i])}return n})(t,e);ht.getAuthorizers()[e.transport](ht,i,e,h.UserAuthentication,n)}},vt=e=>{if(void 0===ht.getAuthorizers()[e.transport])throw`'${e.transport}' is not a recognized auth transport`;return(t,n)=>{const i=((e,t)=>{var n="socket_id="+encodeURIComponent(e.socketId);for(var i in n+="&channel_name="+encodeURIComponent(e.channelName),t.params)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(t.params[i]);if(null!=t.paramsProvider){let e=t.paramsProvider();for(var i in e)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(e[i])}return n})(t,e);ht.getAuthorizers()[e.transport](ht,i,e,h.ChannelAuthorization,n)}};function yt(e){return e.httpHost?e.httpHost:e.cluster?`sockjs-${e.cluster}.pusher.com`:o.httpHost}function wt(e){return e.wsHost?e.wsHost:`ws-${e.cluster}.pusher.com`}function St(e){return"https:"===ht.getProtocol()||!1!==e.forceTLS}function Ct(e){return"enableStats"in e?e.enableStats:"disableStats"in e&&!e.disableStats}function kt(e){const t=Object.assign(Object.assign({},o.userAuthentication),e.userAuthentication);return"customHandler"in t&&null!=t.customHandler?t.customHandler:bt(t)}function _t(e,t){const n=function(e,t){let n;return"channelAuthorization"in e?n=Object.assign(Object.assign({},o.channelAuthorization),e.channelAuthorization):(n={transport:e.authTransport||o.authTransport,endpoint:e.authEndpoint||o.authEndpoint},"auth"in e&&("params"in e.auth&&(n.params=e.auth.params),"headers"in e.auth&&(n.headers=e.auth.headers)),"authorizer"in e&&(n.customHandler=((e,t,n)=>{const i={authTransport:t.transport,authEndpoint:t.endpoint,auth:{params:t.params,headers:t.headers}};return(t,r)=>{const o=e.channel(t.channelName);n(o,i).authorize(t.socketId,r)}})(t,n,e.authorizer))),n}(e,t);return"customHandler"in n&&null!=n.customHandler?n.customHandler:vt(n)}class xt extends oe{constructor(e){super(function(e,t){W.debug(`No callbacks on watchlist events for ${e}`)}),this.pusher=e,this.bindWatchlistInternalEvent()}handleEvent(e){e.data.events.forEach(e=>{this.emit(e.name,e)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",e=>{"pusher_internal:watchlist_events"===e.event&&this.handleEvent(e)})}}var Tt=function(){let e,t;return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}};class Et extends oe{constructor(e){super(function(e,t){W.debug("No callbacks on user for "+e)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(e,t)=>{if(e)return W.warn(`Error during signin: ${e}`),void this._cleanup();this.pusher.send_event("pusher:signin",{auth:t.auth,user_data:t.user_data})},this.pusher=e,this.pusher.connection.bind("state_change",({previous:e,current:t})=>{"connected"!==e&&"connected"===t&&this._signin(),"connected"===e&&"connected"!==t&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new xt(e),this.pusher.connection.bind("message",e=>{"pusher:signin_success"===e.event&&this._onSigninSuccess(e.data),this.serverToUserChannel&&this.serverToUserChannel.name===e.channel&&this.serverToUserChannel.handleEvent(e)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),"connected"===this.pusher.connection.state&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(e){try{this.user_data=JSON.parse(e.user_data)}catch(t){return W.error(`Failed parsing user data after signin: ${e.user_data}`),void this._cleanup()}if("string"!=typeof this.user_data.id||""===this.user_data.id)return W.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),void this._cleanup();this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){this.serverToUserChannel=new Te(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((e,t)=>{0!==e.indexOf("pusher_internal:")&&0!==e.indexOf("pusher:")&&this.emit(e,t)}),(e=>{e.subscriptionPending&&e.subscriptionCancelled?e.reinstateSubscription():e.subscriptionPending||"connected"!==this.pusher.connection.state||e.subscribe()})(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested)return;if(this.signinDonePromise&&!this.signinDonePromise.done)return;const{promise:e,resolve:t}=Tt();e.done=!1;const n=()=>{e.done=!0};e.then(n).catch(n),this.signinDonePromise=e,this._signinDoneResolve=t}}class It{static ready(){It.isReady=!0;for(var e=0,t=It.instances.length;e<t;e++)It.instances[e].connect()}static getClientFeatures(){return j(F({ws:ht.Transports.ws},function(e){return e.isSupported({})}))}constructor(e,t){!function(e){if(null==e)throw"You must pass your app key when you instantiate Pusher."}(e),function(e){if(null==e)throw"You must pass an options object";if(null==e.cluster)throw"Options object must provide a cluster";"disableStats"in e&&W.warn("The disableStats option is deprecated in favor of enableStats")}(t),this.key=e,this.config=function(e,t){let n={activityTimeout:e.activityTimeout||o.activityTimeout,cluster:e.cluster,httpPath:e.httpPath||o.httpPath,httpPort:e.httpPort||o.httpPort,httpsPort:e.httpsPort||o.httpsPort,pongTimeout:e.pongTimeout||o.pongTimeout,statsHost:e.statsHost||o.stats_host,unavailableTimeout:e.unavailableTimeout||o.unavailableTimeout,wsPath:e.wsPath||o.wsPath,wsPort:e.wsPort||o.wsPort,wssPort:e.wssPort||o.wssPort,enableStats:Ct(e),httpHost:yt(e),useTLS:St(e),wsHost:wt(e),userAuthenticator:kt(e),channelAuthorizer:_t(e,t)};return"disabledTransports"in e&&(n.disabledTransports=e.disabledTransports),"enabledTransports"in e&&(n.enabledTransports=e.enabledTransports),"ignoreNullOrigin"in e&&(n.ignoreNullOrigin=e.ignoreNullOrigin),"timelineParams"in e&&(n.timelineParams=e.timelineParams),"nacl"in e&&(n.nacl=e.nacl),n}(t,this),this.channels=Ke.createChannels(),this.global_emitter=new oe,this.sessionID=ht.randomInt(1e9),this.timeline=new dt(this.key,this.sessionID,{cluster:this.config.cluster,features:It.getClientFeatures(),params:this.config.timelineParams||{},limit:50,level:lt.INFO,version:o.VERSION}),this.config.enableStats&&(this.timelineSender=Ke.createTimelineSender(this.timeline,{host:this.config.statsHost,path:"/timeline/v2/"+ht.TimelineTransport.name})),this.connection=Ke.createConnectionManager(this.key,{getStrategy:e=>ht.getDefaultStrategy(this.config,e,ft),timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:Boolean(this.config.useTLS)}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",e=>{var t=0===e.event.indexOf("pusher_internal:");if(e.channel){var n=this.channel(e.channel);n&&n.handleEvent(e)}t||this.global_emitter.emit(e.event,e.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",e=>{W.warn(e)}),It.instances.push(this),this.timeline.info({instances:It.instances.length}),this.user=new Et(this),It.isReady&&this.connect()}channel(e){return this.channels.find(e)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var e=this.connection.isUsingTLS(),t=this.timelineSender;this.timelineSenderTimer=new O(6e4,function(){t.send(e)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(e,t,n){return this.global_emitter.bind(e,t,n),this}unbind(e,t,n){return this.global_emitter.unbind(e,t,n),this}bind_global(e){return this.global_emitter.bind_global(e),this}unbind_global(e){return this.global_emitter.unbind_global(e),this}unbind_all(e){return this.global_emitter.unbind_all(),this}subscribeAll(){var e;for(e in this.channels.channels)this.channels.channels.hasOwnProperty(e)&&this.subscribe(e)}subscribe(e){var t=this.channels.add(e,this);return t.subscriptionPending&&t.subscriptionCancelled?t.reinstateSubscription():t.subscriptionPending||"connected"!==this.connection.state||t.subscribe(),t}unsubscribe(e){var t=this.channels.find(e);t&&t.subscriptionPending?t.cancelSubscription():(t=this.channels.remove(e))&&t.subscribed&&t.unsubscribe()}send_event(e,t,n){return this.connection.send_event(e,t,n)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}It.instances=[],It.isReady=!1,It.logToConsole=!1,It.Runtime=ht,It.ScriptReceivers=ht.ScriptReceivers,It.DependenciesReceivers=ht.DependenciesReceivers,It.auth_callbacks=ht.auth_callbacks;var Pt=t.default=It;ht.setup(It)}])};var i=e(n.exports=t());class r{constructor(e){if(this.brandingCache=null,this.config=e,this.frontendUrl=e.frontendUrl||this.getDefaultFrontendUrl(),this.apiUrl=e.apiUrl||this.getDefaultApiUrl(),this.authAppId=e.authAppId,this.invisible=e.invisible||!1,this.targetElement=e.targetElement,this.mockMobileDevice=e.mockMobileDevice||!1,e.realtimeUrl)this.realtimeUrl=e.realtimeUrl,console.log("[SDK]: Using provided realtimeUrl:",this.realtimeUrl);else{const e=new URL(this.frontendUrl),t="https:"===e.protocol?"wss:":"ws:";this.realtimeUrl=`${t}//${e.host}`,console.log("[SDK]: No realtimeUrl provided, inferring from frontendUrl:",this.realtimeUrl)}this.authAppId&&this.fetchBranding().catch(e=>{console.warn("[SDK]: Failed to fetch branding:",e)})}getKeyIdByAuthFlowId(e){if("undefined"==typeof window)return null;const t=`trulyYouKeyId_${e}`,n=localStorage.getItem(t);return n?(console.log(`[SDK]: Found keyId for authFlowId ${e}, key: ${t}`),n):(console.log(`[SDK]: No keyId found for authFlowId: ${e}`),null)}async fetchBranding(){if(this.authAppId)try{const e=await fetch(`${this.apiUrl}/api/apps/${this.authAppId}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(e.ok){const t=await e.json(),n=t.app||t;(n?.colors||n?.icon||n?.name||n?.authFlowId)&&(this.brandingCache={primary:n.colors?.primary,background:n.colors?.background,secondary:n.colors?.secondary,textColor:n.colors?.textColor,icon:n.icon,name:n.name,authFlowId:n.authFlowId},console.log("[SDK]: Branding and authFlowId fetched and cached:",this.brandingCache))}}catch(e){console.warn("[SDK]: Error fetching branding:",e)}}async generateQRCodeWithIcon(e,t){return new Promise((n,i)=>{const r=`https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(e)}`,o=new Image;o.crossOrigin="anonymous",o.onload=()=>{const e=document.createElement("canvas");e.width=300,e.height=300;const r=e.getContext("2d");if(r)if(r.drawImage(o,0,0,300,300),this.brandingCache?.icon){const i=async(i,o)=>{try{let s=i;if(o){const e=`${this.apiUrl}/api/proxy-icon?url=${encodeURIComponent(i)}`,t=await fetch(e);if(!t.ok)throw new Error("Proxy fetch failed");const n=await t.blob();s=URL.createObjectURL(n)}const a=new Image;a.crossOrigin=o?null:"anonymous",await new Promise((e,t)=>{a.onload=()=>e(),a.onerror=()=>t(new Error("Image load failed")),a.src=s});const c=60,h=(300-c)/2,l=(300-c)/2;r.fillStyle="#ffffff",r.beginPath(),r.arc(150,150,c/2+4,0,2*Math.PI),r.fill(),r.drawImage(a,h,l,c,c),o&&s.startsWith("blob:")&&URL.revokeObjectURL(s),t.src=e.toDataURL("image/png"),n()}catch(e){throw e}},o=this.brandingCache.icon;i(o,!0).catch(()=>{i(o,!1).catch(()=>{t.src=e.toDataURL("image/png"),n()})})}else t.src=e.toDataURL("image/png"),n();else i(new Error("Failed to get canvas context"))},o.onerror=()=>{i(new Error("Failed to load QR code"))},o.src=r})}getDefaultFrontendUrl(){if("undefined"!=typeof window){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e)return"http://localhost:3002"}return"https://sdks.verification.local"}getDefaultApiUrl(){if("undefined"!=typeof window){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e)return"http://localhost:3003"}return"https://api.verification.local"}isIOSDevice(){return"undefined"!=typeof window&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)}isSafariBrowser(){return"undefined"!=typeof window&&(/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent))}isDesktopDevice(){if(!0===this.mockMobileDevice)return console.log("[SDK]: Mock mobile device mode enabled - treating device as mobile (no handoff)"),!1;if("undefined"==typeof window)return!1;const e=navigator.userAgent||navigator.vendor||window.opera,t=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile/i.test(e.toLowerCase()),n="ontouchstart"in window||navigator.maxTouchPoints>0,i=window.screen&&"orientation"in window.screen;return!t||t&&!n&&!i}resolveTargetElement(){return this.targetElement?"string"==typeof this.targetElement?document.querySelector(this.targetElement):this.targetElement:null}async probeIframeForKey(){return new Promise(e=>{try{const t=window.location.origin,n=document.createElement("iframe");n.style.cssText="position: fixed; top: -9999px; left: -9999px; width: 1px; height: 1px; border: none; opacity: 0; pointer-events: none;";const i=new URL(`${this.frontendUrl}/probe.html`);let r;i.searchParams.set("probe","true"),i.searchParams.set("origin",t),this.brandingCache?.authFlowId?(i.searchParams.set("authFlowId",this.brandingCache.authFlowId),console.log("[SDK-PROBE]: Adding authFlowId to probe:",this.brandingCache.authFlowId)):console.log("[SDK-PROBE]: No authFlowId available in cache, will check for any key"),n.src=i.toString();const o=()=>{window.removeEventListener("message",s),n.parentNode&&n.parentNode.removeChild(n),r&&clearTimeout(r)},s=async t=>{const n=t.data;if("KEY_CHECK_RESULT"===n?.type||"KEY_CHECK_FAILED"===n?.type){try{const e=new URL(this.frontendUrl).origin;if(t.origin!==e)return}catch(e){if(!t.origin.includes(window.location.hostname))return}"KEY_CHECK_RESULT"===n?.type?(o(),n.hasKey&&n.keyId?e(n.keyId):e(null)):"KEY_CHECK_FAILED"===n?.type&&(o(),e(null))}};window.addEventListener("message",s),document.body.appendChild(n),r=setTimeout(()=>{console.log("[SDK-PROBE]: Timeout reached (3000ms), no response from iframe"),o(),e(null)},3e3)}catch(t){console.error("[SDK-PROBE]: Error in probeIframeForKey:",t),e(null)}})}async enrollWithPopup(){if(!this.authAppId)throw new Error("authAppId is required for enrollment. Please configure authAppId in SDK config.");const e=this.authAppId,t=await fetch(`${this.apiUrl}/api/apps/${e}`);if(!t.ok)throw new Error("Failed to load app configuration");if(!(await t.json()).app.authFlowId)throw new Error("App does not have an authentication flow configured");const n=`client_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,i=await fetch(`${this.apiUrl}/api/sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,clientId:n})});if(!i.ok){const e=await i.json();throw new Error(e.error||"Failed to create enrollment session")}const r=(await i.json()).data.sessionId;return new Promise((t,n)=>{const i=window.location.origin,o=new URLSearchParams({authAppId:e,sessionId:r,returnTo:"popup",origin:i});this.brandingCache?.primary&&o.set("primaryColor",this.brandingCache.primary),this.brandingCache?.background&&o.set("backgroundColor",this.brandingCache.background),this.brandingCache?.secondary&&o.set("secondaryColor",this.brandingCache.secondary),this.brandingCache?.textColor&&o.set("textColor",this.brandingCache.textColor);const s=`${this.frontendUrl}/enroll?${o.toString()}`;console.log("[SDK]: Opening enrollment popup:",s);const a=window.open(s,"trulyyou-enroll","width=600,height=700,scrollbars=yes,resizable=yes");if(!a)return void n(new Error("Failed to open enrollment popup. Please allow popups for this site."));let c,h,l=!1;const d=e=>{console.log("[SDK]: Enrollment popup message received:",e.origin,e.data);try{const t=new URL(this.frontendUrl).origin;if(e.origin!==t)return void console.log("[SDK]: Origin mismatch, ignoring message")}catch(t){if(!e.origin.includes(window.location.hostname))return void console.log("[SDK]: Origin mismatch, ignoring message")}if(e.data&&"ENROLLMENT_SUCCESS"===e.data.type){l=!0,c&&clearTimeout(c),h&&clearInterval(h),window.removeEventListener("message",d);const i=e.data.keyId;i?(console.log("[SDK]: Enrollment successful, keyId obtained from message:",i),t(i)):setTimeout(()=>{let e=null;this.brandingCache?.authFlowId&&(e=this.getKeyIdByAuthFlowId(this.brandingCache.authFlowId)),e?(console.log("[SDK]: Enrollment successful, keyId obtained (delayed) using authFlowId:",e),t(e)):n(new Error("Enrollment completed but no keyId found in message or localStorage"))},500)}else e.data&&"ENROLLMENT_ERROR"===e.data.type&&(l=!0,c&&clearTimeout(c),h&&clearInterval(h),window.removeEventListener("message",d),n(new Error(e.data.error||"Enrollment failed")))};window.addEventListener("message",d),c=setTimeout(()=>{l||(window.removeEventListener("message",d),h&&clearInterval(h),n(new Error("Enrollment timeout")))},6e5),h=setInterval(()=>{a.closed&&!l&&(clearInterval(h),clearTimeout(c),window.removeEventListener("message",d),n(new Error("Enrollment popup was closed")))},500)})}async signWithIframe(e){return new Promise((t,n)=>{try{const i=`sign_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,r=this.resolveTargetElement(),o=()=>{if(!r)return null;const e=document.createElement("div");e.id=`signing-overlay-${i}`,e.style.cssText="\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(255, 255, 255, 0.9);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n z-index: 10000;\n border-radius: 8px;\n ";const t=document.createElement("div");t.style.cssText=`\n width: 48px;\n height: 48px;\n border: 4px solid ${this.config.spinnerBgColor||"#e5e7eb"};\n border-top-color: ${this.config.spinnerColor||"#2563eb"};\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-bottom: 16px;\n `;const n=document.createElement("div");n.textContent="Authenticating...",n.style.cssText=`\n color: ${this.config.spinnerTextColor||"#6b7280"};\n font-size: 14px;\n font-weight: 500;\n `;const o=document.createElement("style");return o.textContent="\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(o),e.appendChild(t),e.appendChild(n),e},s=document.createElement("iframe");s.name=`trulyyou-sign-frame-${i}`,s.scrolling="no",s.setAttribute("scrolling","no"),s.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *");const a=e=>{if(null===e||"object"!=typeof e||e instanceof Array)return e;const t={};return Object.keys(e).sort().forEach(n=>{t[n]=a(e[n])}),t},c=((e,t,n,i)=>{const r=null==i?{}:i,o=a(null==e?{}:e),s=a(r),c=btoa(JSON.stringify(o)),h=btoa(JSON.stringify(s)),l={method:n,uriId:t,requestBody:c,queryParams:h};return{fullbase64:btoa(JSON.stringify(l)),sortedData:o,sortedQueryParams:s,encodedBody:c,encodedQueryParams:h}})(e.body||{},e.uri,e.method,{}),h={payload:c.fullbase64,apiCallStructure:e},l=btoa(JSON.stringify(h)),d=document.createElement("form");d.method="POST",d.action=`${this.frontendUrl}/sign/submit`,d.target=s.name,d.style.display="none";const u=document.createElement("input");u.type="hidden",u.name="attestationData",u.value=l,d.appendChild(u);const p=document.createElement("input");p.type="hidden",p.name="signId",p.value=i,d.appendChild(p);const g=document.createElement("input");g.type="hidden",g.name="mode",g.value="embedded",d.appendChild(g);const f=!this.invisible||this.isIOSDevice()||this.isSafariBrowser(),m=document.createElement("input");m.type="hidden",m.name="branding",m.value=JSON.stringify({primary:this.brandingCache?.primary||this.config.spinnerColor||"#2563eb",background:this.brandingCache?.background||"#ffffff",secondary:this.brandingCache?.secondary||"#2563eb",textColor:this.brandingCache?.textColor||this.config.spinnerTextColor||"#6b7280",spinnerColor:this.config.spinnerColor||this.brandingCache?.primary||"#2563eb",spinnerBgColor:this.config.spinnerBgColor||"#e5e7eb",spinnerTextColor:this.config.spinnerTextColor||this.brandingCache?.textColor||"#6b7280",visible:f}),d.appendChild(m);const b=document.createElement("input");b.type="hidden",b.name="authFlowId",b.value=this.brandingCache?.authFlowId||"",d.appendChild(b);if(this.mockMobileDevice||!this.isDesktopDevice())if(this.isIOSDevice()||this.isSafariBrowser())if(r){const e=window.getComputedStyle(r);"static"===e.position&&(r.style.position="relative");const t=r.style.height||e.height;if(!t||"auto"===t){const e=r.offsetHeight;e>0&&(r.style.height=`${e}px`)}s.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none; z-index: 9999;",r.appendChild(s)}else console.warn("[SDK]: Mobile iOS/Safari with no target element - using invisible iframe (WebAuthn may fail)"),s.style.cssText="position: fixed; top: -9999px; left: -9999px; width: 1px; height: 1px; border: none; opacity: 0; pointer-events: none;";else if(this.invisible)s.style.cssText="position: fixed; top: -9999px; left: -9999px; width: 1px; height: 1px; border: none; opacity: 0; pointer-events: none;";else if(r){const e=window.getComputedStyle(r);"static"===e.position&&(r.style.position="relative");const t=r.style.height||e.height;if(!t||"auto"===t){const e=r.offsetHeight;e>0&&(r.style.height=`${e}px`)}s.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none; z-index: 9999;",r.appendChild(s)}else console.warn("[SDK]: Mobile device with invisible=true but no target element - using invisible iframe"),s.style.cssText="position: fixed; top: -9999px; left: -9999px; width: 1px; height: 1px; border: none; opacity: 0; pointer-events: none;";else if(this.invisible)s.style.cssText="position: fixed; top: -9999px; left: -9999px; width: 1px; height: 1px; border: none; opacity: 0; pointer-events: none;";else if(r){const e=window.getComputedStyle(r);"static"===e.position&&(r.style.position="relative");const t=r.style.height||e.height;if(!t||"auto"===t){const e=r.offsetHeight;e>0&&(r.style.height=`${e}px`)}s.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none; z-index: 9999;",r.appendChild(s);const n=o();n&&r.appendChild(n)}else s.style.cssText="position: fixed; top: 0; left: 0; width: 100%; height: 100%; border: none; z-index: 9999; background: white;";let v;document.body.appendChild(d),s.parentNode||document.body.appendChild(s);let y=null;const w=()=>{window.removeEventListener("message",S),d.parentNode&&d.parentNode.removeChild(d),s.parentNode&&s.parentNode.removeChild(s),y&&y.parentNode&&y.parentNode.removeChild(y),v&&clearTimeout(v),r&&!this.invisible&&(r.style.height="")},S=e=>{try{const t=new URL(this.frontendUrl).origin;if(e.origin!==t)return}catch(t){if(!e.origin.includes(window.location.hostname))return}const r=e.data;if("SIGNING_COMPLETE"!==r?.type&&"SIGNATURE_COMPLETE"!==r?.type||r?.signId!==i)"SIGNING_ERROR"===r?.type&&r?.signId===i&&(w(),n(new Error(r.error||"Signing failed")));else if(console.log("[SDK]: Signature complete message received:",{type:r.type,hasSignature:!!r.signature||!!r.signatureBase64}),w(),r.error)n(new Error(r.error));else{const e=r.signature||r.signatureBase64;if(!e)return void n(new Error("No signature in response"));t({signature:e,keyId:r.keyId||""})}};window.addEventListener("message",S),d.submit(),setTimeout(()=>{d.parentNode&&d.parentNode.removeChild(d)},100),r&&!this.invisible&&(y=r.querySelector(`#signing-overlay-${i}`)),v=setTimeout(()=>{w(),n(new Error("Signing timeout"))},3e5)}catch(e){n(e)}})}async signWithWebSocketHandoff(e,t){return new Promise((n,r)=>{try{console.log("[SDK]: Desktop device detected, using WebSocket handoff with signatureId:",t);const o=this.brandingCache?.primary||"#2563eb",s=this.brandingCache?.name||"TrulyYou",a={signatureId:t,primaryColor:o,authAppName:s},c=btoa(JSON.stringify(a)),h=`${this.frontendUrl}/sign/${c}`,l=e=>{if(null===e||"object"!=typeof e||e instanceof Array)return e;const t={};return Object.keys(e).sort().forEach(n=>{t[n]=l(e[n])}),t},d=((e,t,n,i)=>{const r=null==i?{}:i,o=l(null==e?{}:e),s=l(r),a=btoa(JSON.stringify(o)),c=btoa(JSON.stringify(s)),h={method:n,uriId:t,requestBody:a,queryParams:c};return{fullbase64:btoa(JSON.stringify(h)),sortedData:o,sortedQueryParams:s,encodedBody:a,encodedQueryParams:c}})(e.body||{},e.uri,e.method,{}),u={payload:d.fullbase64,apiCallStructure:e};let p,g,f=!1,m=!0;try{const e=new URL(this.realtimeUrl.startsWith("ws://")||this.realtimeUrl.startsWith("wss://")?this.realtimeUrl:this.realtimeUrl.replace(/^http:/,"ws:").replace(/^https:/,"wss:"));p=e.hostname,g=e.port?parseInt(e.port,10):"wss:"===e.protocol?443:80,f="wss:"===e.protocol,m="wss:"===e.protocol}catch(e){console.warn("[SDK]: Error parsing realtimeUrl, using defaults:",e),p="127.0.0.1",g=6001}const b=this.config.pusherAppKey||"app-key",v={wsHost:this.config.pusherConfig?.wsHost||p,wsPort:this.config.pusherConfig?.wsPort||g,cluster:this.config.pusherConfig?.cluster||"",forceTLS:this.config.pusherConfig?.forceTLS??f,encrypted:this.config.pusherConfig?.encrypted??m,disableStats:this.config.pusherConfig?.disableStats??!0,enabledTransports:this.config.pusherConfig?.enabledTransports||["ws","wss"]};console.log("[SDK]: Initializing Pusher with config:",v);const y=new i(b,v),w=y.subscribe(t);console.log("[SDK]: Attempting to subscribe to Pusher channel:",t),w.bind("pusher:subscription_succeeded",()=>{console.log("[SDK]: ✅ Successfully subscribed to channel:",t),w.bind("countdown_update",e=>{console.log("[SDK]: 📊 Received countdown_update event:",e)}),w.bind("client-countdown_update",e=>{console.log("[SDK]: 📊 Received client-countdown_update event:",e)}),w.bind("countdown_expired",()=>{console.log("[SDK]: ⏰ Received countdown_expired event")}),w.bind("client-countdown_expired",()=>{console.log("[SDK]: ⏰ Received client-countdown_expired event")})});let S=null,C=null;const k=e=>{console.log("[SDK]: 📊 Received countdown_update event (early bind):",e),S?S(e):(console.warn("[SDK]: Countdown handler not ready yet, storing event"),setTimeout(()=>{S&&S(e)},100))};w.bind("countdown_update",k),w.bind("client-countdown_update",k);const _=()=>{console.log("[SDK]: ⏰ Received countdown_expired event (early bind)"),C&&C()};w.bind("countdown_expired",_),w.bind("client-countdown_expired",_),y.connection.bind("error",e=>{console.error("[SDK]: ❌ Pusher connection error:",e)}),y.connection.bind("state_change",e=>{console.log("[SDK]: 🔄 Pusher state change:",e.previous,"->",e.current)});let x,T=!1;y.connection.bind("connected",()=>{console.log("[SDK]: Pusher connected, waiting for counterparty..."),E&&I||w.trigger("client-device_connected",{type:"device_connected",deviceType:"desktop"}),x=setTimeout(()=>{O(),y.disconnect(),r(new Error("WebSocket handoff timeout - no counterparty connected"))},3e5)}),w.bind("client-device_connected",e=>{"device_connected"!==e.type||"mobile"!==e.deviceType||T||(T=!0,console.log("[SDK]: Mobile device connected (payload will be fetched from API)"))}),w.bind("client-signature_result",e=>{console.log("[SDK]: Signature result event received, raw data:",e),console.log("[SDK]: Data keys:",Object.keys(e||{})),console.log("[SDK]: counterpartyConnected:",T);const i=e?.signature||e?.data?.signature,o=e?.error||e?.data?.error,s=e?.keyId||e?.data?.keyId;if(console.log("[SDK]: Extracted values - signature:",!!i,"error:",o,"keyId:",s),console.log("[SDK]: Full socket data received:",JSON.stringify(e,null,2)),T||console.warn("[SDK]: Received signature result but counterparty not marked as connected yet. Waiting..."),clearTimeout(x),o)return console.error("[SDK]: Signature error:",o),O(),y.disconnect(),void r(new Error(o));if(i){console.log("[SDK]: Signature received successfully, resolving promise...");const r=s||"";r||console.warn("[SDK]: ⚠️ WARNING - No keyId received from Device B via socket! Data:",e),console.log("[SDK]: ✅ Using keyId from Device B:",r,"(extracted from socket)");const o={signature:i,keyId:r,signatureId:t};return console.log("[SDK]: Resolving with SigningResult:",{signatureLength:o.signature?.length,keyId:o.keyId,signatureId:o.signatureId,keyIdSource:r?"Device B (socket)":"MISSING - will fallback to localStorage"}),O(),y.disconnect(),void n(o)}console.error("[SDK]: Invalid signature result data - no signature or error:",JSON.stringify(e)),O(),y.disconnect(),r(new Error("Invalid signature result received"))}),y.connection.bind("error",e=>{console.error("[SDK]: Pusher connection error:",e),clearTimeout(x),y.disconnect(),r(new Error("Pusher connection error"))}),y.connection.bind("disconnected",()=>{console.log("[SDK]: Pusher disconnected"),clearTimeout(x)}),sessionStorage.setItem(`signHandoff_${t}`,JSON.stringify(u));const E=this.resolveTargetElement();let I=null,P=null;if(E){I=document.createElement("div"),I.id=`qr-handoff-${t}`,I.style.cssText="\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n max-width: 100%;\n max-height: 100%;\n overflow: hidden;\n background-color: rgba(255, 255, 255, 0.98);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n z-index: 10001;\n padding: 0;\n box-sizing: border-box;\n ";const e=document.createElement("div");e.style.cssText="\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n max-width: 100%;\n max-height: 100%;\n ";const n=document.createElement("div");n.style.cssText="\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 48px;\n height: 48px;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n ";const i=document.createElement("div");i.style.cssText=`\n width: 48px;\n height: 48px;\n border: 4px solid ${this.brandingCache?.primary?`${this.brandingCache.primary}20`:"#e5e7eb"};\n border-top-color: ${this.brandingCache?.primary||"#2563eb"};\n border-radius: 50%;\n animation: spin 1s linear infinite;\n `;const o=document.createElement("style");o.textContent="\n @keyframes spin {\n to { transform: rotate(360deg); }\n }\n ",document.head.appendChild(o),n.appendChild(i);const s=document.createElement("img");s.alt="QR Code for mobile signing (click to copy URL)",s.style.cssText="\n width: 100%;\n height: 100%;\n max-width: 100%;\n max-height: 100%;\n aspect-ratio: 1;\n object-fit: contain;\n cursor: pointer;\n transition: opacity 0.2s;\n position: relative;\n z-index: 2;\n display: none;\n opacity: 0;\n ",s.title="Click to copy URL to clipboard",s.addEventListener("load",()=>{console.log("[SDK]: QR image loaded"),n.style.display="none",s.style.display="block",s.style.opacity="1",setTimeout(()=>{c&&c()},50)}),s.addEventListener("error",()=>{console.error("[SDK]: QR image failed to load"),n.style.display="none",s.style.display="block",s.style.opacity="0.5"});const a=document.createElementNS("http://www.w3.org/2000/svg","svg");a.id=`countdown-svg-${t}`;const c=()=>{const n=s.getBoundingClientRect(),i=e.getBoundingClientRect(),r=Math.min(n.width,n.height),o=.05*r,c=r+2*o,h=n.left+n.width/2-i.left-c/2,l=n.top+n.height/2-i.top-c/2;console.log("[SDK]: QR positioning - centered offset:",h,l,"QR size:",r,"SVG size:",c),a.style.cssText=`\n position: absolute;\n top: ${l}px;\n left: ${h}px;\n width: ${c}px;\n height: ${c}px;\n pointer-events: none;\n z-index: 2;\n transform: rotate(0deg);\n transform-origin: center center;\n `,a.setAttribute("viewBox",`0 0 ${c} ${c}`),a.setAttribute("preserveAspectRatio","xMidYMid meet");const d=.04*c,u=.06*c;for(;a.firstChild;)a.removeChild(a.firstChild);const p=o-u/2,g=o-u/2,f=r+u,m=r+u,b=document.createElementNS("http://www.w3.org/2000/svg","rect");b.setAttribute("x",p.toString()),b.setAttribute("y",g.toString()),b.setAttribute("width",f.toString()),b.setAttribute("height",m.toString()),b.setAttribute("rx",d.toString()),b.setAttribute("ry",d.toString()),b.setAttribute("fill","none"),b.setAttribute("stroke","#e5e7eb"),b.setAttribute("stroke-width",u.toString()),a.appendChild(b);const v=document.createElementNS("http://www.w3.org/2000/svg","rect");v.id=`countdown-progress-${t}`,v.setAttribute("x",p.toString()),v.setAttribute("y",g.toString()),v.setAttribute("width",f.toString()),v.setAttribute("height",m.toString()),v.setAttribute("rx",d.toString()),v.setAttribute("ry",d.toString()),v.setAttribute("fill","none"),v.setAttribute("stroke",this.brandingCache?.primary||"#2563eb"),v.setAttribute("stroke-width",u.toString()),v.setAttribute("stroke-linecap","round"),v.setAttribute("stroke-linejoin","round");const y=d,w=2*(f+m-2*y)+2*Math.PI*y;return v.setAttribute("stroke-dasharray",w.toString()),v.setAttribute("stroke-dashoffset",w.toString()),v.style.transition="stroke-dashoffset 0.3s linear, stroke 0.3s linear",a.appendChild(v),{perimeter:w}};s.complete&&s.naturalWidth>0||s.addEventListener("load",()=>{c()}),c();let l={remaining:30,total:30};S=e=>{if(console.log("[SDK]: 🎯 Processing countdown_update:",e),!e||"countdown_update"!==e.type&&void 0===e.timeRemaining)console.warn("[SDK]: Invalid countdown_update data:",e);else{l={remaining:e.timeRemaining??l.remaining,total:e.totalTime??l.total},console.log(`[SDK]: 📊 Updating countdown rectangle: ${l.remaining}/${l.total}`);const n=a.getAttribute("viewBox"),i=n&&parseFloat(n.split(" ")[2])||100,r=.06*i,o=i/1.1,s=.04*i,c=2*(o+r+(o+r)-2*s)+2*Math.PI*s,h=l.remaining/l.total,d=c*(1-h),u=document.getElementById(`countdown-progress-${t}`);u&&u instanceof SVGRectElement&&(u.setAttribute("stroke-dashoffset",d.toString()),console.log(`[SDK]: 📊 Set stroke-dashoffset to: ${d} (percentage: ${h}, perimeter: ${c})`),l.remaining<=5?u.setAttribute("stroke","#ef4444"):l.remaining<=10?u.setAttribute("stroke","#f59e0b"):u.setAttribute("stroke",this.brandingCache?.primary||"#2563eb"))}},C=()=>{if(console.log("[SDK]: ⏰ Countdown expired - cleaning up and resetting state"),y&&"connected"===y.connection.state&&y.disconnect(),I){for(;I.firstChild;)I.removeChild(I.firstChild);I.parentNode&&I.parentNode.removeChild(I),I=null}const e=document.getElementById(`countdown-svg-${t}`);e&&e.parentNode&&e.parentNode.removeChild(e),O(),r(new Error("Countdown expired"))},w.bind("countdown_update",S),w.bind("client-countdown_update",S),w.bind("countdown_expired",C),w.bind("client-countdown_expired",C),e.appendChild(n),e.appendChild(s),e.appendChild(a),s.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(h),console.log("[SDK]: URL copied to clipboard:",h);const e=s.style.opacity||"1";s.style.opacity="0.7",setTimeout(()=>{s.style.opacity=e},200)}catch(e){console.error("[SDK]: Failed to copy URL to clipboard:",e);const t=document.createElement("textarea");t.value=h,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{document.execCommand("copy"),console.log("[SDK]: URL copied to clipboard (fallback method)")}catch(e){console.error("[SDK]: Fallback copy failed:",e)}document.body.removeChild(t)}}),this.generateQRCodeWithIcon(h,s).catch(e=>{console.warn("[SDK]: Error generating QR code with icon, using fallback:",e);const t=`https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(h)}`;s.src=t}),I.appendChild(e);const d=window.getComputedStyle(E);"static"===d.position&&(E.style.position="relative"),"visible"===d.overflow&&(E.style.overflow="hidden"),E.appendChild(I)}else{console.warn("[SDK]: No target element available, opening sign page in new window");const e=window.open(h,"_blank","width=600,height=700");if(!e)return y.disconnect(),void r(new Error("Failed to open sign page. Please allow popups for this site."));P=setInterval(()=>{e.closed&&(P&&clearInterval(P),clearTimeout(x),y.disconnect(),r(new Error("Sign window was closed")))},500)}let D=y;const O=()=>{I&&I.parentNode&&I.parentNode.removeChild(I),P&&clearInterval(P),clearTimeout(x),D&&(D.disconnect(),D=null),sessionStorage.removeItem(`signHandoff_${t}`)}}catch(e){r(e)}})}async signPayload(e,t,n){try{if(this.isDesktopDevice()){if(console.log("[SDK]: Desktop device detected, using WebSocket handoff (skipping key probe)"),!t)throw new Error("signatureId is required for desktop handoff");return await this.signWithWebSocketHandoff(e,t)}let i=n;if(i)console.log("[SDK]: Using existing keyId from enrollment:",i);else if(console.log("[SDK]: Mobile device detected, probing iframe for existing key..."),i=await this.probeIframeForKey(),!i&&(console.log("[SDK]: No valid active key found (missing, invalid, revoked, or expired), opening enrollment popup..."),i=await this.enrollWithPopup(),!i))throw new Error("Enrollment completed but no valid active key found");return console.log("[SDK]: Valid active key found, signing with keyId:",i),console.log("[SDK]: Using iframe signing for mobile device"),await this.signWithIframe(e)}catch(e){throw console.error("[SDK]: Signing error:",e),e}}async fetchWithSignature(e,t={}){let n;try{console.log("[SDK]: fetchWithSignature called for:",e);const i=new URL(e),r=i.pathname+i.search,o=`${i.protocol}//${i.host}`,s={body:t.body?JSON.parse(t.body):{},uri:r,method:(t.method||"GET").toUpperCase(),headers:t.headers||{}};if(console.log("[SDK]: API call structure:",s),!this.authAppId)throw new Error("authAppId is required for signature validation. Please configure authAppId in SDK initialization.");try{n=`sig_${Date.now()}_${Math.random().toString(36).substring(2,15)}${Math.random().toString(36).substring(2,15)}${Math.random().toString(36).substring(2,15)}${Math.random().toString(36).substring(2,15)}`;let i=null;this.brandingCache?.authFlowId&&(i=this.getKeyIdByAuthFlowId(this.brandingCache.authFlowId));const a=localStorage.getItem("trulyYouUserId");let c;if(a)try{c=a}catch(e){console.warn("[SDK]: Failed to parse userId from localStorage:",e)}const h=this.isDesktopDevice();if(!h&&!i&&(console.log("[SDK]: No key found in localStorage, triggering enrollment..."),i=await this.probeIframeForKey(),!i)){if(console.log("[SDK]: No key in iframe either, opening enrollment popup..."),i=await this.enrollWithPopup(),!i)throw new Error("Enrollment completed but no key found. Please try again.");console.log("[SDK]: Enrollment successful, obtained keyId:",i)}const l=await fetch(`${this.apiUrl}/api/signatures/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:this.authAppId,baseUrl:o,endpoint:r,method:s.method,keyId:i||"",userId:c,apiCallStructure:s,signatureId:n,isHandoff:h})});if(!l.ok){const e=await l.json().catch(()=>({}));throw new Error("Failed to create signature: "+(e.error||"Creation request failed"))}{const e=await l.json();if(!e.success||!e.data?.signatureId)throw new Error("Failed to create signature document: "+(e.error||"No signatureId returned"));console.log("[SDK]: Signature document created with signatureId:",e.data.signatureId)}const d=await this.signPayload(s,n,i||void 0),u=d.keyId||"";console.log("[SDK]: 🔍 KeyId debug - signingResult.keyId:",u,"localStorage keyId:",i,"keyId type:",typeof u,"empty?:",""===u);const p=u||i||"";console.log("[SDK]: ✅ Final keyId for auth header:",p,"(from",u&&""!==u?"Device B":"localStorage fallback",")");const g=btoa(JSON.stringify({signature:d.signature,keyId:p,signatureId:n})),f=await fetch(e,{...t,headers:{...t.headers,"x-truly-auth":g}});return console.log("[SDK]: Request complete, status:",f.status),{response:f,signature:d.signature,signatureId:n}}catch(e){if(console.error("[SDK]: Signature creation error:",e),e.message&&e.message.includes("Countdown expired"))return{response:null,signature:"",signatureId:n||""};throw new Error("Signature creation failed: "+(e.message||"Unknown error"))}}catch(e){if(console.error("[SDK]: fetchWithSignature error:",e),e.message&&e.message.includes("Countdown expired")){return{response:null,signature:"",signatureId:n||""}}throw e}}}export{r as TrulyYouSDK};
8
+ */window,t=function(){return function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(i,r,function(t){return e[t]}.bind(null,r));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=2)}([function(e,t,n){var i,r=this&&this.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},i(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0});var o=256,s=function(){function e(e){void 0===e&&(e="="),this._paddingCharacter=e}return e.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(8*e+5)/6|0},e.prototype.encode=function(e){for(var t="",n=0;n<e.length-2;n+=3){var i=e[n]<<16|e[n+1]<<8|e[n+2];t+=this._encodeByte(i>>>18&63),t+=this._encodeByte(i>>>12&63),t+=this._encodeByte(i>>>6&63),t+=this._encodeByte(i>>>0&63)}var r=e.length-n;return r>0&&(i=e[n]<<16|(2===r?e[n+1]<<8:0),t+=this._encodeByte(i>>>18&63),t+=this._encodeByte(i>>>12&63),t+=2===r?this._encodeByte(i>>>6&63):this._paddingCharacter||"",t+=this._paddingCharacter||""),t},e.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(6*e+7)/8|0},e.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},e.prototype.decode=function(e){if(0===e.length)return new Uint8Array(0);for(var t=this._getPaddingLength(e),n=e.length-t,i=new Uint8Array(this.maxDecodedLength(n)),r=0,s=0,a=0,c=0,h=0,l=0,d=0;s<n-4;s+=4)c=this._decodeChar(e.charCodeAt(s+0)),h=this._decodeChar(e.charCodeAt(s+1)),l=this._decodeChar(e.charCodeAt(s+2)),d=this._decodeChar(e.charCodeAt(s+3)),i[r++]=c<<2|h>>>4,i[r++]=h<<4|l>>>2,i[r++]=l<<6|d,a|=c&o,a|=h&o,a|=l&o,a|=d&o;if(s<n-1&&(c=this._decodeChar(e.charCodeAt(s)),h=this._decodeChar(e.charCodeAt(s+1)),i[r++]=c<<2|h>>>4,a|=c&o,a|=h&o),s<n-2&&(l=this._decodeChar(e.charCodeAt(s+2)),i[r++]=h<<4|l>>>2,a|=l&o),s<n-3&&(d=this._decodeChar(e.charCodeAt(s+3)),i[r++]=l<<6|d,a|=d&o),0!==a)throw new Error("Base64Coder: incorrect characters for decoding");return i},e.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-15,t+=62-e>>>8&3,String.fromCharCode(t)},e.prototype._decodeChar=function(e){var t=o;return t+=(42-e&e-44)>>>8&-256+e-43+62,t+=(46-e&e-48)>>>8&-256+e-47+63,t+=(47-e&e-58)>>>8&-256+e-48+52,t+=(64-e&e-91)>>>8&-256+e-65+0,t+=(96-e&e-123)>>>8&-256+e-97+26},e.prototype._getPaddingLength=function(e){var t=0;if(this._paddingCharacter){for(var n=e.length-1;n>=0&&e[n]===this._paddingCharacter;n--)t++;if(e.length<4||t>2)throw new Error("Base64Coder: incorrect padding")}return t},e}();t.Coder=s;var a=new s;t.encode=function(e){return a.encode(e)},t.decode=function(e){return a.decode(e)};var c=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return r(t,e),t.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-13,t+=62-e>>>8&49,String.fromCharCode(t)},t.prototype._decodeChar=function(e){var t=o;return t+=(44-e&e-46)>>>8&-256+e-45+62,t+=(94-e&e-96)>>>8&-256+e-95+63,t+=(47-e&e-58)>>>8&-256+e-48+52,t+=(64-e&e-91)>>>8&-256+e-65+0,t+=(96-e&e-123)>>>8&-256+e-97+26},t}(s);t.URLSafeCoder=c;var h=new c;t.encodeURLSafe=function(e){return h.encode(e)},t.decodeURLSafe=function(e){return h.decode(e)},t.encodedLength=function(e){return a.encodedLength(e)},t.maxDecodedLength=function(e){return a.maxDecodedLength(e)},t.decodedLength=function(e){return a.decodedLength(e)}},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var i="utf8: invalid string",r="utf8: invalid source encoding";function o(e){for(var t=0,n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128)t+=1;else if(r<2048)t+=2;else if(r<55296)t+=3;else{if(!(r<=57343))throw new Error(i);if(n>=e.length-1)throw new Error(i);n++,t+=4}}return t}t.encode=function(e){for(var t=new Uint8Array(o(e)),n=0,i=0;i<e.length;i++){var r=e.charCodeAt(i);r<128?t[n++]=r:r<2048?(t[n++]=192|r>>6,t[n++]=128|63&r):r<55296?(t[n++]=224|r>>12,t[n++]=128|r>>6&63,t[n++]=128|63&r):(i++,r=(1023&r)<<10,r|=1023&e.charCodeAt(i),r+=65536,t[n++]=240|r>>18,t[n++]=128|r>>12&63,t[n++]=128|r>>6&63,t[n++]=128|63&r)}return t},t.encodedLength=o,t.decode=function(e){for(var t=[],n=0;n<e.length;n++){var i=e[n];if(128&i){var o=void 0;if(i<224){if(n>=e.length)throw new Error(r);if(128!=(192&(s=e[++n])))throw new Error(r);i=(31&i)<<6|63&s,o=128}else if(i<240){if(n>=e.length-1)throw new Error(r);var s=e[++n],a=e[++n];if(128!=(192&s)||128!=(192&a))throw new Error(r);i=(15&i)<<12|(63&s)<<6|63&a,o=2048}else{if(!(i<248))throw new Error(r);if(n>=e.length-2)throw new Error(r);s=e[++n],a=e[++n];var c=e[++n];if(128!=(192&s)||128!=(192&a)||128!=(192&c))throw new Error(r);i=(15&i)<<18|(63&s)<<12|(63&a)<<6|63&c,o=65536}if(i<o||i>=55296&&i<=57343)throw new Error(r);if(i>=65536){if(i>1114111)throw new Error(r);i-=65536,t.push(String.fromCharCode(55296|i>>10)),i=56320|1023&i}}t.push(String.fromCharCode(i))}return t.join("")}},function(e,t,n){e.exports=n(3).default},function(e,t,n){n.r(t);class i{constructor(e,t){this.lastId=0,this.prefix=e,this.name=t}create(e){this.lastId++;var t=this.lastId,n=this.prefix+t,i=this.name+"["+t+"]",r=!1,o=function(){r||(e.apply(null,arguments),r=!0)};return this[t]=o,{number:t,id:n,name:i,callback:o}}remove(e){delete this[e.number]}}var r=new i("_pusher_script_","Pusher.ScriptReceivers"),o={VERSION:"8.4.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""},s=new i("_pusher_dependencies","Pusher.DependenciesReceivers"),a=new class{constructor(e){this.options=e,this.receivers=e.receivers||r,this.loading={}}load(e,t,n){var i=this;if(i.loading[e]&&i.loading[e].length>0)i.loading[e].push(n);else{i.loading[e]=[n];var r=ht.createScriptRequest(i.getPath(e,t)),o=i.receivers.create(function(t){if(i.receivers.remove(o),i.loading[e]){var n=i.loading[e];delete i.loading[e];for(var s=function(e){e||r.cleanup()},a=0;a<n.length;a++)n[a](t,s)}});r.send(o)}}getRoot(e){var t=ht.getDocument().location.protocol;return(e&&e.useTLS||"https:"===t?this.options.cdn_https:this.options.cdn_http).replace(/\/*$/,"")+"/"+this.options.version}getPath(e,t){return this.getRoot(t)+"/"+e+this.options.suffix+".js"}}({cdn_http:o.cdn_http,cdn_https:o.cdn_https,version:o.VERSION,suffix:o.dependency_suffix,receivers:s});const c={baseUrl:"https://pusher.com",urls:{authenticationEndpoint:{path:"/docs/channels/server_api/authenticating_users"},authorizationEndpoint:{path:"/docs/channels/server_api/authorizing-users/"},javascriptQuickStart:{path:"/docs/javascript_quick_start"},triggeringClientEvents:{path:"/docs/client_api_guide/client_events#trigger-events"},encryptedChannelSupport:{fullUrl:"https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support"}}};var h,l=function(e){const t=c.urls[e];if(!t)return"";let n;return t.fullUrl?n=t.fullUrl:t.path&&(n=c.baseUrl+t.path),n?`See: ${n}`:""};!function(e){e.UserAuthentication="user-authentication",e.ChannelAuthorization="channel-authorization"}(h||(h={}));class d extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class u extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class p extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class g extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class f extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class m extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class b extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class y extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class v extends Error{constructor(e,t){super(t),this.status=e,Object.setPrototypeOf(this,new.target.prototype)}}var w=function(e,t,n,i,r){const o=ht.createXHR();for(var s in o.open("POST",n.endpoint,!0),o.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),n.headers)o.setRequestHeader(s,n.headers[s]);if(null!=n.headersProvider){let e=n.headersProvider();for(var s in e)o.setRequestHeader(s,e[s])}return o.onreadystatechange=function(){if(4===o.readyState)if(200===o.status){let e,t=!1;try{e=JSON.parse(o.responseText),t=!0}catch(e){r(new v(200,`JSON returned from ${i.toString()} endpoint was invalid, yet status code was 200. Data was: ${o.responseText}`),null)}t&&r(null,e)}else{let e="";switch(i){case h.UserAuthentication:e=l("authenticationEndpoint");break;case h.ChannelAuthorization:e=`Clients must be authorized to join private or presence channels. ${l("authorizationEndpoint")}`}r(new v(o.status,`Unable to retrieve auth string from ${i.toString()} endpoint - received status: ${o.status} from ${n.endpoint}. ${e}`),null)}},o.send(t),o},S=String.fromCharCode,C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",k=function(e){var t=e.charCodeAt(0);return t<128?e:t<2048?S(192|t>>>6)+S(128|63&t):S(224|t>>>12&15)+S(128|t>>>6&63)+S(128|63&t)},_=function(e){return e.replace(/[^\x00-\x7F]/g,k)},T=function(e){var t=[0,2,1][e.length%3],n=e.charCodeAt(0)<<16|(e.length>1?e.charCodeAt(1):0)<<8|(e.length>2?e.charCodeAt(2):0);return[C.charAt(n>>>18),C.charAt(n>>>12&63),t>=2?"=":C.charAt(n>>>6&63),t>=1?"=":C.charAt(63&n)].join("")},x=window.btoa||function(e){return e.replace(/[\s\S]{1,3}/g,T)},E=class{constructor(e,t,n,i){this.clear=t,this.timer=e(()=>{this.timer&&(this.timer=i(this.timer))},n)}isRunning(){return null!==this.timer}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}};function I(e){window.clearTimeout(e)}function P(e){window.clearInterval(e)}class D extends E{constructor(e,t){super(setTimeout,I,e,function(e){return t(),null})}}class A extends E{constructor(e,t){super(setInterval,P,e,function(e){return t(),e})}}var O={now:()=>Date.now?Date.now():(new Date).valueOf(),defer:e=>new D(0,e),method(e,...t){var n=Array.prototype.slice.call(arguments,1);return function(t){return t[e].apply(t,n.concat(arguments))}}},R=O;function L(e,...t){for(var n=0;n<t.length;n++){var i=t[n];for(var r in i)i[r]&&i[r].constructor&&i[r].constructor===Object?e[r]=L(e[r]||{},i[r]):e[r]=i[r]}return e}function N(){for(var e=["Pusher"],t=0;t<arguments.length;t++)"string"==typeof arguments[t]?e.push(arguments[t]):e.push(J(arguments[t]));return e.join(" : ")}function U(e,t){var n=Array.prototype.indexOf;if(null===e)return-1;if(n&&e.indexOf===n)return e.indexOf(t);for(var i=0,r=e.length;i<r;i++)if(e[i]===t)return i;return-1}function K(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(e[n],n,e)}function j(e){var t=[];return K(e,function(e,n){t.push(n)}),t}function F(e,t,n){for(var i=0;i<e.length;i++)t.call(n||window,e[i],i,e)}function $(e,t){for(var n=[],i=0;i<e.length;i++)n.push(t(e[i],i,e,n));return n}function M(e,t){t=t||function(e){return!!e};for(var n=[],i=0;i<e.length;i++)t(e[i],i,e,n)&&n.push(e[i]);return n}function B(e,t){var n={};return K(e,function(i,r){(t&&t(i,r,e,n)||Boolean(i))&&(n[r]=i)}),n}function H(e,t){for(var n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1}function z(e){return t=function(e){return"object"==typeof e&&(e=J(e)),encodeURIComponent((t=e.toString(),x(_(t))));var t},n={},K(e,function(e,i){n[i]=t(e)}),n;var t,n}function q(e){var t,n,i=B(e,function(e){return void 0!==e});return $((t=z(i),n=[],K(t,function(e,t){n.push([t,e])}),n),R.method("join","=")).join("&")}function J(e){try{return JSON.stringify(e)}catch(i){return JSON.stringify((t=[],n=[],function e(i,r){var o,s,a;switch(typeof i){case"object":if(!i)return null;for(o=0;o<t.length;o+=1)if(t[o]===i)return{$ref:n[o]};if(t.push(i),n.push(r),"[object Array]"===Object.prototype.toString.apply(i))for(a=[],o=0;o<i.length;o+=1)a[o]=e(i[o],r+"["+o+"]");else for(s in a={},i)Object.prototype.hasOwnProperty.call(i,s)&&(a[s]=e(i[s],r+"["+JSON.stringify(s)+"]"));return a;case"number":case"string":case"boolean":return i}}(e,"$")))}var t,n}var W=new class{constructor(){this.globalLog=e=>{window.console&&window.console.log&&window.console.log(e)}}debug(...e){this.log(this.globalLog,e)}warn(...e){this.log(this.globalLogWarn,e)}error(...e){this.log(this.globalLogError,e)}globalLogWarn(e){window.console&&window.console.warn?window.console.warn(e):this.globalLog(e)}globalLogError(e){window.console&&window.console.error?window.console.error(e):this.globalLogWarn(e)}log(e,...t){var n=N.apply(this,arguments);Pt.log?Pt.log(n):Pt.logToConsole&&e.bind(this)(n)}},X=function(e,t,n,i,r){void 0===n.headers&&null==n.headersProvider||W.warn(`To send headers with the ${i.toString()} request, you must use AJAX, rather than JSONP.`);var o=e.nextAuthCallbackID.toString();e.nextAuthCallbackID++;var s=e.getDocument(),a=s.createElement("script");e.auth_callbacks[o]=function(e){r(null,e)};var c="Pusher.auth_callbacks['"+o+"']";a.src=n.endpoint+"?callback="+encodeURIComponent(c)+"&"+t;var h=s.getElementsByTagName("head")[0]||s.documentElement;h.insertBefore(a,h.firstChild)};class G{constructor(e){this.src=e}send(e){var t=this,n="Error loading "+t.src;t.script=document.createElement("script"),t.script.id=e.id,t.script.src=t.src,t.script.type="text/javascript",t.script.charset="UTF-8",t.script.addEventListener?(t.script.onerror=function(){e.callback(n)},t.script.onload=function(){e.callback(null)}):t.script.onreadystatechange=function(){"loaded"!==t.script.readyState&&"complete"!==t.script.readyState||e.callback(null)},void 0===t.script.async&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(t.errorScript=document.createElement("script"),t.errorScript.id=e.id+"_error",t.errorScript.text=e.name+"('"+n+"');",t.script.async=t.errorScript.async=!1):t.script.async=!0;var i=document.getElementsByTagName("head")[0];i.insertBefore(t.script,i.firstChild),t.errorScript&&i.insertBefore(t.errorScript,t.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class Q{constructor(e,t){this.url=e,this.data=t}send(e){if(!this.request){var t=q(this.data),n=this.url+"/"+e.number+"?"+t;this.request=ht.createScriptRequest(n),this.request.send(e)}}cleanup(){this.request&&this.request.cleanup()}}var Y={name:"jsonp",getAgent:function(e,t){return function(n,i){var o="http"+(t?"s":"")+"://"+(e.host||e.options.host)+e.options.path,s=ht.createJSONPRequest(o,n),a=ht.ScriptReceivers.create(function(t,n){r.remove(a),s.cleanup(),n&&n.host&&(e.host=n.host),i&&i(t,n)});s.send(a)}}};function V(e,t,n){return e+(t.useTLS?"s":"")+"://"+(t.useTLS?t.hostTLS:t.hostNonTLS)+n}function Z(e,t){return"/app/"+e+"?protocol="+o.PROTOCOL+"&client=js&version="+o.VERSION+(t?"&"+t:"")}var ee={getInitial:function(e,t){return V("ws",t,(t.httpPath||"")+Z(e,"flash=false"))}},te={getInitial:function(e,t){return V("http",t,(t.httpPath||"/pusher")+Z(e))}},ne={getInitial:function(e,t){return V("http",t,t.httpPath||"/pusher")},getPath:function(e,t){return Z(e)}};class ie{constructor(){this._callbacks={}}get(e){return this._callbacks[re(e)]}add(e,t,n){var i=re(e);this._callbacks[i]=this._callbacks[i]||[],this._callbacks[i].push({fn:t,context:n})}remove(e,t,n){if(e||t||n){var i=e?[re(e)]:j(this._callbacks);t||n?this.removeCallback(i,t,n):this.removeAllCallbacks(i)}else this._callbacks={}}removeCallback(e,t,n){F(e,function(e){this._callbacks[e]=M(this._callbacks[e]||[],function(e){return t&&t!==e.fn||n&&n!==e.context}),0===this._callbacks[e].length&&delete this._callbacks[e]},this)}removeAllCallbacks(e){F(e,function(e){delete this._callbacks[e]},this)}}function re(e){return"_"+e}class oe{constructor(e){this.callbacks=new ie,this.global_callbacks=[],this.failThrough=e}bind(e,t,n){return this.callbacks.add(e,t,n),this}bind_global(e){return this.global_callbacks.push(e),this}unbind(e,t,n){return this.callbacks.remove(e,t,n),this}unbind_global(e){return e?(this.global_callbacks=M(this.global_callbacks||[],t=>t!==e),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(e,t,n){for(var i=0;i<this.global_callbacks.length;i++)this.global_callbacks[i](e,t);var r=this.callbacks.get(e),o=[];if(n?o.push(t,n):t&&o.push(t),r&&r.length>0)for(i=0;i<r.length;i++)r[i].fn.apply(r[i].context||window,o);else this.failThrough&&this.failThrough(e,t);return this}}class se extends oe{constructor(e,t,n,i,r){super(),this.initialize=ht.transportConnectionInitializer,this.hooks=e,this.name=t,this.priority=n,this.key=i,this.options=r,this.state="new",this.timeline=r.timeline,this.activityTimeout=r.activityTimeout,this.id=this.timeline.generateUniqueID()}handlesActivityChecks(){return Boolean(this.hooks.handlesActivityChecks)}supportsPing(){return Boolean(this.hooks.supportsPing)}connect(){if(this.socket||"initialized"!==this.state)return!1;var e=this.hooks.urls.getInitial(this.key,this.options);try{this.socket=this.hooks.getSocket(e,this.options)}catch(e){return R.defer(()=>{this.onError(e),this.changeState("closed")}),!1}return this.bindListeners(),W.debug("Connecting",{transport:this.name,url:e}),this.changeState("connecting"),!0}close(){return!!this.socket&&(this.socket.close(),!0)}send(e){return"open"===this.state&&(R.defer(()=>{this.socket&&this.socket.send(e)}),!0)}ping(){"open"===this.state&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(e){this.emit("error",{type:"WebSocketError",error:e}),this.timeline.error(this.buildTimelineMessage({error:e.toString()}))}onClose(e){e?this.changeState("closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(e){this.emit("message",e)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=e=>{this.onError(e)},this.socket.onclose=e=>{this.onClose(e)},this.socket.onmessage=e=>{this.onMessage(e)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(e,t){this.state=e,this.timeline.info(this.buildTimelineMessage({state:e,params:t})),this.emit(e,t)}buildTimelineMessage(e){return L({cid:this.id},e)}}class ae{constructor(e){this.hooks=e}isSupported(e){return this.hooks.isSupported(e)}createConnection(e,t,n,i){return new se(this.hooks,e,t,n,i)}}var ce=new ae({urls:ee,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return Boolean(ht.getWebSocketAPI())},isSupported:function(){return Boolean(ht.getWebSocketAPI())},getSocket:function(e){return ht.createWebSocket(e)}}),he={urls:te,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},le=L({getSocket:function(e){return ht.HTTPFactory.createStreamingSocket(e)}},he),de=L({getSocket:function(e){return ht.HTTPFactory.createPollingSocket(e)}},he),ue={isSupported:function(){return ht.isXHRSupported()}},pe={ws:ce,xhr_streaming:new ae(L({},le,ue)),xhr_polling:new ae(L({},de,ue))},ge=new ae({file:"sockjs",urls:ne,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return void 0!==window.SockJS},getSocket:function(e,t){return new window.SockJS(e,null,{js_path:a.getPath("sockjs",{useTLS:t.useTLS}),ignore_null_origin:t.ignoreNullOrigin})},beforeOpen:function(e,t){e.send(JSON.stringify({path:t}))}}),fe={isSupported:function(e){return ht.isXDRSupported(e.useTLS)}},me=new ae(L({},le,fe)),be=new ae(L({},de,fe));pe.xdr_streaming=me,pe.xdr_polling=be,pe.sockjs=ge;var ye=pe,ve=new class extends oe{constructor(){super();var e=this;void 0!==window.addEventListener&&(window.addEventListener("online",function(){e.emit("online")},!1),window.addEventListener("offline",function(){e.emit("offline")},!1))}isOnline(){return void 0===window.navigator.onLine||window.navigator.onLine}};class we{constructor(e,t,n){this.manager=e,this.transport=t,this.minPingDelay=n.minPingDelay,this.maxPingDelay=n.maxPingDelay,this.pingDelay=void 0}createConnection(e,t,n,i){i=L({},i,{activityTimeout:this.pingDelay});var r=this.transport.createConnection(e,t,n,i),o=null,s=function(){r.unbind("open",s),r.bind("closed",a),o=R.now()},a=e=>{if(r.unbind("closed",a),1002===e.code||1003===e.code)this.manager.reportDeath();else if(!e.wasClean&&o){var t=R.now()-o;t<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(t/2,this.minPingDelay))}};return r.bind("open",s),r}isSupported(e){return this.manager.isAlive()&&this.transport.isSupported(e)}}const Se={decodeMessage:function(e){try{var t=JSON.parse(e.data),n=t.data;if("string"==typeof n)try{n=JSON.parse(t.data)}catch(e){}var i={event:t.event,channel:t.channel,data:n};return t.user_id&&(i.user_id=t.user_id),i}catch(t){throw{type:"MessageParseError",error:t,data:e.data}}},encodeMessage:function(e){return JSON.stringify(e)},processHandshake:function(e){var t=Se.decodeMessage(e);if("pusher:connection_established"===t.event){if(!t.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:t.data.socket_id,activityTimeout:1e3*t.data.activity_timeout}}if("pusher:error"===t.event)return{action:this.getCloseAction(t.data),error:this.getCloseError(t.data)};throw"Invalid handshake"},getCloseAction:function(e){return e.code<4e3?e.code>=1002&&e.code<=1004?"backoff":null:4e3===e.code?"tls_only":e.code<4100?"refused":e.code<4200?"backoff":e.code<4300?"retry":"refused"},getCloseError:function(e){return 1e3!==e.code&&1001!==e.code?{type:"PusherError",data:{code:e.code,message:e.reason||e.message}}:null}};var Ce=Se;class ke extends oe{constructor(e,t){super(),this.id=e,this.transport=t,this.activityTimeout=t.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(e){return this.transport.send(e)}send_event(e,t,n){var i={event:e,data:t};return n&&(i.channel=n),W.debug("Event sent",i),this.send(Ce.encodeMessage(i))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var e={message:e=>{var t;try{t=Ce.decodeMessage(e)}catch(t){this.emit("error",{type:"MessageParseError",error:t,data:e.data})}if(void 0!==t){switch(W.debug("Event recd",t),t.event){case"pusher:error":this.emit("error",{type:"PusherError",data:t.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong")}this.emit("message",t)}},activity:()=>{this.emit("activity")},error:e=>{this.emit("error",e)},closed:e=>{t(),e&&e.code&&this.handleCloseEvent(e),this.transport=null,this.emit("closed")}},t=()=>{K(e,(e,t)=>{this.transport.unbind(t,e)})};K(e,(e,t)=>{this.transport.bind(t,e)})}handleCloseEvent(e){var t=Ce.getCloseAction(e),n=Ce.getCloseError(e);n&&this.emit("error",n),t&&this.emit(t,{action:t,error:n})}}class _e{constructor(e,t){this.transport=e,this.callback=t,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=e=>{var t;this.unbindListeners();try{t=Ce.processHandshake(e)}catch(e){return this.finish("error",{error:e}),void this.transport.close()}"connected"===t.action?this.finish("connected",{connection:new ke(t.id,this.transport),activityTimeout:t.activityTimeout}):(this.finish(t.action,{error:t.error}),this.transport.close())},this.onClosed=e=>{this.unbindListeners();var t=Ce.getCloseAction(e)||"backoff",n=Ce.getCloseError(e);this.finish(t,{error:n})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(e,t){this.callback(L({transport:this.transport,action:e},t))}}class Te{constructor(e,t){this.timeline=e,this.options=t||{}}send(e,t){this.timeline.isEmpty()||this.timeline.send(ht.TimelineTransport.getAgent(this,e),t)}}class xe extends oe{constructor(e,t){super(function(t,n){W.debug("No callbacks on "+e+" for "+t)}),this.name=e,this.pusher=t,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(e,t){return t(null,{auth:""})}trigger(e,t){if(0!==e.indexOf("client-"))throw new d("Event '"+e+"' does not start with 'client-'");if(!this.subscribed){var n=l("triggeringClientEvents");W.warn(`Client event triggered before channel 'subscription_succeeded' event . ${n}`)}return this.pusher.send_event(e,t,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(e){var t=e.event,n=e.data;"pusher_internal:subscription_succeeded"===t?this.handleSubscriptionSucceededEvent(e):"pusher_internal:subscription_count"===t?this.handleSubscriptionCountEvent(e):0!==t.indexOf("pusher_internal:")&&this.emit(t,n,{})}handleSubscriptionSucceededEvent(e){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",e.data)}handleSubscriptionCountEvent(e){e.data.subscription_count&&(this.subscriptionCount=e.data.subscription_count),this.emit("pusher:subscription_count",e.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(e,t)=>{e?(this.subscriptionPending=!1,W.error(e.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:e.message},e instanceof v?{status:e.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:t.auth,channel_data:t.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class Ee extends xe{authorize(e,t){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:e},t)}}class Ie{constructor(){this.reset()}get(e){return Object.prototype.hasOwnProperty.call(this.members,e)?{id:e,info:this.members[e]}:null}each(e){K(this.members,(t,n)=>{e(this.get(n))})}setMyID(e){this.myID=e}onSubscription(e){this.members=e.presence.hash,this.count=e.presence.count,this.me=this.get(this.myID)}addMember(e){return null===this.get(e.user_id)&&this.count++,this.members[e.user_id]=e.user_info,this.get(e.user_id)}removeMember(e){var t=this.get(e.user_id);return t&&(delete this.members[e.user_id],this.count--),t}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Pe=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}c((i=i.apply(e,t||[])).next())})};class De extends Ee{constructor(e,t){super(e,t),this.members=new Ie}authorize(e,t){super.authorize(e,(e,n)=>Pe(this,void 0,void 0,function*(){if(!e)if(null!=n.channel_data){var i=JSON.parse(n.channel_data);this.members.setMyID(i.user_id)}else{if(yield this.pusher.user.signinDonePromise,null==this.pusher.user.user_data){let e=l("authorizationEndpoint");return W.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${e}, or the user should be signed in.`),void t("Invalid auth response")}this.members.setMyID(this.pusher.user.user_data.id)}t(e,n)}))}handleEvent(e){var t=e.event;if(0===t.indexOf("pusher_internal:"))this.handleInternalEvent(e);else{var n=e.data,i={};e.user_id&&(i.user_id=e.user_id),this.emit(t,n,i)}}handleInternalEvent(e){var t=e.event,n=e.data;switch(t){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(e);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(e);break;case"pusher_internal:member_added":var i=this.members.addMember(n);this.emit("pusher:member_added",i);break;case"pusher_internal:member_removed":var r=this.members.removeMember(n);r&&this.emit("pusher:member_removed",r)}}handleSubscriptionSucceededEvent(e){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(e.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Ae=n(1),Oe=n(0);class Re extends Ee{constructor(e,t,n){super(e,t),this.key=null,this.nacl=n}authorize(e,t){super.authorize(e,(e,n)=>{if(e)return void t(e,n);let i=n.shared_secret;i?(this.key=Object(Oe.decode)(i),delete n.shared_secret,t(null,n)):t(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null)})}trigger(e,t){throw new m("Client events are not currently supported for encrypted channels")}handleEvent(e){var t=e.event,n=e.data;0!==t.indexOf("pusher_internal:")&&0!==t.indexOf("pusher:")?this.handleEncryptedEvent(t,n):super.handleEvent(e)}handleEncryptedEvent(e,t){if(!this.key)return void W.debug("Received encrypted event before key has been retrieved from the authEndpoint");if(!t.ciphertext||!t.nonce)return void W.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+t);let n=Object(Oe.decode)(t.ciphertext);if(n.length<this.nacl.secretbox.overheadLength)return void W.error(`Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${n.length}`);let i=Object(Oe.decode)(t.nonce);if(i.length<this.nacl.secretbox.nonceLength)return void W.error(`Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${i.length}`);let r=this.nacl.secretbox.open(n,i,this.key);if(null===r)return W.debug("Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint..."),void this.authorize(this.pusher.connection.socket_id,(t,o)=>{t?W.error(`Failed to make a request to the authEndpoint: ${o}. Unable to fetch new key, so dropping encrypted event`):(r=this.nacl.secretbox.open(n,i,this.key),null!==r?this.emit(e,this.getDataToEmit(r)):W.error("Failed to decrypt event with new key. Dropping encrypted event"))});this.emit(e,this.getDataToEmit(r))}getDataToEmit(e){let t=Object(Ae.decode)(e);try{return JSON.parse(t)}catch(e){return t}}}class Le extends oe{constructor(e,t){super(),this.state="initialized",this.connection=null,this.key=e,this.options=t,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var n=ht.getNetwork();n.bind("online",()=>{this.timeline.info({netinfo:"online"}),"connecting"!==this.state&&"unavailable"!==this.state||this.retryIn(0)}),n.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}connect(){this.connection||this.runner||(this.strategy.isSupported()?(this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()):this.updateState("failed"))}send(e){return!!this.connection&&this.connection.send(e)}send_event(e,t,n){return!!this.connection&&this.connection.send_event(e,t,n)}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var e=(t,n)=>{t?this.runner=this.strategy.connect(0,e):"error"===n.action?(this.emit("error",{type:"HandshakeError",error:n.error}),this.timeline.error({handshakeError:n.error})):(this.abortConnecting(),this.handshakeCallbacks[n.action](n))};this.runner=this.strategy.connect(0,e)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection&&this.abandonConnection().close()}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(e){this.timeline.info({action:"retry",delay:e}),e>0&&this.emit("connecting_in",Math.round(e/1e3)),this.retryTimer=new D(e||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new D(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new D(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new D(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(e){return L({},e,{message:e=>{this.resetActivityCheck(),this.emit("message",e)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:e=>{this.emit("error",e)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(e){return L({},e,{connected:e=>{this.activityTimeout=Math.min(this.options.activityTimeout,e.activityTimeout,e.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(e.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let e=e=>t=>{t.error&&this.emit("error",{type:"WebSocketError",error:t.error}),e(t)};return{tls_only:e(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:e(()=>{this.disconnect()}),backoff:e(()=>{this.retryIn(1e3)}),retry:e(()=>{this.retryIn(0)})}}setConnection(e){for(var t in this.connection=e,this.connectionCallbacks)this.connection.bind(t,this.connectionCallbacks[t]);this.resetActivityCheck()}abandonConnection(){if(this.connection){for(var e in this.stopActivityCheck(),this.connectionCallbacks)this.connection.unbind(e,this.connectionCallbacks[e]);var t=this.connection;return this.connection=null,t}}updateState(e,t){var n=this.state;if(this.state=e,n!==e){var i=e;"connected"===i&&(i+=" with new socket ID "+t.socket_id),W.debug("State changed",n+" -> "+i),this.timeline.info({state:e,params:t}),this.emit("state_change",{previous:n,current:e}),this.emit(e,t)}}shouldRetry(){return"connecting"===this.state||"connected"===this.state}}class Ne{constructor(){this.channels={}}add(e,t){return this.channels[e]||(this.channels[e]=function(e,t){if(0===e.indexOf("private-encrypted-")){if(t.config.nacl)return Ke.createEncryptedChannel(e,t,t.config.nacl);let n="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",i=l("encryptedChannelSupport");throw new m(`${n}. ${i}`)}if(0===e.indexOf("private-"))return Ke.createPrivateChannel(e,t);if(0===e.indexOf("presence-"))return Ke.createPresenceChannel(e,t);if(0===e.indexOf("#"))throw new u('Cannot create a channel with name "'+e+'".');return Ke.createChannel(e,t)}(e,t)),this.channels[e]}all(){return function(e){var t=[];return K(e,function(e){t.push(e)}),t}(this.channels)}find(e){return this.channels[e]}remove(e){var t=this.channels[e];return delete this.channels[e],t}disconnect(){K(this.channels,function(e){e.disconnect()})}}var Ue={createChannels:()=>new Ne,createConnectionManager:(e,t)=>new Le(e,t),createChannel:(e,t)=>new xe(e,t),createPrivateChannel:(e,t)=>new Ee(e,t),createPresenceChannel:(e,t)=>new De(e,t),createEncryptedChannel:(e,t,n)=>new Re(e,t,n),createTimelineSender:(e,t)=>new Te(e,t),createHandshake:(e,t)=>new _e(e,t),createAssistantToTheTransportManager:(e,t,n)=>new we(e,t,n)},Ke=Ue;class je{constructor(e){this.options=e||{},this.livesLeft=this.options.lives||1/0}getAssistant(e){return Ke.createAssistantToTheTransportManager(this,e,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class Fe{constructor(e,t){this.strategies=e,this.loop=Boolean(t.loop),this.failFast=Boolean(t.failFast),this.timeout=t.timeout,this.timeoutLimit=t.timeoutLimit}isSupported(){return H(this.strategies,R.method("isSupported"))}connect(e,t){var n=this.strategies,i=0,r=this.timeout,o=null,s=(a,c)=>{c?t(null,c):(i+=1,this.loop&&(i%=n.length),i<n.length?(r&&(r*=2,this.timeoutLimit&&(r=Math.min(r,this.timeoutLimit))),o=this.tryStrategy(n[i],e,{timeout:r,failFast:this.failFast},s)):t(!0))};return o=this.tryStrategy(n[i],e,{timeout:r,failFast:this.failFast},s),{abort:function(){o.abort()},forceMinPriority:function(t){e=t,o&&o.forceMinPriority(t)}}}tryStrategy(e,t,n,i){var r=null,o=null;return n.timeout>0&&(r=new D(n.timeout,function(){o.abort(),i(!0)})),o=e.connect(t,function(e,t){e&&r&&r.isRunning()&&!n.failFast||(r&&r.ensureAborted(),i(e,t))}),{abort:function(){r&&r.ensureAborted(),o.abort()},forceMinPriority:function(e){o.forceMinPriority(e)}}}}class $e{constructor(e){this.strategies=e}isSupported(){return H(this.strategies,R.method("isSupported"))}connect(e,t){return function(e,t,n){var i=$(e,function(e,i,r,o){return e.connect(t,n(i,o))});return{abort:function(){F(i,Me)},forceMinPriority:function(e){F(i,function(t){t.forceMinPriority(e)})}}}(this.strategies,e,function(e,n){return function(i,r){n[e].error=i,i?function(e){return function(e,t){for(var n=0;n<e.length;n++)if(!t(e[n],n,e))return!1;return!0}(e,function(e){return Boolean(e.error)})}(n)&&t(!0):(F(n,function(e){e.forceMinPriority(r.transport.priority)}),t(null,r))}})}}function Me(e){e.error||e.aborted||(e.abort(),e.aborted=!0)}class Be{constructor(e,t,n){this.strategy=e,this.transports=t,this.ttl=n.ttl||18e5,this.usingTLS=n.useTLS,this.timeline=n.timeline}isSupported(){return this.strategy.isSupported()}connect(e,t){var n=this.usingTLS,i=function(e){var t=ht.getLocalStorage();if(t)try{var n=t[He(e)];if(n)return JSON.parse(n)}catch(t){ze(e)}return null}(n),r=i&&i.cacheSkipCount?i.cacheSkipCount:0,o=[this.strategy];if(i&&i.timestamp+this.ttl>=R.now()){var s=this.transports[i.transport];s&&(["ws","wss"].includes(i.transport)||r>3?(this.timeline.info({cached:!0,transport:i.transport,latency:i.latency}),o.push(new Fe([s],{timeout:2*i.latency+1e3,failFast:!0}))):r++)}var a=R.now(),c=o.pop().connect(e,function i(s,h){s?(ze(n),o.length>0?(a=R.now(),c=o.pop().connect(e,i)):t(s)):(function(e,t,n,i){var r=ht.getLocalStorage();if(r)try{r[He(e)]=J({timestamp:R.now(),transport:t,latency:n,cacheSkipCount:i})}catch(e){}}(n,h.transport.name,R.now()-a,r),t(null,h))});return{abort:function(){c.abort()},forceMinPriority:function(t){e=t,c&&c.forceMinPriority(t)}}}}function He(e){return"pusherTransport"+(e?"TLS":"NonTLS")}function ze(e){var t=ht.getLocalStorage();if(t)try{delete t[He(e)]}catch(e){}}class qe{constructor(e,{delay:t}){this.strategy=e,this.options={delay:t}}isSupported(){return this.strategy.isSupported()}connect(e,t){var n,i=this.strategy,r=new D(this.options.delay,function(){n=i.connect(e,t)});return{abort:function(){r.ensureAborted(),n&&n.abort()},forceMinPriority:function(t){e=t,n&&n.forceMinPriority(t)}}}}class Je{constructor(e,t,n){this.test=e,this.trueBranch=t,this.falseBranch=n}isSupported(){return(this.test()?this.trueBranch:this.falseBranch).isSupported()}connect(e,t){return(this.test()?this.trueBranch:this.falseBranch).connect(e,t)}}class We{constructor(e){this.strategy=e}isSupported(){return this.strategy.isSupported()}connect(e,t){var n=this.strategy.connect(e,function(e,i){i&&n.abort(),t(e,i)});return n}}function Xe(e){return function(){return e.isSupported()}}var Ge,Qe=function(e,t,n){var i={};function r(t,r,o,s,a){var c=n(e,t,r,o,s,a);return i[t]=c,c}var o,s=Object.assign({},t,{hostNonTLS:e.wsHost+":"+e.wsPort,hostTLS:e.wsHost+":"+e.wssPort,httpPath:e.wsPath}),a=Object.assign({},s,{useTLS:!0}),c=Object.assign({},t,{hostNonTLS:e.httpHost+":"+e.httpPort,hostTLS:e.httpHost+":"+e.httpsPort,httpPath:e.httpPath}),h={loop:!0,timeout:15e3,timeoutLimit:6e4},l=new je({minPingDelay:1e4,maxPingDelay:e.activityTimeout}),d=new je({lives:2,minPingDelay:1e4,maxPingDelay:e.activityTimeout}),u=r("ws","ws",3,s,l),p=r("wss","ws",3,a,l),g=r("sockjs","sockjs",1,c),f=r("xhr_streaming","xhr_streaming",1,c,d),m=r("xdr_streaming","xdr_streaming",1,c,d),b=r("xhr_polling","xhr_polling",1,c),y=r("xdr_polling","xdr_polling",1,c),v=new Fe([u],h),w=new Fe([p],h),S=new Fe([g],h),C=new Fe([new Je(Xe(f),f,m)],h),k=new Fe([new Je(Xe(b),b,y)],h),_=new Fe([new Je(Xe(C),new $e([C,new qe(k,{delay:4e3})]),k)],h),T=new Je(Xe(_),_,S);return o=t.useTLS?new $e([v,new qe(T,{delay:2e3})]):new $e([v,new qe(w,{delay:2e3}),new qe(T,{delay:5e3})]),new Be(new We(new Je(Xe(u),o,T)),i,{ttl:18e5,timeline:t.timeline,useTLS:t.useTLS})},Ye={getRequest:function(e){var t=new window.XDomainRequest;return t.ontimeout=function(){e.emit("error",new p),e.close()},t.onerror=function(t){e.emit("error",t),e.close()},t.onprogress=function(){t.responseText&&t.responseText.length>0&&e.onChunk(200,t.responseText)},t.onload=function(){t.responseText&&t.responseText.length>0&&e.onChunk(200,t.responseText),e.emit("finished",200),e.close()},t},abortRequest:function(e){e.ontimeout=e.onerror=e.onprogress=e.onload=null,e.abort()}};class Ve extends oe{constructor(e,t,n){super(),this.hooks=e,this.method=t,this.url=n}start(e){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},ht.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(e)}close(){this.unloader&&(ht.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(e,t){for(;;){var n=this.advanceBuffer(t);if(!n)break;this.emit("chunk",{status:e,data:n})}this.isBufferTooLong(t)&&this.emit("buffer_too_long")}advanceBuffer(e){var t=e.slice(this.position),n=t.indexOf("\n");return-1!==n?(this.position+=n+1,t.slice(0,n)):null}isBufferTooLong(e){return this.position===e.length&&e.length>262144}}!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.OPEN=1]="OPEN",e[e.CLOSED=3]="CLOSED"}(Ge||(Ge={}));var Ze=Ge,et=1;function tt(e){var t=-1===e.indexOf("?")?"?":"&";return e+t+"t="+ +new Date+"&n="+et++}function nt(e){return ht.randomInt(e)}var it,rt=class{constructor(e,t){this.hooks=e,this.session=nt(1e3)+"/"+function(e){for(var t=[],n=0;n<e;n++)t.push(nt(32).toString(32));return t.join("")}(8),this.location=function(e){var t=/([^\?]*)\/*(\??.*)/.exec(e);return{base:t[1],queryString:t[2]}}(t),this.readyState=Ze.CONNECTING,this.openStream()}send(e){return this.sendRaw(JSON.stringify([e]))}ping(){this.hooks.sendHeartbeat(this)}close(e,t){this.onClose(e,t,!0)}sendRaw(e){if(this.readyState!==Ze.OPEN)return!1;try{return ht.createSocketRequest("POST",tt((t=this.location,n=this.session,t.base+"/"+n+"/xhr_send"))).start(e),!0}catch(e){return!1}var t,n}reconnect(){this.closeStream(),this.openStream()}onClose(e,t,n){this.closeStream(),this.readyState=Ze.CLOSED,this.onclose&&this.onclose({code:e,reason:t,wasClean:n})}onChunk(e){var t;if(200===e.status)switch(this.readyState===Ze.OPEN&&this.onActivity(),e.data.slice(0,1)){case"o":t=JSON.parse(e.data.slice(1)||"{}"),this.onOpen(t);break;case"a":t=JSON.parse(e.data.slice(1)||"[]");for(var n=0;n<t.length;n++)this.onEvent(t[n]);break;case"m":t=JSON.parse(e.data.slice(1)||"null"),this.onEvent(t);break;case"h":this.hooks.onHeartbeat(this);break;case"c":t=JSON.parse(e.data.slice(1)||"[]"),this.onClose(t[0],t[1],!0)}}onOpen(e){var t,n,i;this.readyState===Ze.CONNECTING?(e&&e.hostname&&(this.location.base=(t=this.location.base,n=e.hostname,(i=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(t))[1]+n+i[3])),this.readyState=Ze.OPEN,this.onopen&&this.onopen()):this.onClose(1006,"Server lost session",!0)}onEvent(e){this.readyState===Ze.OPEN&&this.onmessage&&this.onmessage({data:e})}onActivity(){this.onactivity&&this.onactivity()}onError(e){this.onerror&&this.onerror(e)}openStream(){this.stream=ht.createSocketRequest("POST",tt(this.hooks.getReceiveURL(this.location,this.session))),this.stream.bind("chunk",e=>{this.onChunk(e)}),this.stream.bind("finished",e=>{this.hooks.onFinished(this,e)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(e){R.defer(()=>{this.onError(e),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}},ot={getReceiveURL:function(e,t){return e.base+"/"+t+"/xhr_streaming"+e.queryString},onHeartbeat:function(e){e.sendRaw("[]")},sendHeartbeat:function(e){e.sendRaw("[]")},onFinished:function(e,t){e.onClose(1006,"Connection interrupted ("+t+")",!1)}},st={getReceiveURL:function(e,t){return e.base+"/"+t+"/xhr"+e.queryString},onHeartbeat:function(){},sendHeartbeat:function(e){e.sendRaw("[]")},onFinished:function(e,t){200===t?e.reconnect():e.onClose(1006,"Connection interrupted ("+t+")",!1)}},at={getRequest:function(e){var t=new(ht.getXHRAPI());return t.onreadystatechange=t.onprogress=function(){switch(t.readyState){case 3:t.responseText&&t.responseText.length>0&&e.onChunk(t.status,t.responseText);break;case 4:t.responseText&&t.responseText.length>0&&e.onChunk(t.status,t.responseText),e.emit("finished",t.status),e.close()}},t},abortRequest:function(e){e.onreadystatechange=null,e.abort()}},ct={createStreamingSocket(e){return this.createSocket(ot,e)},createPollingSocket(e){return this.createSocket(st,e)},createSocket:(e,t)=>new rt(e,t),createXHR(e,t){return this.createRequest(at,e,t)},createRequest:(e,t,n)=>new Ve(e,t,n),createXDR:function(e,t){return this.createRequest(Ye,e,t)}},ht={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:r,DependenciesReceivers:s,getDefaultStrategy:Qe,Transports:ye,transportConnectionInitializer:function(){var e=this;e.timeline.info(e.buildTimelineMessage({transport:e.name+(e.options.useTLS?"s":"")})),e.hooks.isInitialized()?e.changeState("initialized"):e.hooks.file?(e.changeState("initializing"),a.load(e.hooks.file,{useTLS:e.options.useTLS},function(t,n){e.hooks.isInitialized()?(e.changeState("initialized"),n(!0)):(t&&e.onError(t),e.onClose(),n(!1))})):e.onClose()},HTTPFactory:ct,TimelineTransport:Y,getXHRAPI:()=>window.XMLHttpRequest,getWebSocketAPI:()=>window.WebSocket||window.MozWebSocket,setup(e){window.Pusher=e;var t=()=>{this.onDocumentBody(e.ready)};window.JSON?t():a.load("json2",{},t)},getDocument:()=>document,getProtocol(){return this.getDocument().location.protocol},getAuthorizers:()=>({ajax:w,jsonp:X}),onDocumentBody(e){document.body?e():setTimeout(()=>{this.onDocumentBody(e)},0)},createJSONPRequest:(e,t)=>new Q(e,t),createScriptRequest:e=>new G(e),getLocalStorage(){try{return window.localStorage}catch(e){return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){return new(this.getXHRAPI())},createMicrosoftXHR:()=>new ActiveXObject("Microsoft.XMLHTTP"),getNetwork:()=>ve,createWebSocket(e){return new(this.getWebSocketAPI())(e)},createSocketRequest(e,t){if(this.isXHRSupported())return this.HTTPFactory.createXHR(e,t);if(this.isXDRSupported(0===t.indexOf("https:")))return this.HTTPFactory.createXDR(e,t);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var e=this.getXHRAPI();return Boolean(e)&&void 0!==(new e).withCredentials},isXDRSupported(e){var t=e?"https:":"http:",n=this.getProtocol();return Boolean(window.XDomainRequest)&&n===t},addUnloadListener(e){void 0!==window.addEventListener?window.addEventListener("unload",e,!1):void 0!==window.attachEvent&&window.attachEvent("onunload",e)},removeUnloadListener(e){void 0!==window.addEventListener?window.removeEventListener("unload",e,!1):void 0!==window.detachEvent&&window.detachEvent("onunload",e)},randomInt:e=>Math.floor((window.crypto||window.msCrypto).getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)*e)};!function(e){e[e.ERROR=3]="ERROR",e[e.INFO=6]="INFO",e[e.DEBUG=7]="DEBUG"}(it||(it={}));var lt=it;class dt{constructor(e,t,n){this.key=e,this.session=t,this.events=[],this.options=n||{},this.sent=0,this.uniqueID=0}log(e,t){e<=this.options.level&&(this.events.push(L({},t,{timestamp:R.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(e){this.log(lt.ERROR,e)}info(e){this.log(lt.INFO,e)}debug(e){this.log(lt.DEBUG,e)}isEmpty(){return 0===this.events.length}send(e,t){var n=L({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],e(n,(e,n)=>{e||this.sent++,t&&t(e,n)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class ut{constructor(e,t,n,i){this.name=e,this.priority=t,this.transport=n,this.options=i||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(e,t){if(!this.isSupported())return pt(new y,t);if(this.priority<e)return pt(new g,t);var n=!1,i=this.transport.createConnection(this.name,this.priority,this.options.key,this.options),r=null,o=function(){i.unbind("initialized",o),i.connect()},s=function(){r=Ke.createHandshake(i,function(e){n=!0,h(),t(null,e)})},a=function(e){h(),t(e)},c=function(){var e;h(),e=J(i),t(new f(e))},h=function(){i.unbind("initialized",o),i.unbind("open",s),i.unbind("error",a),i.unbind("closed",c)};return i.bind("initialized",o),i.bind("open",s),i.bind("error",a),i.bind("closed",c),i.initialize(),{abort:()=>{n||(h(),r?r.close():i.close())},forceMinPriority:e=>{n||this.priority<e&&(r?r.close():i.close())}}}}function pt(e,t){return R.defer(function(){t(e)}),{abort:function(){},forceMinPriority:function(){}}}const{Transports:gt}=ht;var ft=function(e,t,n,i,r,o){var s,a=gt[n];if(!a)throw new b(n);return e.enabledTransports&&-1===U(e.enabledTransports,t)||e.disabledTransports&&-1!==U(e.disabledTransports,t)?s=mt:(r=Object.assign({ignoreNullOrigin:e.ignoreNullOrigin},r),s=new ut(t,i,o?o.getAssistant(a):a,r)),s},mt={isSupported:function(){return!1},connect:function(e,t){var n=R.defer(function(){t(new y)});return{abort:function(){n.ensureAborted()},forceMinPriority:function(){}}}},bt=e=>{if(void 0===ht.getAuthorizers()[e.transport])throw`'${e.transport}' is not a recognized auth transport`;return(t,n)=>{const i=((e,t)=>{var n="socket_id="+encodeURIComponent(e.socketId);for(var i in t.params)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(t.params[i]);if(null!=t.paramsProvider){let e=t.paramsProvider();for(var i in e)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(e[i])}return n})(t,e);ht.getAuthorizers()[e.transport](ht,i,e,h.UserAuthentication,n)}},yt=e=>{if(void 0===ht.getAuthorizers()[e.transport])throw`'${e.transport}' is not a recognized auth transport`;return(t,n)=>{const i=((e,t)=>{var n="socket_id="+encodeURIComponent(e.socketId);for(var i in n+="&channel_name="+encodeURIComponent(e.channelName),t.params)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(t.params[i]);if(null!=t.paramsProvider){let e=t.paramsProvider();for(var i in e)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(e[i])}return n})(t,e);ht.getAuthorizers()[e.transport](ht,i,e,h.ChannelAuthorization,n)}};function vt(e){return e.httpHost?e.httpHost:e.cluster?`sockjs-${e.cluster}.pusher.com`:o.httpHost}function wt(e){return e.wsHost?e.wsHost:`ws-${e.cluster}.pusher.com`}function St(e){return"https:"===ht.getProtocol()||!1!==e.forceTLS}function Ct(e){return"enableStats"in e?e.enableStats:"disableStats"in e&&!e.disableStats}function kt(e){const t=Object.assign(Object.assign({},o.userAuthentication),e.userAuthentication);return"customHandler"in t&&null!=t.customHandler?t.customHandler:bt(t)}function _t(e,t){const n=function(e,t){let n;return"channelAuthorization"in e?n=Object.assign(Object.assign({},o.channelAuthorization),e.channelAuthorization):(n={transport:e.authTransport||o.authTransport,endpoint:e.authEndpoint||o.authEndpoint},"auth"in e&&("params"in e.auth&&(n.params=e.auth.params),"headers"in e.auth&&(n.headers=e.auth.headers)),"authorizer"in e&&(n.customHandler=((e,t,n)=>{const i={authTransport:t.transport,authEndpoint:t.endpoint,auth:{params:t.params,headers:t.headers}};return(t,r)=>{const o=e.channel(t.channelName);n(o,i).authorize(t.socketId,r)}})(t,n,e.authorizer))),n}(e,t);return"customHandler"in n&&null!=n.customHandler?n.customHandler:yt(n)}class Tt extends oe{constructor(e){super(function(e,t){W.debug(`No callbacks on watchlist events for ${e}`)}),this.pusher=e,this.bindWatchlistInternalEvent()}handleEvent(e){e.data.events.forEach(e=>{this.emit(e.name,e)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",e=>{"pusher_internal:watchlist_events"===e.event&&this.handleEvent(e)})}}var xt=function(){let e,t;return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}};class Et extends oe{constructor(e){super(function(e,t){W.debug("No callbacks on user for "+e)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(e,t)=>{if(e)return W.warn(`Error during signin: ${e}`),void this._cleanup();this.pusher.send_event("pusher:signin",{auth:t.auth,user_data:t.user_data})},this.pusher=e,this.pusher.connection.bind("state_change",({previous:e,current:t})=>{"connected"!==e&&"connected"===t&&this._signin(),"connected"===e&&"connected"!==t&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new Tt(e),this.pusher.connection.bind("message",e=>{"pusher:signin_success"===e.event&&this._onSigninSuccess(e.data),this.serverToUserChannel&&this.serverToUserChannel.name===e.channel&&this.serverToUserChannel.handleEvent(e)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),"connected"===this.pusher.connection.state&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(e){try{this.user_data=JSON.parse(e.user_data)}catch(t){return W.error(`Failed parsing user data after signin: ${e.user_data}`),void this._cleanup()}if("string"!=typeof this.user_data.id||""===this.user_data.id)return W.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),void this._cleanup();this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){this.serverToUserChannel=new xe(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((e,t)=>{0!==e.indexOf("pusher_internal:")&&0!==e.indexOf("pusher:")&&this.emit(e,t)}),(e=>{e.subscriptionPending&&e.subscriptionCancelled?e.reinstateSubscription():e.subscriptionPending||"connected"!==this.pusher.connection.state||e.subscribe()})(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested)return;if(this.signinDonePromise&&!this.signinDonePromise.done)return;const{promise:e,resolve:t}=xt();e.done=!1;const n=()=>{e.done=!0};e.then(n).catch(n),this.signinDonePromise=e,this._signinDoneResolve=t}}class It{static ready(){It.isReady=!0;for(var e=0,t=It.instances.length;e<t;e++)It.instances[e].connect()}static getClientFeatures(){return j(B({ws:ht.Transports.ws},function(e){return e.isSupported({})}))}constructor(e,t){!function(e){if(null==e)throw"You must pass your app key when you instantiate Pusher."}(e),function(e){if(null==e)throw"You must pass an options object";if(null==e.cluster)throw"Options object must provide a cluster";"disableStats"in e&&W.warn("The disableStats option is deprecated in favor of enableStats")}(t),this.key=e,this.config=function(e,t){let n={activityTimeout:e.activityTimeout||o.activityTimeout,cluster:e.cluster,httpPath:e.httpPath||o.httpPath,httpPort:e.httpPort||o.httpPort,httpsPort:e.httpsPort||o.httpsPort,pongTimeout:e.pongTimeout||o.pongTimeout,statsHost:e.statsHost||o.stats_host,unavailableTimeout:e.unavailableTimeout||o.unavailableTimeout,wsPath:e.wsPath||o.wsPath,wsPort:e.wsPort||o.wsPort,wssPort:e.wssPort||o.wssPort,enableStats:Ct(e),httpHost:vt(e),useTLS:St(e),wsHost:wt(e),userAuthenticator:kt(e),channelAuthorizer:_t(e,t)};return"disabledTransports"in e&&(n.disabledTransports=e.disabledTransports),"enabledTransports"in e&&(n.enabledTransports=e.enabledTransports),"ignoreNullOrigin"in e&&(n.ignoreNullOrigin=e.ignoreNullOrigin),"timelineParams"in e&&(n.timelineParams=e.timelineParams),"nacl"in e&&(n.nacl=e.nacl),n}(t,this),this.channels=Ke.createChannels(),this.global_emitter=new oe,this.sessionID=ht.randomInt(1e9),this.timeline=new dt(this.key,this.sessionID,{cluster:this.config.cluster,features:It.getClientFeatures(),params:this.config.timelineParams||{},limit:50,level:lt.INFO,version:o.VERSION}),this.config.enableStats&&(this.timelineSender=Ke.createTimelineSender(this.timeline,{host:this.config.statsHost,path:"/timeline/v2/"+ht.TimelineTransport.name})),this.connection=Ke.createConnectionManager(this.key,{getStrategy:e=>ht.getDefaultStrategy(this.config,e,ft),timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:Boolean(this.config.useTLS)}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",e=>{var t=0===e.event.indexOf("pusher_internal:");if(e.channel){var n=this.channel(e.channel);n&&n.handleEvent(e)}t||this.global_emitter.emit(e.event,e.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",e=>{W.warn(e)}),It.instances.push(this),this.timeline.info({instances:It.instances.length}),this.user=new Et(this),It.isReady&&this.connect()}channel(e){return this.channels.find(e)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var e=this.connection.isUsingTLS(),t=this.timelineSender;this.timelineSenderTimer=new A(6e4,function(){t.send(e)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(e,t,n){return this.global_emitter.bind(e,t,n),this}unbind(e,t,n){return this.global_emitter.unbind(e,t,n),this}bind_global(e){return this.global_emitter.bind_global(e),this}unbind_global(e){return this.global_emitter.unbind_global(e),this}unbind_all(e){return this.global_emitter.unbind_all(),this}subscribeAll(){var e;for(e in this.channels.channels)this.channels.channels.hasOwnProperty(e)&&this.subscribe(e)}subscribe(e){var t=this.channels.add(e,this);return t.subscriptionPending&&t.subscriptionCancelled?t.reinstateSubscription():t.subscriptionPending||"connected"!==this.connection.state||t.subscribe(),t}unsubscribe(e){var t=this.channels.find(e);t&&t.subscriptionPending?t.cancelSubscription():(t=this.channels.remove(e))&&t.subscribed&&t.unsubscribe()}send_event(e,t,n){return this.connection.send_event(e,t,n)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}It.instances=[],It.isReady=!1,It.logToConsole=!1,It.Runtime=ht,It.ScriptReceivers=ht.ScriptReceivers,It.DependenciesReceivers=ht.DependenciesReceivers,It.auth_callbacks=ht.auth_callbacks;var Pt=t.default=It;ht.setup(It)}])};var i=e(n.exports=t());class r{constructor(e){if(this.brandingCache=null,this.config=e,this.frontendUrl=e.frontendUrl||this.getDefaultFrontendUrl(),this.apiUrl=e.apiUrl||this.getDefaultApiUrl(),this.authAppId=e.authAppId,this.invisible=e.invisible||!1,this.targetElement=e.targetElement,this.mockMobileDevice=e.mockMobileDevice||!1,e.realtimeUrl)this.realtimeUrl=e.realtimeUrl,console.log("[SDK]: Using provided realtimeUrl:",this.realtimeUrl);else{const e=new URL(this.frontendUrl),t="https:"===e.protocol?"wss:":"ws:";this.realtimeUrl=`${t}//${e.host}`,console.log("[SDK]: No realtimeUrl provided, inferring from frontendUrl:",this.realtimeUrl)}this.authAppId&&this.fetchBranding().catch(e=>{console.warn("[SDK]: Failed to fetch branding:",e)})}getKeyIdByAuthFlowId(e){if("undefined"==typeof window)return null;const t=`trulyYouKeyId_${e}`,n=localStorage.getItem(t);return n?(console.log(`[SDK]: Found keyId for authFlowId ${e}, key: ${t}`),n):(console.log(`[SDK]: No keyId found for authFlowId: ${e}`),null)}async fetchBranding(){if(!this.authAppId)return console.warn("[SDK]: Cannot fetch branding - authAppId not configured"),!1;try{const e=await fetch(`${this.apiUrl}/api/apps/${this.authAppId}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(e.ok){const t=await e.json(),n=t.app||t;if(n?.colors||n?.icon||n?.name||n?.authFlowId)return this.brandingCache={primary:n.colors?.primary,background:n.colors?.background,secondary:n.colors?.secondary,textColor:n.colors?.textColor,icon:n.icon,name:n.name,authFlowId:n.authFlowId},console.log("[SDK]: Branding and authFlowId fetched and cached:",this.brandingCache),!!n.authFlowId}return console.warn("[SDK]: Failed to fetch branding - response not ok or missing app data"),!1}catch(e){return console.warn("[SDK]: Error fetching branding:",e),!1}}async ensureAuthFlowIdLoaded(){if(this.brandingCache?.authFlowId)return void console.log("[SDK]: authFlowId already loaded:",this.brandingCache.authFlowId);console.log("[SDK]: authFlowId not yet loaded, fetching branding...");if(!await this.fetchBranding()||!this.brandingCache?.authFlowId)throw new Error("authFlowId is required for signing but not available. Please check that your app configuration includes an authFlowId.");console.log("[SDK]: authFlowId loaded successfully:",this.brandingCache.authFlowId)}async generateQRCodeWithIcon(e,t){return new Promise((n,i)=>{const r=`https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(e)}`,o=new Image;o.crossOrigin="anonymous",o.onload=()=>{const e=document.createElement("canvas");e.width=300,e.height=300;const r=e.getContext("2d");if(r)if(r.drawImage(o,0,0,300,300),this.brandingCache?.icon){const i=async(i,o)=>{try{let s=i;if(o){const e=`${this.apiUrl}/api/proxy-icon?url=${encodeURIComponent(i)}`,t=await fetch(e);if(!t.ok)throw new Error("Proxy fetch failed");const n=await t.blob();s=URL.createObjectURL(n)}const a=new Image;a.crossOrigin=o?null:"anonymous",await new Promise((e,t)=>{a.onload=()=>e(),a.onerror=()=>t(new Error("Image load failed")),a.src=s});const c=60,h=(300-c)/2,l=(300-c)/2;r.fillStyle="#ffffff",r.beginPath(),r.arc(150,150,c/2+4,0,2*Math.PI),r.fill(),r.drawImage(a,h,l,c,c),o&&s.startsWith("blob:")&&URL.revokeObjectURL(s),t.src=e.toDataURL("image/png"),n()}catch(e){throw e}},o=this.brandingCache.icon;i(o,!0).catch(()=>{i(o,!1).catch(()=>{t.src=e.toDataURL("image/png"),n()})})}else t.src=e.toDataURL("image/png"),n();else i(new Error("Failed to get canvas context"))},o.onerror=()=>{i(new Error("Failed to load QR code"))},o.src=r})}getDefaultFrontendUrl(){if("undefined"!=typeof window){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e)return"http://localhost:3002"}return"https://sdks.verification.local"}getDefaultApiUrl(){if("undefined"!=typeof window){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e)return"http://localhost:3003"}return"https://api.verification.local"}isIOSDevice(){return"undefined"!=typeof window&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)}isSafariBrowser(){return"undefined"!=typeof window&&(/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent))}isDesktopDevice(){if(!0===this.mockMobileDevice)return console.log("[SDK]: Mock mobile device mode enabled - treating device as mobile (no handoff)"),!1;if("undefined"==typeof window)return!1;const e=navigator.userAgent||navigator.vendor||window.opera,t=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile/i.test(e.toLowerCase()),n="ontouchstart"in window||navigator.maxTouchPoints>0,i=window.screen&&"orientation"in window.screen;return!t||t&&!n&&!i}resolveTargetElement(){return this.targetElement?"string"==typeof this.targetElement?document.querySelector(this.targetElement):this.targetElement:null}async probeIframeForKey(){return await this.ensureAuthFlowIdLoaded(),this.brandingCache?.authFlowId?new Promise(e=>{try{const t=window.location.origin,n=document.createElement("iframe");n.style.cssText="position: fixed; top: -9999px; left: -9999px; width: 1px; height: 1px; border: none; opacity: 0; pointer-events: none;";const i=new URL(`${this.frontendUrl}/probe.html`);i.searchParams.set("probe","true"),i.searchParams.set("origin",t);const r=this.brandingCache.authFlowId;let o;i.searchParams.set("authFlowId",r),console.log("[SDK-PROBE]: Adding authFlowId to probe:",r),n.src=i.toString();const s=()=>{window.removeEventListener("message",a),n.parentNode&&n.parentNode.removeChild(n),o&&clearTimeout(o)},a=async t=>{const n=t.data;if("KEY_CHECK_RESULT"===n?.type||"KEY_CHECK_FAILED"===n?.type){try{const e=new URL(this.frontendUrl).origin;if(t.origin!==e)return}catch(e){if(!t.origin.includes(window.location.hostname))return}"KEY_CHECK_RESULT"===n?.type?(s(),n.hasKey&&n.keyId?e(n.keyId):e(null)):"KEY_CHECK_FAILED"===n?.type&&(s(),e(null))}};window.addEventListener("message",a),document.body.appendChild(n),o=setTimeout(()=>{console.log("[SDK-PROBE]: Timeout reached (3000ms), no response from iframe"),s(),e(null)},3e3)}catch(t){console.error("[SDK-PROBE]: Error in probeIframeForKey:",t),e(null)}}):(console.error("[SDK-PROBE]: authFlowId is required but not available after fetch"),null)}async enrollWithPopup(){if(!this.authAppId)throw new Error("authAppId is required for enrollment. Please configure authAppId in SDK config.");const e=this.authAppId,t=await fetch(`${this.apiUrl}/api/apps/${e}`);if(!t.ok)throw new Error("Failed to load app configuration");if(!(await t.json()).app.authFlowId)throw new Error("App does not have an authentication flow configured");const n=`client_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,i=await fetch(`${this.apiUrl}/api/sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,clientId:n})});if(!i.ok){const e=await i.json();throw new Error(e.error||"Failed to create enrollment session")}const r=(await i.json()).data.sessionId;return new Promise((t,n)=>{const i=window.location.origin,o=new URLSearchParams({authAppId:e,sessionId:r,returnTo:"popup",origin:i});this.brandingCache?.primary&&o.set("primaryColor",this.brandingCache.primary),this.brandingCache?.background&&o.set("backgroundColor",this.brandingCache.background),this.brandingCache?.secondary&&o.set("secondaryColor",this.brandingCache.secondary),this.brandingCache?.textColor&&o.set("textColor",this.brandingCache.textColor);const s=`${this.frontendUrl}/enroll?${o.toString()}`;console.log("[SDK]: Opening enrollment popup:",s);const a=window.open(s,"trulyyou-enroll","width=600,height=700,scrollbars=yes,resizable=yes");if(!a)return void n(new Error("Failed to open enrollment popup. Please allow popups for this site."));let c,h,l=!1;const d=e=>{console.log("[SDK]: Enrollment popup message received:",e.origin,e.data);try{const t=new URL(this.frontendUrl).origin;if(e.origin!==t)return void console.log("[SDK]: Origin mismatch, ignoring message")}catch(t){if(!e.origin.includes(window.location.hostname))return void console.log("[SDK]: Origin mismatch, ignoring message")}if(e.data&&"ENROLLMENT_SUCCESS"===e.data.type){l=!0,c&&clearTimeout(c),h&&clearInterval(h),window.removeEventListener("message",d);const i=e.data.keyId;i?(console.log("[SDK]: Enrollment successful, keyId obtained from message:",i),t(i)):setTimeout(()=>{let e=null;this.brandingCache?.authFlowId&&(e=this.getKeyIdByAuthFlowId(this.brandingCache.authFlowId)),e?(console.log("[SDK]: Enrollment successful, keyId obtained (delayed) using authFlowId:",e),t(e)):n(new Error("Enrollment completed but no keyId found in message or localStorage"))},500)}else e.data&&"ENROLLMENT_ERROR"===e.data.type&&(l=!0,c&&clearTimeout(c),h&&clearInterval(h),window.removeEventListener("message",d),n(new Error(e.data.error||"Enrollment failed")))};window.addEventListener("message",d),c=setTimeout(()=>{l||(window.removeEventListener("message",d),h&&clearInterval(h),n(new Error("Enrollment timeout")))},6e5),h=setInterval(()=>{a.closed&&!l&&(clearInterval(h),clearTimeout(c),window.removeEventListener("message",d),n(new Error("Enrollment popup was closed")))},500)})}async signWithIframe(e){return new Promise((t,n)=>{try{const i=`sign_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,r=this.resolveTargetElement(),o=()=>{if(!r)return null;const e=document.createElement("div");e.id=`signing-overlay-${i}`,e.style.cssText="\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(255, 255, 255, 0.9);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n z-index: 10000;\n border-radius: 8px;\n ";const t=document.createElement("div");t.style.cssText=`\n width: 48px;\n height: 48px;\n border: 4px solid ${this.config.spinnerBgColor||"#e5e7eb"};\n border-top-color: ${this.config.spinnerColor||"#2563eb"};\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-bottom: 16px;\n `;const n=document.createElement("div");n.textContent="Authenticating...",n.style.cssText=`\n color: ${this.config.spinnerTextColor||"#6b7280"};\n font-size: 14px;\n font-weight: 500;\n `;const o=document.createElement("style");return o.textContent="\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(o),e.appendChild(t),e.appendChild(n),e},s=document.createElement("iframe");s.name=`trulyyou-sign-frame-${i}`,s.scrolling="no",s.setAttribute("scrolling","no"),s.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *");const a=e=>{if(null===e||"object"!=typeof e||e instanceof Array)return e;const t={};return Object.keys(e).sort().forEach(n=>{t[n]=a(e[n])}),t},c=((e,t,n,i)=>{const r=null==i?{}:i,o=a(null==e?{}:e),s=a(r),c=btoa(JSON.stringify(o)),h=btoa(JSON.stringify(s)),l={method:n,uriId:t,requestBody:c,queryParams:h};return{fullbase64:btoa(JSON.stringify(l)),sortedData:o,sortedQueryParams:s,encodedBody:c,encodedQueryParams:h}})(e.body||{},e.uri,e.method,{}),h={payload:c.fullbase64,apiCallStructure:e},l=btoa(JSON.stringify(h)),d=document.createElement("form");d.method="POST",d.action=`${this.frontendUrl}/sign/submit`,d.target=s.name,d.style.display="none";const u=document.createElement("input");u.type="hidden",u.name="attestationData",u.value=l,d.appendChild(u);const p=document.createElement("input");p.type="hidden",p.name="signId",p.value=i,d.appendChild(p);const g=document.createElement("input");g.type="hidden",g.name="mode",g.value="embedded",d.appendChild(g);const f=!this.invisible||this.isIOSDevice()||this.isSafariBrowser(),m=document.createElement("input");m.type="hidden",m.name="branding",m.value=JSON.stringify({primary:this.brandingCache?.primary||this.config.spinnerColor||"#2563eb",background:this.brandingCache?.background||"#ffffff",secondary:this.brandingCache?.secondary||"#2563eb",textColor:this.brandingCache?.textColor||this.config.spinnerTextColor||"#6b7280",spinnerColor:this.config.spinnerColor||this.brandingCache?.primary||"#2563eb",spinnerBgColor:this.config.spinnerBgColor||"#e5e7eb",spinnerTextColor:this.config.spinnerTextColor||this.brandingCache?.textColor||"#6b7280",visible:f}),d.appendChild(m);const b=document.createElement("input");b.type="hidden",b.name="authFlowId",b.value=this.brandingCache?.authFlowId||"",d.appendChild(b);if(this.mockMobileDevice||!this.isDesktopDevice())if(this.isIOSDevice()||this.isSafariBrowser())if(r){const e=window.getComputedStyle(r);"static"===e.position&&(r.style.position="relative");const t=r.style.height||e.height;if(!t||"auto"===t){const e=r.offsetHeight;e>0&&(r.style.height=`${e}px`)}s.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none; z-index: 9999;",r.appendChild(s)}else console.warn("[SDK]: Mobile iOS/Safari with no target element - using invisible iframe (WebAuthn may fail)"),s.style.cssText="position: fixed; top: -9999px; left: -9999px; width: 1px; height: 1px; border: none; opacity: 0; pointer-events: none;";else if(this.invisible)s.style.cssText="position: fixed; top: -9999px; left: -9999px; width: 1px; height: 1px; border: none; opacity: 0; pointer-events: none;";else if(r){const e=window.getComputedStyle(r);"static"===e.position&&(r.style.position="relative");const t=r.style.height||e.height;if(!t||"auto"===t){const e=r.offsetHeight;e>0&&(r.style.height=`${e}px`)}s.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none; z-index: 9999;",r.appendChild(s)}else console.warn("[SDK]: Mobile device with invisible=true but no target element - using invisible iframe"),s.style.cssText="position: fixed; top: -9999px; left: -9999px; width: 1px; height: 1px; border: none; opacity: 0; pointer-events: none;";else if(this.invisible)s.style.cssText="position: fixed; top: -9999px; left: -9999px; width: 1px; height: 1px; border: none; opacity: 0; pointer-events: none;";else if(r){const e=window.getComputedStyle(r);"static"===e.position&&(r.style.position="relative");const t=r.style.height||e.height;if(!t||"auto"===t){const e=r.offsetHeight;e>0&&(r.style.height=`${e}px`)}s.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none; z-index: 9999;",r.appendChild(s);const n=o();n&&r.appendChild(n)}else s.style.cssText="position: fixed; top: 0; left: 0; width: 100%; height: 100%; border: none; z-index: 9999; background: white;";let y;document.body.appendChild(d),s.parentNode||document.body.appendChild(s);let v=null;const w=()=>{window.removeEventListener("message",S),d.parentNode&&d.parentNode.removeChild(d),s.parentNode&&s.parentNode.removeChild(s),v&&v.parentNode&&v.parentNode.removeChild(v),y&&clearTimeout(y),r&&!this.invisible&&(r.style.height="")},S=e=>{try{const t=new URL(this.frontendUrl).origin;if(e.origin!==t)return}catch(t){if(!e.origin.includes(window.location.hostname))return}const r=e.data;if("SIGNING_COMPLETE"!==r?.type&&"SIGNATURE_COMPLETE"!==r?.type||r?.signId!==i)"SIGNING_ERROR"===r?.type&&r?.signId===i&&(w(),n(new Error(r.error||"Signing failed")));else if(console.log("[SDK]: Signature complete message received:",{type:r.type,hasSignature:!!r.signature||!!r.signatureBase64}),w(),r.error)n(new Error(r.error));else{const e=r.signature||r.signatureBase64;if(!e)return void n(new Error("No signature in response"));t({signature:e,keyId:r.keyId||""})}};window.addEventListener("message",S),d.submit(),setTimeout(()=>{d.parentNode&&d.parentNode.removeChild(d)},100),r&&!this.invisible&&(v=r.querySelector(`#signing-overlay-${i}`)),y=setTimeout(()=>{w(),n(new Error("Signing timeout"))},3e5)}catch(e){n(e)}})}async signWithWebSocketHandoff(e,t){return new Promise((n,r)=>{try{console.log("[SDK]: Desktop device detected, using WebSocket handoff with signatureId:",t);const o=this.brandingCache?.primary||"#2563eb",s=this.brandingCache?.name||"TrulyYou",a={signatureId:t,primaryColor:o,authAppName:s},c=btoa(JSON.stringify(a)),h=`${this.frontendUrl}/sign/${c}`,l=e=>{if(null===e||"object"!=typeof e||e instanceof Array)return e;const t={};return Object.keys(e).sort().forEach(n=>{t[n]=l(e[n])}),t},d=((e,t,n,i)=>{const r=null==i?{}:i,o=l(null==e?{}:e),s=l(r),a=btoa(JSON.stringify(o)),c=btoa(JSON.stringify(s)),h={method:n,uriId:t,requestBody:a,queryParams:c};return{fullbase64:btoa(JSON.stringify(h)),sortedData:o,sortedQueryParams:s,encodedBody:a,encodedQueryParams:c}})(e.body||{},e.uri,e.method,{}),u={payload:d.fullbase64,apiCallStructure:e};let p,g,f=!1,m=!0;try{const e=new URL(this.realtimeUrl.startsWith("ws://")||this.realtimeUrl.startsWith("wss://")?this.realtimeUrl:this.realtimeUrl.replace(/^http:/,"ws:").replace(/^https:/,"wss:"));p=e.hostname,g=e.port?parseInt(e.port,10):"wss:"===e.protocol?443:80,f="wss:"===e.protocol,m="wss:"===e.protocol}catch(e){console.warn("[SDK]: Error parsing realtimeUrl, using defaults:",e),p="127.0.0.1",g=6001}const b=this.config.pusherAppKey||"app-key",y={wsHost:this.config.pusherConfig?.wsHost||p,wsPort:this.config.pusherConfig?.wsPort||g,cluster:this.config.pusherConfig?.cluster||"",forceTLS:this.config.pusherConfig?.forceTLS??f,encrypted:this.config.pusherConfig?.encrypted??m,disableStats:this.config.pusherConfig?.disableStats??!0,enabledTransports:this.config.pusherConfig?.enabledTransports||["ws","wss"]};console.log("[SDK]: Initializing Pusher with config:",y);const v=new i(b,y),w=v.subscribe(t);console.log("[SDK]: Attempting to subscribe to Pusher channel:",t),w.bind("pusher:subscription_succeeded",()=>{console.log("[SDK]: ✅ Successfully subscribed to channel:",t),w.bind("countdown_update",e=>{console.log("[SDK]: 📊 Received countdown_update event:",e)}),w.bind("client-countdown_update",e=>{console.log("[SDK]: 📊 Received client-countdown_update event:",e)}),w.bind("countdown_expired",()=>{console.log("[SDK]: ⏰ Received countdown_expired event")}),w.bind("client-countdown_expired",()=>{console.log("[SDK]: ⏰ Received client-countdown_expired event")})});let S=null,C=null;const k=e=>{console.log("[SDK]: 📊 Received countdown_update event (early bind):",e),S?S(e):(console.warn("[SDK]: Countdown handler not ready yet, storing event"),setTimeout(()=>{S&&S(e)},100))};w.bind("countdown_update",k),w.bind("client-countdown_update",k);const _=()=>{console.log("[SDK]: ⏰ Received countdown_expired event (early bind)"),C&&C()};w.bind("countdown_expired",_),w.bind("client-countdown_expired",_),v.connection.bind("error",e=>{console.error("[SDK]: ❌ Pusher connection error:",e)}),v.connection.bind("state_change",e=>{console.log("[SDK]: 🔄 Pusher state change:",e.previous,"->",e.current)});let T,x=!1;v.connection.bind("connected",()=>{console.log("[SDK]: Pusher connected, waiting for counterparty..."),E&&I||w.trigger("client-device_connected",{type:"device_connected",deviceType:"desktop"}),T=setTimeout(()=>{A(),v.disconnect(),r(new Error("WebSocket handoff timeout - no counterparty connected"))},3e5)}),w.bind("client-device_connected",e=>{"device_connected"!==e.type||"mobile"!==e.deviceType||x||(x=!0,console.log("[SDK]: Mobile device connected (payload will be fetched from API)"))}),w.bind("client-signature_result",e=>{console.log("[SDK]: Signature result event received, raw data:",e),console.log("[SDK]: Data keys:",Object.keys(e||{})),console.log("[SDK]: counterpartyConnected:",x);const i=e?.signature||e?.data?.signature,o=e?.error||e?.data?.error,s=e?.keyId||e?.data?.keyId;if(console.log("[SDK]: Extracted values - signature:",!!i,"error:",o,"keyId:",s),console.log("[SDK]: Full socket data received:",JSON.stringify(e,null,2)),x||console.warn("[SDK]: Received signature result but counterparty not marked as connected yet. Waiting..."),clearTimeout(T),o)return console.error("[SDK]: Signature error:",o),A(),v.disconnect(),void r(new Error(o));if(i){console.log("[SDK]: Signature received successfully, resolving promise...");const r=s||"";r||console.warn("[SDK]: ⚠️ WARNING - No keyId received from Device B via socket! Data:",e),console.log("[SDK]: ✅ Using keyId from Device B:",r,"(extracted from socket)");const o={signature:i,keyId:r,signatureId:t};return console.log("[SDK]: Resolving with SigningResult:",{signatureLength:o.signature?.length,keyId:o.keyId,signatureId:o.signatureId,keyIdSource:r?"Device B (socket)":"MISSING - will fallback to localStorage"}),A(),v.disconnect(),void n(o)}console.error("[SDK]: Invalid signature result data - no signature or error:",JSON.stringify(e)),A(),v.disconnect(),r(new Error("Invalid signature result received"))}),v.connection.bind("error",e=>{console.error("[SDK]: Pusher connection error:",e),clearTimeout(T),v.disconnect(),r(new Error("Pusher connection error"))}),v.connection.bind("disconnected",()=>{console.log("[SDK]: Pusher disconnected"),clearTimeout(T)}),sessionStorage.setItem(`signHandoff_${t}`,JSON.stringify(u));const E=this.resolveTargetElement();let I=null,P=null;if(E){I=document.createElement("div"),I.id=`qr-handoff-${t}`,I.style.cssText="\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n max-width: 100%;\n max-height: 100%;\n overflow: hidden;\n background-color: rgba(255, 255, 255, 0.98);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n z-index: 10001;\n padding: 0;\n box-sizing: border-box;\n ";const e=document.createElement("div");e.style.cssText="\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n max-width: 100%;\n max-height: 100%;\n ";const n=document.createElement("div");n.style.cssText="\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 48px;\n height: 48px;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n ";const i=document.createElement("div");i.style.cssText=`\n width: 48px;\n height: 48px;\n border: 4px solid ${this.brandingCache?.primary?`${this.brandingCache.primary}20`:"#e5e7eb"};\n border-top-color: ${this.brandingCache?.primary||"#2563eb"};\n border-radius: 50%;\n animation: spin 1s linear infinite;\n `;const o=document.createElement("style");o.textContent="\n @keyframes spin {\n to { transform: rotate(360deg); }\n }\n ",document.head.appendChild(o),n.appendChild(i);const s=document.createElement("img");s.alt="QR Code for mobile signing (click to copy URL)",s.style.cssText="\n width: 100%;\n height: 100%;\n max-width: 100%;\n max-height: 100%;\n aspect-ratio: 1;\n object-fit: contain;\n cursor: pointer;\n transition: opacity 0.2s;\n position: relative;\n z-index: 2;\n display: none;\n opacity: 0;\n ",s.title="Click to copy URL to clipboard",s.addEventListener("load",()=>{console.log("[SDK]: QR image loaded"),n.style.display="none",s.style.display="block",s.style.opacity="1",setTimeout(()=>{c&&c()},50)}),s.addEventListener("error",()=>{console.error("[SDK]: QR image failed to load"),n.style.display="none",s.style.display="block",s.style.opacity="0.5"});const a=document.createElementNS("http://www.w3.org/2000/svg","svg");a.id=`countdown-svg-${t}`;const c=()=>{const n=s.getBoundingClientRect(),i=e.getBoundingClientRect(),r=Math.min(n.width,n.height),o=.05*r,c=r+2*o,h=n.left+n.width/2-i.left-c/2,l=n.top+n.height/2-i.top-c/2;console.log("[SDK]: QR positioning - centered offset:",h,l,"QR size:",r,"SVG size:",c),a.style.cssText=`\n position: absolute;\n top: ${l}px;\n left: ${h}px;\n width: ${c}px;\n height: ${c}px;\n pointer-events: none;\n z-index: 2;\n transform: rotate(0deg);\n transform-origin: center center;\n `,a.setAttribute("viewBox",`0 0 ${c} ${c}`),a.setAttribute("preserveAspectRatio","xMidYMid meet");const d=.04*c,u=.06*c;for(;a.firstChild;)a.removeChild(a.firstChild);const p=o-u/2,g=o-u/2,f=r+u,m=r+u,b=document.createElementNS("http://www.w3.org/2000/svg","rect");b.setAttribute("x",p.toString()),b.setAttribute("y",g.toString()),b.setAttribute("width",f.toString()),b.setAttribute("height",m.toString()),b.setAttribute("rx",d.toString()),b.setAttribute("ry",d.toString()),b.setAttribute("fill","none"),b.setAttribute("stroke","#e5e7eb"),b.setAttribute("stroke-width",u.toString()),a.appendChild(b);const y=document.createElementNS("http://www.w3.org/2000/svg","rect");y.id=`countdown-progress-${t}`,y.setAttribute("x",p.toString()),y.setAttribute("y",g.toString()),y.setAttribute("width",f.toString()),y.setAttribute("height",m.toString()),y.setAttribute("rx",d.toString()),y.setAttribute("ry",d.toString()),y.setAttribute("fill","none"),y.setAttribute("stroke",this.brandingCache?.primary||"#2563eb"),y.setAttribute("stroke-width",u.toString()),y.setAttribute("stroke-linecap","round"),y.setAttribute("stroke-linejoin","round");const v=d,w=2*(f+m-2*v)+2*Math.PI*v;return y.setAttribute("stroke-dasharray",w.toString()),y.setAttribute("stroke-dashoffset",w.toString()),y.style.transition="stroke-dashoffset 0.3s linear, stroke 0.3s linear",a.appendChild(y),{perimeter:w}};s.complete&&s.naturalWidth>0||s.addEventListener("load",()=>{c()}),c();let l={remaining:30,total:30};S=e=>{if(console.log("[SDK]: 🎯 Processing countdown_update:",e),!e||"countdown_update"!==e.type&&void 0===e.timeRemaining)console.warn("[SDK]: Invalid countdown_update data:",e);else{l={remaining:e.timeRemaining??l.remaining,total:e.totalTime??l.total},console.log(`[SDK]: 📊 Updating countdown rectangle: ${l.remaining}/${l.total}`);const n=a.getAttribute("viewBox"),i=n&&parseFloat(n.split(" ")[2])||100,r=.06*i,o=i/1.1,s=.04*i,c=2*(o+r+(o+r)-2*s)+2*Math.PI*s,h=l.remaining/l.total,d=c*(1-h),u=document.getElementById(`countdown-progress-${t}`);u&&u instanceof SVGRectElement&&(u.setAttribute("stroke-dashoffset",d.toString()),console.log(`[SDK]: 📊 Set stroke-dashoffset to: ${d} (percentage: ${h}, perimeter: ${c})`),l.remaining<=5?u.setAttribute("stroke","#ef4444"):l.remaining<=10?u.setAttribute("stroke","#f59e0b"):u.setAttribute("stroke",this.brandingCache?.primary||"#2563eb"))}},C=()=>{if(console.log("[SDK]: ⏰ Countdown expired - cleaning up and resetting state"),v&&"connected"===v.connection.state&&v.disconnect(),I){for(;I.firstChild;)I.removeChild(I.firstChild);I.parentNode&&I.parentNode.removeChild(I),I=null}const e=document.getElementById(`countdown-svg-${t}`);e&&e.parentNode&&e.parentNode.removeChild(e),A(),r(new Error("Countdown expired"))},w.bind("countdown_update",S),w.bind("client-countdown_update",S),w.bind("countdown_expired",C),w.bind("client-countdown_expired",C),e.appendChild(n),e.appendChild(s),e.appendChild(a),s.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(h),console.log("[SDK]: URL copied to clipboard:",h);const e=s.style.opacity||"1";s.style.opacity="0.7",setTimeout(()=>{s.style.opacity=e},200)}catch(e){console.error("[SDK]: Failed to copy URL to clipboard:",e);const t=document.createElement("textarea");t.value=h,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{document.execCommand("copy"),console.log("[SDK]: URL copied to clipboard (fallback method)")}catch(e){console.error("[SDK]: Fallback copy failed:",e)}document.body.removeChild(t)}}),this.generateQRCodeWithIcon(h,s).catch(e=>{console.warn("[SDK]: Error generating QR code with icon, using fallback:",e);const t=`https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(h)}`;s.src=t}),I.appendChild(e);const d=window.getComputedStyle(E);"static"===d.position&&(E.style.position="relative"),"visible"===d.overflow&&(E.style.overflow="hidden"),E.appendChild(I)}else{console.warn("[SDK]: No target element available, opening sign page in new window");const e=window.open(h,"_blank","width=600,height=700");if(!e)return v.disconnect(),void r(new Error("Failed to open sign page. Please allow popups for this site."));P=setInterval(()=>{e.closed&&(P&&clearInterval(P),clearTimeout(T),v.disconnect(),r(new Error("Sign window was closed")))},500)}let D=v;const A=()=>{I&&I.parentNode&&I.parentNode.removeChild(I),P&&clearInterval(P),clearTimeout(T),D&&(D.disconnect(),D=null),sessionStorage.removeItem(`signHandoff_${t}`)}}catch(e){r(e)}})}async signPayload(e,t,n){try{if(this.isDesktopDevice()){if(console.log("[SDK]: Desktop device detected, using WebSocket handoff (skipping key probe)"),!t)throw new Error("signatureId is required for desktop handoff");return await this.signWithWebSocketHandoff(e,t)}let i=n;if(i)console.log("[SDK]: Using existing keyId from enrollment:",i);else if(console.log("[SDK]: Mobile device detected, probing iframe for existing key..."),i=await this.probeIframeForKey(),!i&&(console.log("[SDK]: No valid active key found (missing, invalid, revoked, or expired), opening enrollment popup..."),i=await this.enrollWithPopup(),!i))throw new Error("Enrollment completed but no valid active key found");return console.log("[SDK]: Valid active key found, signing with keyId:",i),console.log("[SDK]: Using iframe signing for mobile device"),await this.signWithIframe(e)}catch(e){throw console.error("[SDK]: Signing error:",e),e}}async fetchWithSignature(e,t={}){let n;await this.ensureAuthFlowIdLoaded();try{console.log("[SDK]: fetchWithSignature called for:",e);const i=new URL(e),r=i.pathname+i.search,o=`${i.protocol}//${i.host}`,s={body:t.body?JSON.parse(t.body):{},uri:r,method:(t.method||"GET").toUpperCase(),headers:t.headers||{}};if(console.log("[SDK]: API call structure:",s),!this.authAppId)throw new Error("authAppId is required for signature validation. Please configure authAppId in SDK initialization.");try{n=`sig_${Date.now()}_${Math.random().toString(36).substring(2,15)}${Math.random().toString(36).substring(2,15)}${Math.random().toString(36).substring(2,15)}${Math.random().toString(36).substring(2,15)}`;let i=null;this.brandingCache?.authFlowId&&(i=this.getKeyIdByAuthFlowId(this.brandingCache.authFlowId));const a=localStorage.getItem("trulyYouUserId");let c;if(a)try{c=a}catch(e){console.warn("[SDK]: Failed to parse userId from localStorage:",e)}const h=this.isDesktopDevice();if(!h&&!i&&(console.log("[SDK]: No key found in localStorage, triggering enrollment..."),i=await this.probeIframeForKey(),!i)){if(console.log("[SDK]: No key in iframe either, opening enrollment popup..."),i=await this.enrollWithPopup(),!i)throw new Error("Enrollment completed but no key found. Please try again.");console.log("[SDK]: Enrollment successful, obtained keyId:",i)}const l=await fetch(`${this.apiUrl}/api/signatures/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:this.authAppId,baseUrl:o,endpoint:r,method:s.method,keyId:i||"",userId:c,apiCallStructure:s,signatureId:n,isHandoff:h})});if(!l.ok){const e=await l.json().catch(()=>({}));throw new Error("Failed to create signature: "+(e.error||"Creation request failed"))}{const e=await l.json();if(!e.success||!e.data?.signatureId)throw new Error("Failed to create signature document: "+(e.error||"No signatureId returned"));console.log("[SDK]: Signature document created with signatureId:",e.data.signatureId)}const d=await this.signPayload(s,n,i||void 0),u=d.keyId||"";console.log("[SDK]: 🔍 KeyId debug - signingResult.keyId:",u,"localStorage keyId:",i,"keyId type:",typeof u,"empty?:",""===u);const p=u||i||"";console.log("[SDK]: ✅ Final keyId for auth header:",p,"(from",u&&""!==u?"Device B":"localStorage fallback",")");const g=btoa(JSON.stringify({signature:d.signature,keyId:p,signatureId:n})),f=await fetch(e,{...t,headers:{...t.headers,"x-truly-auth":g}});return console.log("[SDK]: Request complete, status:",f.status),{response:f,signature:d.signature,signatureId:n}}catch(e){if(console.error("[SDK]: Signature creation error:",e),e.message&&e.message.includes("Countdown expired"))return{response:null,signature:"",signatureId:n||""};throw new Error("Signature creation failed: "+(e.message||"Unknown error"))}}catch(e){if(console.error("[SDK]: fetchWithSignature error:",e),e.message&&e.message.includes("Countdown expired")){return{response:null,signature:"",signatureId:n||""}}throw e}}async probeForKeyId(){if(await this.ensureAuthFlowIdLoaded(),!this.brandingCache?.authFlowId)return console.warn("[SDK-PROBE]: authFlowId is required but not available"),null;const e=this.brandingCache.authFlowId,t=this.getKeyIdByAuthFlowId(e);return t?(console.log("[SDK-PROBE]: Found keyId in same-origin localStorage"),t):(console.log("[SDK-PROBE]: KeyId not found in same-origin localStorage, probing TrulyYou frontend..."),await this.probeIframeForKey())}}export{r as TrulyYouSDK};
9
9
  //# sourceMappingURL=index.esm.js.map