@streamlayer/sdk-web 1.10.7 → 1.10.8

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/lib/cjs/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ci=require("pino"),S=require("@streamlayer/sl-eslib/interactive/interactive.common_pb"),ot=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_pb"),V=require("@streamlayer/sl-eslib/sdkSettings/sdkSettings.common_pb"),st=require("@streamlayer/sl-eslib/analytics/v1/invitations/invitations_pb"),ne=require("nanostores"),Zt=require("uuid"),M=require("@connectrpc/connect"),Nn=require("@connectrpc/connect-web"),Fn=require("@nanostores/query"),yr=require("@streamlayer/sl-eslib/sports/events/events_connect"),Ze=require("@streamlayer/sl-eslib/sdkSettings/client/client_connect"),gn=require("@streamlayer/sl-eslib/users/users_connect"),W=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_connect"),gr=require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_connect");require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_pb");const di=require("@streamlayer/sl-eslib/shortLinks/linksClient_connect"),v=require("@streamlayer/sl-eslib/analytics/v1/common/analytics.common_pb"),mr=require("@streamlayer/sl-eslib/analytics/v2/streaming/streaming_connect"),Dn=require("@streamlayer/sl-eslib/analytics/v1/interactions/interactions_pb"),ee=require("@streamlayer/sl-eslib/analytics/v1/notifications/notifications_pb");function li(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var br={exports:{}},U=br.exports={},se,ae;function en(){throw new Error("setTimeout has not been defined")}function tn(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?se=setTimeout:se=en}catch{se=en}try{typeof clearTimeout=="function"?ae=clearTimeout:ae=tn}catch{ae=tn}})();function vr(t){if(se===setTimeout)return setTimeout(t,0);if((se===en||!se)&&setTimeout)return se=setTimeout,setTimeout(t,0);try{return se(t,0)}catch{try{return se.call(null,t,0)}catch{return se.call(this,t,0)}}}function fi(t){if(ae===clearTimeout)return clearTimeout(t);if((ae===tn||!ae)&&clearTimeout)return ae=clearTimeout,clearTimeout(t);try{return ae(t)}catch{try{return ae.call(null,t)}catch{return ae.call(this,t)}}}var ge=[],Me=!1,Ae,dt=-1;function pi(){!Me||!Ae||(Me=!1,Ae.length?ge=Ae.concat(ge):dt=-1,ge.length&&Sr())}function Sr(){if(!Me){var t=vr(pi);Me=!0;for(var e=ge.length;e;){for(Ae=ge,ge=[];++dt<e;)Ae&&Ae[dt].run();dt=-1,e=ge.length}Ae=null,Me=!1,fi(t)}}U.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];ge.push(new wr(t,e)),ge.length===1&&!Me&&vr(Sr)};function wr(t,e){this.fun=t,this.array=e}wr.prototype.run=function(){this.fun.apply(null,this.array)};U.title="browser";U.browser=!0;U.env={};U.argv=[];U.version="";U.versions={};function be(){}U.on=be;U.addListener=be;U.once=be;U.off=be;U.removeListener=be;U.removeAllListeners=be;U.emit=be;U.prependListener=be;U.prependOnceListener=be;U.listeners=function(t){return[]};U.binding=function(t){throw new Error("process.binding is not supported")};U.cwd=function(){return"/"};U.chdir=function(t){throw new Error("process.chdir is not supported")};U.umask=function(){return 0};var hi=br.exports;const I=li(hi),yi=ci.pino({level:"trace",enabled:typeof window<"u"&&!!window.localStorage.getItem("SL_DEBUG"),browser:{write:t=>{console.log(t)}}}),ce=(t,e)=>yi.child({name:t},e);class gi extends Event{slEventBus;constructor(e,n){super(e),this.slEventBus=n}}const mi=ce("event-bus");class bi{name;listeners;constructor(e="sl-event-bus"){this.name=e,this.listeners=new Set}emit=(e,n)=>{const r=new gi(this.name,{...n,type:e});mi.debug(r,"Emitting event"),window.dispatchEvent(r)};listen(e){return window.addEventListener(this.name,e),this.listeners.add(e),()=>{this.off(e)}}off(e){window.removeEventListener(this.name,e),this.listeners.delete(e)}destroy=()=>{this.listeners.forEach(e=>{window.removeEventListener(this.name,e),this.listeners.delete(e)}),this.listeners.clear()}}class vi{}var me;(function(t){t[t.ONBOARDING=1]="ONBOARDING",t[t.QUESTION=2]="QUESTION",t[t.QUESTION_RESOLVED=3]="QUESTION_RESOLVED"})(me||(me={}));window.slStore=Object.create(null);class Ot{store;name;constructor(e,n){this.store=e,this.name=n}getStore(){return this.store}}const Si=t=>{const e=Object.keys(t);return ne.computed(e.map(n=>t[n].getStore()),(...n)=>Object.fromEntries(e.map((r,i)=>[r,n[i]])))};class Ie extends Ot{getValues=()=>this.getStore().get();getValue=e=>this.getStore().get()[e];setValue=(e,n)=>this.getStore().setKey(e,n);subscribe=(...e)=>this.getStore().subscribe(...e);unsubscribe=()=>this.getStore().off()}const H=t=>ne.map(t);var pe;(function(t){t.ORGANIZATION="ORGANIZATION",t.STREAM="STREAM"})(pe||(pe={}));const wi={[V.SdkOverlayType.BETTING]:"betting",[V.SdkOverlayType.GAMES]:"games",[V.SdkOverlayType.PUBLIC_CHAT]:"publicChat",[V.SdkOverlayType.TWITTER]:"twitter"};var Ye;(function(t){t.Ready="ready",t.Suspended="suspended"})(Ye||(Ye={}));class Tr{status;source;config;settings;listeners=new Set;settingsKey;constructor({settings:e,...n},r){this.settingsKey=wi[n.type],this.status=ne.atom(Ye.Suspended),this.config=new Ie(H(n),`feature:config:${this.settingsKey}`),this.settingsKey!==void 0&&e?.overlaySettings.case===this.settingsKey?this.settings=new Ie(H(e.overlaySettings.value),`feature:settings:${this.settingsKey}`):this.settings=new Ie(H({}),`feature:settings:${this.settingsKey}`),this.source=r}get featureConfig(){return this.config.getStore()}get featureSettings(){return this.settings.getStore()}registerEventListener(e){this.listeners.add(e)}enable=()=>{this.status.set(Ye.Ready)};disable=()=>{this.status.set(Ye.Suspended)};setFeatureConfig=({settings:e,...n})=>{let r;for(r in n)this.config.setValue(r,n[r]);if(e?.overlaySettings?.case!==void 0&&e?.overlaySettings.case===this.settingsKey){const i=e.overlaySettings.value;if(i!==void 0){let o;for(o in i)i[o]!==0&&i[o]!==""&&this.settings.setValue(o,i[o])}}};update=(e,n)=>{this.source===pe.STREAM&&n===pe.ORGANIZATION||(this.setFeatureConfig(e),this.source=n)};fireEvent(e){for(const n of this.listeners.values())try{n.onEvent(e)}catch(r){console.error(r)}}}class J extends Ot{getValue=()=>this.getStore().get();getValues(){throw new Error("not implemented")}setValue=e=>this.getStore().set(e);subscribe=e=>this.getStore().subscribe(e);unsubscribe=()=>this.getStore().off();listen(e){return this.getStore().listen(e)}get(){return this.getStore().get()}}const Q=t=>ne.atom(t);class te extends Ot{atomStore;constructor(e,n,r){super(e,`api:${n}`),this.atomStore=ne.atom(),r&&e.subscribe(i=>{const o=this.atomStore.get(),s=r(i,o);o!==s&&this.atomStore.set(s)})}getAtomStore=()=>this.atomStore;getValue=async()=>{const e=this.getStore();if(e.value===void 0)throw new Error("no store");return await e.value.promise,e.get().data};getValues=()=>this.getStore().get();setValue=e=>this.getStore().set({loading:!1,data:e?.data});subscribe=e=>this.getStore().subscribe(e);unsubscribe=()=>{throw new Error("not implemented")};invalidate=()=>{this.store.invalidate()};listen=e=>this.getStore().listen(e);get(){throw new Error("not implemented")}key=()=>this.getStore().key;off=()=>this.getStore().off()}const q=new bi;async function*Ti(t,e){for await(const n of e){t.response.message=n,t.received_at=Date.now(),t.id=Date.now();const r={type:"__GRPC_DEVTOOLS_EXTENSION__",data:t};window.postMessage(r),yield n}}const Ei=()=>t=>async e=>{const n={id:Date.now(),name:e.url,stream:e.stream,sent_at:Date.now(),request:{header:Object.fromEntries(e.header.entries()),message:e.message},response:{}};window.postMessage({type:"__GRPC_DEVTOOLS_EXTENSION__",data:n});try{const r=await t(e);if(n.received_at=Date.now(),n.response.header=Object.fromEntries(r.header.entries()),n.response.trailer=Object.fromEntries(r.trailer.entries()),e.stream){const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:{...n,stream:!0}};return window.postMessage(i),{...r,message:Ti(n,r.message)}}else{n.response.message=r.message,n.latency=n.received_at-n.sent_at;const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:n};window.postMessage(i)}return r}catch(r){n.received_at=Date.now(),n.response.trailer={"grpc-status":r.code,"grpc-message":r.rawMessage},n.response.message=r.rawMessage,n.latency=n.received_at-n.sent_at;const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:n};throw window.postMessage(i),r}};window.dispatchEvent(new CustomEvent("grpc_devtools_loaded"));function Er(t){return t instanceof DOMException&&(t.code===22||t.code===1014||t.name==="QuotaExceededError"||t.name==="NS_ERROR_DOM_QUOTA_REACHED")}class Ke{delimiter=":";prefix;storage;constructor(e="main",n=window.localStorage){this.prefix=`sl-sdk${this.delimiter}${e}`,this.storage=n}clear=()=>{for(const e in window.localStorage)e.startsWith(this.prefix)&&this.storage.removeItem(e)};generateKey=e=>`${this.prefix}${this.delimiter}${e.join(this.delimiter)}`;write=(...e)=>{const n=e.pop()||"",r=this.generateKey(e);try{this.storage.setItem(r,n)}catch(i){Er(i)&&this.storage===window.sessionStorage&&(window.sessionStorage.removeItem("slstreamlogs"),this.storage.setItem(r,n))}};read=(...e)=>{const n=this.storage.getItem(this.generateKey(e));return n===null?void 0:n};remove=(...e)=>{this.storage.removeItem(this.generateKey(e))}}var Z;(function(t){t.Init="init",t.Ready="ready",t.Connecting="connecting",t.Connected="connected",t.Disconnected="disconnected",t.Failed="failed",t.Reconnect="reconnect",t.Reconnecting="reconnecting"})(Z||(Z={}));const Rn=ce("grpc:stream");class Ai{params;streamCancel;method;options;headers;listeners;state;store;paramsListener;reconnectTimeout;attempt=0;constructor(e,n,r,i){const o={status:Z.Init,ts:new Date,log:[]};this.state=new Ie(H(o),`subscription:${i.name}:state`),this.options={...i,reconnectDelay:i.reconnectDelay??1e3,reconnectMaxDelay:i.reconnectMaxDelay??3e4,reconnectMaxAttempts:i.reconnectMaxAttempts??10,withStore:i.withStore??!1},this.headers=e,this.listeners=new Map,this.params=r,this.method=n,i.withStore&&(this.store=new J(Q(null),`subscription:${i.name}:store`)),"subscribe"in r&&typeof r.subscribe=="function"&&(this.paramsListener=r.subscribe(s=>{this.state.getValue("status")===Z.Connected&&(this.addStateLog(`params updated, reconnect => ${JSON.stringify(s)}`),this.reconnect())})),this.updateState(Z.Ready)}updateState=e=>{this.state.setValue("status",e),this.state.setValue("ts",new Date),this.addStateLog(`status => ${e}`)};addStateLog=e=>{const n=this.state.getStore().get().log,r=`${this.options.name} ${new Date().toISOString()}: ${e}`;if(n.push(r),this.state.setValue("log",n),localStorage.getItem("SL_DEBUG")){e.startsWith("received data")?Rn.trace({name:this.options.name,attempt:this.attempt},"received data"):Rn.trace({name:this.options.name,attempt:this.attempt},e);try{window.sessionStorage.setItem("slstreamlogs",window.sessionStorage.getItem("slstreamlogs")+`
2
- `+r)}catch(i){Er(i)&&window.sessionStorage.removeItem("slstreamlogs"),window.sessionStorage.setItem("slstreamlogs",r)}}};addListener=(e,n)=>this.listeners.has(e)?(this.addStateLog(`listener '${e}' not added, already exists`),()=>{}):(this.listeners.set(e,n),this.addStateLog(`listener '${e}' added`),()=>this.removeListener(e));removeListener=e=>{this.listeners.delete(e),this.addStateLog(`listener '${e}' removed`)};connect=()=>{this.updateState(Z.Connecting),this.streamCancel&&(this.addStateLog("disconnect prev connection"),this.streamCancel.abort(),this.streamCancel=void 0);const e="get"in this.params&&typeof this.params.get=="function"?this.params.get():this.params;(async()=>{this.streamCancel=new AbortController;try{const r={headers:this.headers.getValues(),signal:this.streamCancel.signal},i=this.method(e,r);for await(const o of i)this.attempt=0,this.onData(o)}catch(r){r instanceof M.ConnectError&&r.code!=M.Code.Canceled&&this.onStreamError(r)}})(),this.updateState(Z.Connected)};disconnect=()=>{this.streamCancel&&this.streamCancel.abort(),this.listeners.clear(),this.paramsListener?.(),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.updateState(Z.Disconnected)};reconnect=()=>{if(this.reconnectTimeout)this.addStateLog("already reconnecting");else if(this.attempt<this.options.reconnectMaxAttempts){this.updateState(Z.Reconnect);const e=Math.min(this.options.reconnectMaxDelay,Math.pow(2,this.attempt)*this.options.reconnectDelay),n=Math.round(e*(1+Math.random())/2);this.reconnectTimeout=setTimeout(()=>{this.attempt++,this.updateState(Z.Reconnecting),this.addStateLog(`reconnect attempt ${this.attempt} after ${n}ms`),this.connect(),this.reconnectTimeout=void 0},n)}else this.addStateLog("max reconnect attempts reached"),this.disconnect()};getStore=()=>this.store?.getStore();onData=e=>{try{this.addStateLog(`received data => ${JSON.stringify(e)}`),this.store&&this.store.setValue(e);for(const[,n]of this.listeners)n(e);this.addStateLog(`data routed to ${this.listeners.size} listeners`)}catch(n){this.addStateLog(`error process data => ${n}`)}};onStreamError=e=>{if(this.addStateLog(`error => ${e?JSON.stringify(e):"undefined"}}`),e!==void 0){if(e instanceof M.ConnectError&&e.code!==M.Code.Canceled){this.updateState(Z.Failed),this.state.setValue("error",e),e.code===M.Code.Unknown&&e.cause==="missing trailer"&&(this.attempt=0),this.reconnect();return}this.disconnect()}}}const Ii=new Set([M.Code.Unknown,M.Code.Internal,M.Code.DeadlineExceeded,M.Code.ResourceExhausted,M.Code.FailedPrecondition,M.Code.Unavailable,M.Code.DataLoss]),Vn=ce("grpc:retry"),Oi=t=>async e=>{const n=e.contextValues.get(nn.retryAttempts),r=300,i=e.contextValues.get(nn.retryDelay);if(e.stream||n===0)return t(e);Vn.trace({url:e.url,attempts:n,maxDelay:i},"retry options");for(let o=0;;o++)try{return await t(e)}catch(s){Vn.trace({attempt:o,error:s,url:e.url},"retry attempt");const a=M.ConnectError.from(s);if(o>=n||!(a instanceof M.ConnectError)||!Ii.has(a.code))throw s;const u=Math.min(i,Math.pow(2,o)*r),d=Math.round(u*(1+Math.random())/2);await new Promise(c=>setTimeout(c,d))}},nn={retryAttempts:M.createContextKey(10,{description:"Number of attempts to retry"}),retryDelay:M.createContextKey(3e4,{description:"Max delay between retries in milliseconds"})},ki=()=>{const t=localStorage.getItem("sl-device-id");if(t)return t;const e=Zt.v4();return localStorage.setItem("sl-device-id",e),e},_i=()=>navigator.userAgentData?.platform||navigator.platform;class $n{toJsonOptions={emitDefaultValues:!1,enumAsInteger:!0,useProtoFieldName:!1};transport;streamTransport;nanoquery;host;$headers;interceptors=[];clients;streamClients;subscriptions;opts;constructor(e,n){this.host=e,this.opts=n,this.$headers=new Ie(H({"sl-device-id":ki(),"sl-device-os":_i()}),"transport:headers"),this.initInterceptors(),this.clients=new Map,this.streamClients=new Map,this.subscriptions=new Map;const[r,i,o]=Fn.nanoquery({dedupeTime:n?.dedupeTime,refetchInterval:n?.refetchInterval});this.nanoquery={createFetcherStore:r,createMutatorStore:i,utils:o},this.transport=Nn.createGrpcWebTransport({baseUrl:e,defaultTimeoutMs:1e4,interceptors:this.interceptors}),this.streamTransport=Nn.createGrpcWebTransport({baseUrl:e,interceptors:this.interceptors})}addSubscription=(e,n,r)=>{const i=this.subscriptions.get(n);if(i)return i;const o=new Ai(this.$headers,e,n,r);return this.subscriptions.set(n,o),o};removeSubscription=e=>{e.disconnect(),this.subscriptions.delete(e.params)};disconnect=()=>{for(const[i,o]of this.subscriptions)o.disconnect(),this.subscriptions.delete(i);this.clients.clear(),this.streamClients.clear(),this.subscriptions.clear();const[e,n,r]=Fn.nanoquery({dedupeTime:this.opts?.dedupeTime,refetchInterval:this.opts?.refetchInterval});this.nanoquery={createFetcherStore:e,createMutatorStore:n,utils:r}};registerInterceptor=e=>{this.interceptors.push(e)};removeInterceptor=e=>{this.interceptors=this.interceptors.filter(n=>n!==e)};getClient=e=>{const n=e.typeName;if(this.clients.has(n))return this.clients.get(n);const r=M.createClient(e,this.transport);return this.clients.set(n,r),r};getStreamClient=e=>{const n=`stream-${e.typeName}`;if(this.clients.has(n))return this.clients.get(n);const r=M.createClient(e,this.streamTransport);return this.clients.set(n,r),r};createPromiseClient=(e,{params:n=[],method:r})=>{const i=this.getClient(e),o=e.methods[r].name,s=[e.typeName,o.charAt(0).toLowerCase()+o.slice(1),...Array.isArray(n)?n:[n]],a=[e.typeName,o.charAt(0).toLowerCase()+o.slice(1)];return{client:i,createRequestOptions:d=>{const c=M.createContextValues();for(const f in d){const p=nn[f];c.set(p,d[f])}return c},queryKey:s,queryKeyStr:a.join("")}};createStreamClient=e=>({client:this.getStreamClient(e)});setSdkKey=e=>{this.$headers.setValue("sdk",e)};setAuth=(e,n)=>{this.$headers.setValue("authorization",e),this.$headers.setValue("sl-user-id",n)};setHeader=(e,n)=>this.$headers.setValue(e,n);getHeader=e=>this.$headers.getValue(e);getHeaders=()=>this.$headers.getValues();initInterceptors=()=>{if(this.interceptors.length!==0)return;const e=n=>r=>{const i=this.$headers.getValues();for(const o in i)r.header.set(o,i[o]);return n(r)};this.interceptors.push(e),this.interceptors.push(Ei()),this.opts?.retryable&&this.interceptors.push(Oi)}}const Ci=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(yr.Events,{method:"retrieveEventId",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s||typeof s!="string")return"";try{return(await n.retrieveEventId({id:s})).data?.id||""}catch{return""}}})},Pi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"getStream",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>s?(await n.getStream({id:s})).data?.attributes:void 0})},Li=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(yr.Events,{method:"summary",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>s?(await n.summary({id:s})).data?.attributes:void 0})},Ni=(t,e)=>{const{queryKey:n,client:r}=e.createPromiseClient(gn.Users,{method:"me",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>{if(!e.getHeader("authorization"))return{data:void 0};const{data:o}=await r.me({});return{data:o}}})},Fi=t=>{const{client:e,createRequestOptions:n}=t.createPromiseClient(gn.Users,{method:"bypassAuth"}),r=n({retryAttempts:0});return({userKey:i,schema:o,init:s,inviterKey:a})=>e.bypassAuth({userKey:i,schema:o,init:s,inviterKey:a},{contextValues:r})},Di=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>(await n.get({})).data?.attributes})},Ri=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"getOrganization",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>{const i=await n.getOrganization({});return i.data?{...i.data.attributes,id:i.data.id}:void 0}})},Vi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"getOrganizationAdvertising",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>(await n.getOrganizationAdvertising({})).data?.attributes})},$i=(t,e,n)=>{t.transport=new $n(e.host,{dedupeTime:1e3*60*5,refetchInterval:1e3*60*5,retryable:!0}),t.analyticsTransport=new $n(e.analyticsHost),t.sdk.host=t.transport.host,t.transport.setSdkKey(e.sdkKey),t.transport.setHeader("sl-sdk-version",e.version||"-"),t.transport.$headers.subscribe(r=>{t.analyticsTransport.$headers.getStore().set(r)}),t.sdk.onMount({name:"transport"},()=>()=>{t.transport.disconnect(),t.analyticsTransport.disconnect()}),n()};var fe;(function(t){t.SCHEMA="schema",t.EXTERNAL_TOKEN="eToken",t.TOKEN="token"})(fe||(fe={}));class $e extends Ke{constructor(){super("user")}setSchema=e=>{this.write(fe.SCHEMA,e)};getSchema=()=>this.read(fe.SCHEMA);setToken=e=>{this.write(fe.TOKEN,e)};getToken=()=>this.read(fe.TOKEN);setExternalToken=e=>{this.write(fe.EXTERNAL_TOKEN,e)};getExternalToken=()=>this.read(fe.EXTERNAL_TOKEN);removeToken=()=>{this.remove(fe.TOKEN)}}var he;(function(t){t.DISABLED="disabled",t.INITIALIZATION="initialization",t.READY="ready",t.FAILED="failed",t.SUSPENDED="suspended"})(he||(he={}));const Bi=t=>{const e=new $e,n=new J(Q(e.getExternalToken()),"userKey"),r=new J(Q(e.getToken()),"userToken"),i=new te(Ni(r.getStore(),t),"user",({data:s,error:a,loading:u},d)=>{if(!a)return s?.data?.id?s.data.id:u===!1?void 0:d}),o=new te(Di(r.getStore(),t),"userSettings");return{userKey:n,userToken:r,user:i,userSettings:o}},Mi=t=>{const e=new J(Q(void 0),"providerStreamId"),n=new te(Ci(e.getStore(),t),"slStreamId",o=>o?.data),r=new te(Pi(n.getAtomStore(),t),"streamSettings"),i=new te(Li(n.getAtomStore(),t),"streamSettings");return n.getAtomStore().listen(o=>{(o===""||o===void 0)&&(r.getStore().mutate(void 0),i.getStore().mutate(void 0))}),{providerStreamId:e,slStreamId:n,streamSettings:r,streamSummary:i}},qi=t=>{const e=new J(Q(void 0),"enabled"),n=new J(Q(he.DISABLED),"status"),r=new te(Ri(e.getStore(),t),"organizationSettings",a=>a?.data?.id),i=new te(Vi(r.getAtomStore(),t),"organizationAdvertising"),o=Bi(t),s=Mi(t);return{enabled:e,status:n,providerStreamId:s.providerStreamId,slStreamId:s.slStreamId,streamSettings:s.streamSettings,streamSummary:s.streamSummary,user:o.user,userKey:o.userKey,userToken:o.userToken,userSettings:o.userSettings,organizationSettings:r,organizationAdvertising:i}};class Ui extends Ot{stores;constructor(e){const n=qi(e),r=Si(n);super(r,"core"),this.stores=n}getValue(){throw new Error("Not implemented")}getValues(){return this.stores}setValue(){throw new Error("Not implemented")}subscribe=e=>{let n;for(n in this.stores){const r=e[n];n in e&&r!==void 0&&this.stores[n].subscribe(e[n])}};unsubscribe=()=>this.getStore().off()}const Qi=(t,e,n)=>{t.store=new Ui(t.transport),t.stores=t.store.getValues(),t.sdk.enabled=t.stores.enabled.getStore(),t.sdk.status=t.stores.status.getStore(),t.sdk.sdkStore=Object.fromEntries(Object.entries(t.stores).map(([r,i])=>[r,i.getStore()])),t.sdk.organizationStore=()=>t.stores.organizationSettings.getStore(),t.sdk.streamStore=()=>t.stores.streamSettings.getStore(),t.sdk.streamSummary=()=>t.stores.streamSummary.getStore(),t.storeUnsubscribe=()=>{t.store.unsubscribe()},n()},ji=t=>{const{client:e}=t.createPromiseClient(gr.Leaderboard,{method:"list"});return n=>e.list(n)},Ar=t=>{const{client:e}=t.createPromiseClient(gr.Leaderboard,{method:"summary"});return n=>e.summary(n)},xi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(gn.Users,{method:"getFriends",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s)return[];try{return(await n.getFriends({})).data}catch{return[]}}})},Gi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(W.Feed,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>(await n.get({eventId:s})).data?.attributes,refetchInterval:0,dedupeTime:1e3*60*60})},Ki=(t,e,n)=>{const{client:r,queryKey:i}=n.createPromiseClient(W.Feed,{method:"syncQuestion",params:[t,e?"true":""]});return n.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>{if(!a||u)return;const d=await r.syncQuestion({filter:{eventId:a}});if(d.data?.attributes?.question?.type!==S.QuestionType.PROMOTION)return d.data?.attributes},dedupeTime:1e3*60*10,refetchInterval:0})},zi=async(t,e)=>{const{client:n}=e.createPromiseClient(W.Feed,{method:"item",params:[t]});return(await n.item({id:t})).data},Hi=(t,e)=>{const{client:n}=e.createStreamClient(W.Feed),r=ne.atom({eventId:t.get()||"",feedId:""});return t.subscribe((o="")=>{r.set({eventId:o,feedId:""})}),e.addSubscription(n.subscription,r,{name:"feedSubscription"})},Wi=(t,e)=>{const{client:n}=e.createStreamClient(W.Feed);return e.addSubscription(n.questionSubscription,{questionId:t},{name:"questionSubscription"})},rn=async(t,e)=>{const{client:n}=e.createPromiseClient(W.Feed,{method:"questionByUser",params:[t]});return(await n.questionByUser({questionId:t})).data?.attributes?.question},qe=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(W.Feed,{method:"questionByUser",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>(await n.questionByUser({questionId:s})).data?.attributes?.question,dedupeTime:1e3*60*5})},Ir=async(t,e)=>{if(!t)return;const{client:n}=e.createPromiseClient(W.Feed,{method:"getQuestion",params:[t]}),r=await n.getQuestion({id:t});if(!r.data?.attributes)return;const{options:i,notification:o,...s}=r.data.attributes,a=i?.options.case==="promotion"?i?.options.value:void 0;return{id:s.id,question:s,promotion:a,notification:o}},Yi=(t,e,n,r)=>{const{client:i,queryKey:o}=r.createPromiseClient(W.Feed,{method:"list",params:[t,e,n?"true":""]});return r.nanoquery.createFetcherStore(o,{fetcher:async(s,a,u,d,c)=>!u||c?[]:(await i.list({eventId:u,filter:{types:d===Se.ALLOWED?[]:[S.QuestionType.FACTOID,S.QuestionType.PROMOTION,S.QuestionType.TWEET],statuses:[S.QuestionStatus.ACTIVE,S.QuestionStatus.RESOLVED]}})).data,dedupeTime:0,refetchInterval:0})},Ji=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(W.Feed,{method:"list",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s)return;const u=(await n.list({eventId:s,filter:{types:[S.QuestionType.PROMOTION],statuses:[S.QuestionStatus.ACTIVE]},pagination:{page:0,pageSize:1}})).data?.[0];if(u.type==="promotion")return Ir(u.id,e)},dedupeTime:0,refetchInterval:0})},Xi=(t,e,n,r,i)=>{const{client:o,queryKey:s}=i.createPromiseClient(W.Feed,{method:"betPack",params:[t,e,n]});return i.nanoquery.createFetcherStore(s,{fetcher:async(a,u,d,c,f)=>{if(!d||!c||!f)return{timestamp:Date.now(),data:null};const p=await o.betPack({eventId:d,types:[S.QuestionType.PREDICTION],statuses:[S.QuestionStatus.ACTIVE,S.QuestionStatus.RESOLVED],limit:5,sort:{field:"activated_at",order:"asc"}});return!p.data||!p.data.length?{timestamp:Date.now(),data:null}:{timestamp:Date.now(),data:p.data?.reduce((w,E)=>{const g=E?.attributes?.question;if(!g?.id)return w;const m={eventId:d,userId:c,organizationId:f};return r.isBetPackQuestionReceived(m,g.id)||(q.emit("poll",{action:"received",payload:{questionId:g.id,questionType:g.type}}),r.saveBetPackQuestionReceived(m,g.id)),{...w,[g.id]:g}},{})}},dedupeTime:0,refetchInterval:0})},Zi=(t,e,n)=>{const r=ne.batched([e,n],()=>{const a=e.get();if(!a)return;const u=n.get().data?.find(c=>c.id===a?.questionId),d=a?.question?.openedFrom;return u?(u.openedFrom=d,u):a.question}),i=ne.batched(r,a=>a&&a.type==="question"?a.id:void 0),o=qe(i,t);return{$store:r,$extendedStore:o,updateExtendedQuestion:a=>{const u=o.get().data,d=(c,f)=>{if(!c||!f)return c||f||[];const p=[];for(let w=0;w<c.length;w++)p.push({...c[w],...f[w],correct:c[w].correct,youVoted:c[w].youVoted,pointsEarned:c[w].pointsEarned});return p};o.mutate({...a,options:u?.options,subject:u?.subject,appearance:u?.appearance,answers:d(u?.answers,a?.answers)})}}};var mt;(function(t){t.SHOWED="showed"})(mt||(mt={}));class eo extends Ke{constructor(){super("advertisement")}setShowed=e=>{this.write(mt.SHOWED,e,"true")};isViewed=e=>this.read(mt.SHOWED,e)}const to=t=>{const e=t.data?.attributes?.question;if((t.data?.attributes?.feedItem?.type==="promotion"?t.data.attributes.feedItem:void 0)===void 0||!e)return;const{options:r,notification:i,...o}=e,s=r?.options.case==="promotion"?r.options.value:void 0;return{id:o.id,question:o,notification:i,promotion:s}},at=t=>t.startsWith("http://")||t.startsWith("https://")?new URL(t).toString():t,no=({gamOptions:t,gamBaseUrl:e})=>{const n=`${e}?`,r=[];for(const i in t){const o=i.replace(/([a-zA-Z])(?=[A-Z])/g,"$1_").toLowerCase(),s=t[i];if(s)if(typeof s=="string")r.push(`${o}=${at(s)}`);else if(Array.isArray(s))r.push(`${o}=${s.map(at).join(",")}`);else{const a=Object.entries(s).map(([u,d])=>Array.isArray(d)?`${u}=${d.map(at).join(",")}`:typeof d=="string"?`${u}=${at(d)}`:`${u}=${d}`).join("&").replaceAll("=","%3D").replaceAll("&","%26").replaceAll(",","%2C");r.push(`${o}=${a}`)}}return n+r.join("&")},Fe=t=>(t?.promotion?.type===S.PromotionType.INGAME_IAB11_LBAR||t?.promotion?.type===S.PromotionType.INGAME_IAB21_LBAR)&&!!t.promotion.additionalBanner?.imageUrl,ro=(t,e,n)=>{let r=!1;const i=n.transport,o=ce("advertisement"),s=new eo,a=H({}),u=Ji(t,i),d=g=>{const m=a.get(),T=m.data?.question.id,D=m.data?.promotion?.type;T&&(q.emit("advertisement",{action:"opened",payload:{id:T,type:D,hasBanner:Fe(m.data),openedFrom:g?.fromNotification?"notification":"auto"}}),g?.fromNotification&&(a.setKey("hasNotification",!1),q.emit("advertisement",{action:"notification-opened",payload:{id:T,type:D,hasBanner:Fe(m.data)}})))},c=()=>{const g=a.get(),m=g.data?.question.id,T=g.data?.promotion?.type,D=a.get()?.isOpened;m&&!D&&(o.debug({id:m},"markAsViewed: %o"),s.setShowed(m),a.setKey("isOpened",!0),q.emit("advertisement",{action:"viewed",payload:{id:m,type:T,hasBanner:Fe(g.data)}}))},f=(g,m)=>{m?a.set({loading:!1,error:void 0,data:m,hasNotification:m?.notification?.enabled===S.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>p(m.question.id),togglePause:T=>w(m.question.id,T),isViewed:!!s.isViewed(m.question.id)}):(a.setKey("loading",!0),Ir(g,i).then(T=>a.set({loading:!1,error:void 0,data:T,hasNotification:T?.notification?.enabled===S.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>p(T?.question.id),togglePause:D=>w(T?.question.id,D),isViewed:T&&!!s.isViewed(T.question.id)})).catch(T=>a.set({loading:!1,error:T,data:void 0})))};a.subscribe((g,m)=>{if(!(g.data?.id===m?.data?.id&&g.isPaused!==m?.isPaused)){if(g.data?.promotion?.type===S.PromotionType.EXTERNAL_AD&&!g?.externalAd&&g.data.promotion.adCampaigns?.gamOptions&&g.data.promotion.adCampaigns?.gamBaseUrl){const T=no(g.data.promotion.adCampaigns);a.setKey("externalAd",{type:"gam",url:T})}g.data?.promotion&&!g.isOpened&&(q.emit("advertisement",{action:"received",payload:{id:g.data.question.id,type:g.data.promotion.type,hasNotification:!!g.hasNotification,hasBanner:Fe(g.data),isViewed:!!s.isViewed(g.data.question.id)},skipAnalytics:g.data.question.id===m?.data?.question.id}),g.data.question.id!==m?.data?.question.id&&!s.isViewed(g.data.question.id)&&q.emit("advertisement",{action:"notification-received",payload:{id:g.data.question.id,type:g.data.promotion.type,hasNotification:!0,hasBanner:Fe(g.data),isViewed:!1}})),!g?.data&&m?.data&&q.emit("advertisement",{action:"closed",payload:{id:m.data.question.id,type:m.data.promotion?.type,hasNotification:!!m.hasNotification,hasBanner:Fe(m.data),isViewed:!!s.isViewed(m.data.question.id)}})}});const p=g=>{(!g||a.get()?.data?.question.id===g)&&a.set({})},w=(g,m)=>{a.get()?.data?.question.id===g&&a.setKey("isPaused",m)};return{connect:()=>{r||(r=!0,u.subscribe((g,m)=>{g.data&&(!m?.data||g.data.id!==m.data.id)&&f(g.data.question.id,g.data)}),e.addListener("promotion",g=>{const m=to(g);if(m){if(m.question.status===S.QuestionStatus.RESOLVED){p(m.question.id),o.debug({promotion:m},"resolved: %o");return}if(m.question.status===S.QuestionStatus.ACTIVE){o.debug({promotion:m},"active: %o"),f(m.question.id,m);return}o.debug({promotion:m},"skip: %o")}}))},hide:p,show:f,open:d,markAsViewed:c,$store:a}};var oe;(function(t){t.ONBOARDING="onboarding",t.ONBOARDING_IO="onboarding_io",t.BET_PACK_ITEM_RECEIVED="bp-item-received",t.QUESTION_OPENED="q-opened"})(oe||(oe={}));class io extends Ke{constructor(){super("gamification-session",window.sessionStorage)}writeValue=(e,n)=>{this.write(...e,n)};readValue=e=>this.read(...e)}class oo extends Ke{sessionStorage;constructor(){super("gamification"),this.sessionStorage=new io}saveBetPackQuestionReceived=({userId:e,eventId:n,organizationId:r},i)=>{this.write(oe.BET_PACK_ITEM_RECEIVED,r,e,n,i)};isBetPackQuestionReceived=({userId:e,eventId:n,organizationId:r},i)=>!!this.read(oe.BET_PACK_ITEM_RECEIVED,r,e,n,i);saveQuestionOpened=({userId:e,eventId:n,organizationId:r},i)=>{this.write(oe.QUESTION_OPENED,r,e,n,i)};isQuestionOpened=({userId:e,eventId:n,organizationId:r},i)=>!!this.read(oe.QUESTION_OPENED,r,e,n,i);saveOnboardingStatus=({userId:e,eventId:n,organizationId:r},i)=>{this.write(oe.ONBOARDING,r,e,n,i)};getOnboardingStatus=({userId:e,eventId:n,organizationId:r})=>this.read(oe.ONBOARDING,r,e,n);setOnboardingInstantOpen=({userId:e,eventId:n,organizationId:r})=>{this.sessionStorage.writeValue([oe.ONBOARDING_IO,r,e,n],"1")};getOnboardingInstantOpen=({userId:e,eventId:n,organizationId:r})=>this.sessionStorage.readValue([oe.ONBOARDING_IO,r,e,n])}var Se;(function(t){t.ALLOWED="allowed",t.DISALLOWED="disallowed"})(Se||(Se={}));class so{slStreamId;organizationId;userId;interactiveAllowed;openedQuestionId;openedQuestion;activeQuestionId;feedList;betPack;moderationId;moderation;feedSubscription;questionSubscription;advertisement;storage;notifications;log;transport;cancels=new Set;constructor(e){this.transport=e.transport,this.log=ce("gamification-background"),this.storage=new oo,this.slStreamId=e.stores.slStreamId.getAtomStore(),this.organizationId=e.stores.organizationSettings.getAtomStore(),this.userId=e.stores.user.getAtomStore(),this.moderationId=new J(Q(void 0),"moderationId").getStore(),this.interactiveAllowed=new J(Q(Se.DISALLOWED),"interactiveAllowed").getStore(),this.openedQuestionId=new J(Q(void 0),"openedQuestionId").getStore(),this.notifications=e.notifications,this.moderation=new te(Gi(this.slStreamId,e.transport),"gamification:moderation");const n=!!e.sdk.options.get().betPack;this.feedList=new te(Yi(this.slStreamId,this.interactiveAllowed,n,e.transport),"gamification:feedList"),this.betPack=new te(Xi(this.slStreamId,this.userId,this.organizationId,this.storage,e.transport),"gamification:betPack"),this.activeQuestionId=Ki(this.slStreamId,n,e.transport),this.openedQuestion=Zi(e.transport,this.openedQuestionId,this.feedList.getStore()),this.cancels.add(this.openedQuestionId.listen(r=>{this.log.debug({item:r},"received question"),r?.questionId?(this.questionSubscription=Wi(r.questionId,e.transport),this.questionSubscription.addListener("feed-subscription-opened-question",async i=>{const o=i.data?.attributes?.question;if(this.openedQuestion.updateExtendedQuestion(o),o?.type===S.QuestionType.PREDICTION&&(o.status===S.QuestionStatus.ACTIVE||o.status===S.QuestionStatus.RESOLVED)){const s=this.betPack.getValues().data?.data||{};if(s?.[o.id]||Object.keys(s).length<5){const u=qe(o.id,this.transport),d=u.subscribe(()=>{});await u.get().promise;let c=u.get().data;c||(c=await rn(o.id,this.transport)),d(),window.requestAnimationFrame(()=>{u.invalidate()}),this.betPack.getStore().mutate({timestamp:Date.now(),data:{...s,[o.id]:c}})}}}),this.questionSubscription.connect()):(this.log.info("cleanup on close question"),this.questionSubscription!==void 0&&(e.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0))})),this.feedSubscription=Hi(this.slStreamId,e.transport),this.cancels.add(this.feedSubscription.addListener("bet-pack-update",async r=>{const i=r.data?.attributes?.question;if(i?.type===S.QuestionType.PREDICTION&&(i.status===S.QuestionStatus.ACTIVE||i.status===S.QuestionStatus.RESOLVED)){const o=this.betPack.getValues().data?.data||{};if(o?.[i.id]||Object.keys(o).length<5){const a=qe(i.id,this.transport),u=a.subscribe(()=>{});await a.get().promise;let d=a.get().data;d||(d=await rn(i.id,this.transport)),u(),window.requestAnimationFrame(()=>{a.invalidate()}),this.betPack.getStore().mutate({timestamp:Date.now(),data:{...o,[i.id]:d}})}}})),this.cancels.add(this.feedSubscription.addListener("feed-subscription-active-question",r=>{const i=this.activeQuestionId.get().data?.question?.id,o=r.data?.attributes?.question;if(!(!o||o.type===S.QuestionType.PROMOTION)){if(o.status===S.QuestionStatus.RESOLVED){i===o.id&&this.activeQuestionId.mutate(void 0);return}window.requestAnimationFrame(()=>{this.activeQuestionId.mutate(r.data?.attributes)})}})),this.cancels.add(this.feedSubscription.addListener("moderation update",r=>{window.requestAnimationFrame(()=>{r.data?.attributes?.question===void 0&&r.data?.attributes?.moderation&&this.moderation.invalidate()})})),this.cancels.add(this.activeQuestionId.subscribe((r,i)=>{r.data?.feedItem&&r.data?.feedItem?.id!==i?.data?.feedItem?.id&&e.onQuestionActivate({stage:"activate",id:r.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:r.data.feedItem.id})),hasNotification:!0,type:r.data.feedItem.type}),!r.data?.feedItem&&i?.data?.feedItem&&e.onQuestionActivate({stage:"deactivate",id:i.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:i.data.feedItem.id})),hasNotification:!0,type:i.data.feedItem.type})})),this.feedSubscription.connect(),this.cancels.add(this.interactiveAllowed.listen(()=>{window.requestAnimationFrame(()=>{this.activeQuestionId.invalidate()})})),e.sdk.onMount({name:"gamification-background"},()=>()=>{this.activeQuestionId.off();for(const r of this.cancels)r(),this.cancels.delete(r)}),n||(this.advertisement=ro(this.slStreamId,this.feedSubscription,e))}getCurrentSessionId=e=>{const n=e.eventId||this.slStreamId.get()||"",r=e.userId||this.userId.get()||"",i=e.organizationId||this.organizationId.get()||"",o=e.entity||"",s=e.prefix||"";return[i,n,r,s,o].join(":")};disconnect=()=>{this.feedSubscription?.disconnect(),this.questionSubscription!==void 0&&(this.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0)};openQuestion=(e,n)=>{this.openedQuestionId.set({questionId:e,question:n}),this.notifications.markAsViewed(this.getCurrentSessionId({prefix:"notification",entity:e}))};closeQuestion=e=>{this.openedQuestionId.set(void 0),e&&this.notifications.markAsViewed(this.getCurrentSessionId({prefix:"notification",entity:e}))}}class ao{notificationsList;store;timeouts;waitingQueue;activeQueue;options;logger;constructor(e){this.options=e,this.logger=ce("notifications"),this.store=new Map,this.timeouts=new Map,this.waitingQueue=new Set,this.activeQueue=new Set,this.notificationsList=Q(new Map)}addToQueue=e=>{if(this.store.has(e.id)){this.logger.debug({notification:e},"skip existed notification: %o");return}const n=e.close,r=e.action;if(this.store.set(e.id,{...e,close:(...i)=>{n&&n(...i),this.closeNotification(e.id)},action:(...i)=>{r&&r(...i),this.closeNotification(e.id,{animateHiding:!1})}}),this.waitingQueue.add(e.id),this.activeQueue.size===this.options.concurrency){const[i]=this.activeQueue;if(this.store.get(i)?.persistent!==!0)this.closeNotification(i);else{const[s]=this.waitingQueue;this.waitingQueue.size>1&&this.closeNotification(s),this.tickWaitingQueue()}}else this.tickWaitingQueue()};tickWaitingQueue=()=>{if(this.activeQueue.size<this.options.concurrency){const[e]=this.waitingQueue;if(!e)return;this.activeQueue.add(e),this.waitingQueue.delete(e),this.logger.debug({job:e},"waiting queue tick"),this.tickActiveQueue(e)}else this.logger.debug({queueSize:this.activeQueue.size,concurrency:this.options.concurrency},"waiting queue tick skipped")};tickActiveQueue=e=>{if(!e)return;const n=this.store.get(e);if(!n){this.logger.debug({notificationId:e},"active queue tick skipped, notification not exist");return}q.emit("notification",{action:"received",payload:{type:n.type,questionId:n.data.questionId,questionType:n.data.questionType}});const r=setTimeout(()=>{const i=e,o=new Map(this.notificationsList.get());o.set(n.id,n),this.notificationsList.set(o);const s=setTimeout(()=>{this.logger.debug({notificationId:i,delay:n.autoHideDuration||5e3},"notification hiding by autoHideDuration"),this.closeNotification(i)},n.autoHideDuration||5e3);this.timeouts.set(i,s),this.logger.debug({notificationId:i,queue:[...o.values()]},"notification displayed")},n.delay||0);this.timeouts.set(e,r),this.logger.debug({notificationId:e},"active queue tick completed"),this.tickWaitingQueue()};closeNotification=(e,{animateHiding:n=!0}={})=>{const r=new Map(this.notificationsList.get()),i=r.get(e);if(i){i.hiding=!(this.waitingQueue.size>=this.options.concurrency)&&n,this.notificationsList.set(r);const o=setTimeout(()=>{const s=new Map(this.notificationsList.get());s.delete(e),this.notificationsList.set(s);const a=this.timeouts.get(e);a!==void 0&&(clearTimeout(a),this.timeouts.delete(e)),this.logger.debug({notificationId:e},"notification hidden"),i.hiding&&q.emit("notification",{action:"closed",payload:{type:i.type,questionId:i.data.questionId,questionType:i.data.questionType}})},this.options.animationDelay||0);this.timeouts.set(e,o)}return this.store.delete(e),this.activeQueue.delete(e),this.waitingQueue.delete(e),this.tickWaitingQueue(),this.logger.debug({notificationId:e},"notification hiding"),i};drain=()=>{this.store.clear(),this.timeouts.clear(),this.waitingQueue.clear(),this.activeQueue.clear(),this.notificationsList.off(),this.notificationsList.set(new Map)}}var bt;(function(t){t.OPENED="opened"})(bt||(bt={}));class uo extends Ke{constructor(){super("notification")}setOpened=e=>{this.write(bt.OPENED,e,"true")};isOpened=e=>this.read(bt.OPENED,e);clearNotification=()=>{this.clear()}}class co{queue;storage;constructor(e={}){this.storage=new uo,this.queue=new ao({concurrency:1,animationDelay:1600,...e})}isViewed=e=>this.storage.isOpened(e);add=e=>{if(!this.isViewed(e.id)){if(e.data&&e.emitEvent){const r=e.action;e.action=(...i)=>{r&&r(...i),q.emit("notification",{action:"opened",payload:{questionId:e.data.questionId,questionType:e.data.questionType}})}}this.queue.addToQueue(e)}};close=(e,{markAsViewed:n=!0,animateHiding:r}={})=>{this.queue.closeNotification(e,{animateHiding:r}),n&&this.markAsViewed(e)};getActiveNotification=()=>{const e=this.queue.notificationsList.get();if(!e?.size)return null;for(const r of e.values())if(r.type===me.ONBOARDING)return r;return e.values().next().value};getQueueStore=()=>this.queue.notificationsList;markAsViewed=e=>{this.storage.setOpened(e)}}const lo=(t,e,n)=>{t.notifications=new co(void 0),t.addNotification=t.notifications.add,t.sdk.getNotificationsStore=()=>t.notifications.getQueueStore(),t.sdk.getActiveNotification=()=>t.notifications.getActiveNotification(),t.sdk.onMount({name:"notifications"},()=>()=>{t.notifications.queue.drain()}),n()};var je;(function(t){t.UNKNOWN="unknown",t.ALREADY_VOTED="already_voted"})(je||(je={}));const Bn=async(t,e)=>{const{client:n,createRequestOptions:r}=t.createPromiseClient(W.Feed,{method:"submitAnswer"}),i=r({retryAttempts:0});try{return await n.submitAnswer({data:e},{contextValues:i})}catch(o){throw M.ConnectError.from(o)?.code===M.Code.AlreadyExists?new Error(je.ALREADY_VOTED):new Error(je.UNKNOWN)}},Or=(t,e)=>{const{client:n,createRequestOptions:r}=t.createPromiseClient(W.Feed,{method:"submitInplay"}),i=r({retryAttempts:0});return n.submitInplay({data:{eventId:+e}},{contextValues:i})},fo={pageSize:10},po=(t,e,n,r,i)=>{let o=0;const s=Q({pageSize:fo.pageSize,page:0}),a=H({data:[],key:Date.now(),hasMore:!0,loading:void 0,error:void 0}),u=ji(t),d=async()=>{const p=e.get(),w=r?.getStore().get().data?.map(E=>E.slId)||[];if(p&&w?.length){const E=n.get();E&&w.push(E),a.setKey("loading",!0),a.setKey("data",[]);const m=await u({eventId:p,usersIds:w});a.set({data:m.data.map((T,D)=>({...T.attributes,friendsRank:D+1})),hasMore:!1,key:Date.now(),loading:!1}),m.meta&&(o=Math.round(m.meta.count/m.meta.pageSize))}},c=()=>{d()},f=p=>{const w=s.get(),E=p||w.page+1;E<=o&&s.set({...w,page:E})};return ne.onMount(a,()=>{const p=e.listen(d),w=r?.listen(d);return()=>{p(),w?.()}}),{$store:a,fetchMore:f,invalidate:c}};class ho extends Ke{get=this.read;set=this.write;del=this.remove;constructor(){super("deep-link-context",window.sessionStorage)}}const Mn="sldl",kt="sldl_uid",kr="sldl_eid",_r="sldl_e_eid",yo=new Set([kt,kr,_r]),qn=t=>{const e={},n={};for(const[r,i]of t)yo.has(r)?e[r]=i:n[r]=i;return{result:e,remain:n}},go=({hash:t,search:e})=>{if(t&&t.includes(Mn)){const n=new URLSearchParams(t.substr(1));return{hash:qn(n)}}if(e&&e.includes(Mn)){const n=new URLSearchParams(e);return{search:qn(n)}}return null},Un=ce("deep_link"),ue={debug:(...t)=>{Un.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Un.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},mo=(t,e)=>{const{hash:n,search:r}=window.location;if(ue.debug({hash:n,search:r},"get deep link data from"),n||r){const i=go({hash:n,search:r});if(ue.debug(i,"parse deep link result"),i){const{hash:o,search:s}=i,{result:a,remain:u}=o||s;if(Object.keys(a).length!==0){t.setValue("data",a);const d=Object.keys(u).length!==0;if(o){let c="";d&&(c=`#${new URLSearchParams(u).toString()}`,ue.debug({updatedHash:c},"update hash")),window.history.replaceState(null,"",window.location.pathname+window.location.search+c)}if(s){let c="";d&&(c=`?${new URLSearchParams(u).toString()}`,ue.debug({updatedSearch:c},"update search")),window.history.replaceState(null,"",window.location.pathname+c+window.location.hash)}e(a)}}}t.setValue("parsed",!0)},bo=(t,e,n)=>{const r=new ho,i=r.get("sl-deep-link-store");let o={};if(i)try{o=JSON.parse(i)}catch(a){ue.debug(a)}t.deepLink={$store:new Ie(H(o),"deep-link-context"),getDeepLinkData:()=>{const{data:a,used:u}=t.deepLink.$store.getValues();return{data:a,used:u}},deepLinkUsed:a=>{ue.debug(`logged in with inviterId: ${a}`),t.deepLink.$store.setValue("used",!0)},onDeepLinkHandlers:new Set},t.sdk.getInviter=()=>{const{data:a,used:u}=t.deepLink.getDeepLinkData();return u?a?.[kt]:void 0},t.sdk.inviteDisplayed=()=>{t.deepLink.$store.getStore().set({}),t.deepLink.$store.getStore().off(),r.del("sl-deep-link-store")},t.deepLink.$store.subscribe(a=>r.set("sl-deep-link-store",JSON.stringify(a))),t.sdk.addDeepLinkHandler=a=>{localStorage.getItem("SL_DEBUG")&&ue.trace("adding deep link handler"),t.deepLink.onDeepLinkHandlers.add(a)},e.onDeepLinkHandled&&t.sdk.addDeepLinkHandler(e.onDeepLinkHandled),t.sdk.removeDeepLinkHandler=a=>{ue.trace("removing deep link handler"),t.deepLink.onDeepLinkHandlers.delete(a)};const s=a=>{t.deepLink.$store.setValue("handled",!0),ue.trace({size:t.deepLink.onDeepLinkHandlers.size},"deep link handled, call callbacks");for(const u of t.deepLink.onDeepLinkHandlers)try{ue.trace("called handler"),u(a)}catch(d){console.error(d)}};mo(t.deepLink.$store,s),n()},vo=ce("bypass");class So extends vi{$coreStore;deepLink;transport;bypassLogin;constructor(e,n,r){super(),this.$coreStore=e,this.deepLink=r,this.transport=n,this.bypassLogin=Fi(this.transport),this.connect()}me=async()=>(this.$coreStore.getValues().user.invalidate(),(await this.$coreStore.getValues().user.getValue())?.data);login=async(e,n)=>{this.$coreStore.getValues().userKey.setValue(n);const{used:r,data:i}=this.deepLink.getDeepLinkData(),o=r?"":i?.[kt];vo.debug({inviterKey:o},"login with inviterKey");const s=await this.bypassLogin({schema:e,userKey:n,inviterKey:o,init:!1}),a=s.meta?.jwt,u=s.data?.id;if(!a||!u)throw new Error("internal: token missing");return s.meta?.inviterKey&&this.deepLink.deepLinkUsed(s.meta.inviterKey),this.$coreStore.getValues().user.getStore().mutate({data:s.data}),this.saveUser(a,u),a};isAuthenticated=()=>this.me();logout=()=>{this.$coreStore.getValues().user.setValue(),this.$coreStore.getValues().userKey.setValue(),this.$coreStore.getValues().userToken.setValue(),this.transport.setAuth("",""),new $e().clear()};softLogout=()=>{const e=new $e;this.transport.setAuth("",""),e.setToken(""),this.reLogin()};reLogin=({skipLogin:e}={skipLogin:!1})=>{const n=new $e,r=n.getToken(),i=n.getExternalToken();if(this.$coreStore.getValues().userKey.setValue(i),r)return this.saveUser(r,""),this.me().then(o=>{if(o?.id){const s=o.id;this.saveUser(r,s)}return o});if(i&&!r&&!e){const o=n.getSchema();o&&i&&this.login(o,i).catch(()=>{this.logout()})}};saveUser=(e,n)=>{this.transport.setAuth(e,n),this.$coreStore.getValues().userToken.setValue(e),new $e().setToken(e)};connect=()=>{this.transport.registerInterceptor(e=>async n=>{try{return await e(n)}catch(r){throw r.code&&(r.code===7||r.code===16)&&this.transport.getHeader("authorization")&&this.softLogout(),r}})}}const We=new $e,wo=(t,e,n)=>{t.auth=new So(t.store,t.transport,t.deepLink),t.stores.status.listen(r=>{r===he.READY&&t.auth.reLogin()}),t.sdk.userId=t.stores.user.getAtomStore,t.sdk.authorizationBypass=async(r,i)=>{if(!(We.getSchema()===r&&We.getExternalToken()===i&&t.transport.getHeader("authorization")))try{await t.auth.login(r,i),We.setSchema(r),We.setExternalToken(i)}catch{t.sdk.logout()}},t.sdk.logout=()=>{t.auth.logout(),We.clear()},t.sdk.getUserStore=()=>t.stores.user.getStore(),t.sdk.isUserAuthorized=()=>t.auth.isAuthenticated(),n()},Qn=ce("video_player"),ut={debug:(...t)=>{Qn.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Qn.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},To=(t,e,n)=>{t.videoPlayer={controllers:new Set},t.sdk.addVideoPlayerController=r=>{ut.trace("adding video player controller"),t.videoPlayer.controllers.add(r)},e.videoPlayerController&&t.sdk.addVideoPlayerController(e.videoPlayerController),t.sdk.removeVideoPlayerController=r=>{ut.trace("removing video player controller"),t.videoPlayer.controllers.delete(r)},t.sdk.controlVideoPlayer=r=>{ut.trace("controlling video player");for(const i of t.videoPlayer.controllers){ut.trace("calling video player controller");try{i(r)}catch(o){console.error(o)}}},n()},Eo={[S.QuestionType.FACTOID]:"insight",[S.QuestionType.POLL]:"poll",[S.QuestionType.TRIVIA]:"trivia",[S.QuestionType.PREDICTION]:"prediction",[S.QuestionType.TWEET]:"tweet"},Ao=(t,e,n)=>{t.sdk.uiState=H({}),t.ui={enableAppNotification:function(){t.sdk.uiState.setKey("appNotification",!0)},disableAppNotification:function(){t.sdk.uiState.get().app||t.sdk.uiState.setKey("appNotification",!1)},enableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!0)},disableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!1)},enableApp:function(){t.sdk.uiState.set({app:!0,appNotification:!0})},disableApp:function(){t.sdk.uiState.set({...t.sdk.uiState.get(),onboardingNotification:!1,appNotification:!1,app:!1})}},e.onContentActivate&&(t.ui.onContentActivate=e.onContentActivate);const r=i=>{t.ui.onContentActivate&&t.ui.onContentActivate({...i,type:"advertisement"})};t.onQuestionActivate=({questionType:i,...o})=>{if(t.ui.onContentActivate){const s=o.type||i&&Eo[i]||"question";t.ui.enableAppNotification(),t.ui.onContentActivate({...o,type:s})}},t.sdk.onMount({name:"ui"},()=>{const i=a=>{if(a.slEventBus?.type==="app")switch(a.slEventBus.action){case"open":t.ui.enableApp();break;case"close":t.ui.disableApp();break}if(a.slEventBus?.type==="notification"){const u=a.slEventBus.action;if(a.slEventBus.payload.type===me.ONBOARDING)switch(u){case"received":t.ui.enableOnboardingNotification();break;case"closed":t.ui.disableOnboardingNotification();break}else switch(u){case"received":t.ui.enableAppNotification();break;case"closed":t.ui.disableAppNotification();break}}if(a.slEventBus?.type==="advertisement"&&e.withAd){const u=a.slEventBus,{hasNotification:d,hasBanner:c,id:f,isViewed:p,type:w}=u.payload;switch(u.action){case"notification-opened":t.sdk.uiState.set({promotionExternalAd:w===S.PromotionType.EXTERNAL_AD,promotionBanner:c,promotionNotification:!1,promotionOverlay:!0,promotionSidebar:!0});break;case"received":if(t.sdk.closeFeature(),r({stage:"activate",id:f,hasNotification:d,hasBanner:c,isViewed:p}),!e.withAdNotification){t.sdk.uiState.set({promotionBanner:c,onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionOverlay:!0,promotionSidebar:!0,promotionExternalAd:w===S.PromotionType.EXTERNAL_AD});break}d?t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionNotification:!0}):t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionBanner:c,promotionOverlay:!0,promotionSidebar:!0,promotionExternalAd:w===S.PromotionType.EXTERNAL_AD});break;case"closed":t.sdk.uiState.set({...t.sdk.uiState.get(),promotionNotification:!1,promotionBanner:!1,promotionOverlay:!1,promotionExternalAd:!1,promotionSidebar:!1}),r({stage:"deactivate",id:f,hasNotification:d,hasBanner:c,isViewed:p});break}}},o=q.listen(i),s=t.activeFeature.subscribe(a=>{a?(t.ui.enableApp(),t.sdk.uiState.set({app:!0})):t.ui.disableApp()});return()=>{o(),s()}}),n()},Io=(t,e,n)=>{const r={onMountedFired:!1},i=new Map,o=new Map;t.sdk=Object.create(null),t.sdk.options=H(e),t.sdk.withAuth=!1,t.sdk.onMount=({name:s,clear:a},u)=>{if(i.has(s)){const d=o.get(s);d&&d(),i.delete(s),o.delete(s)}i.set(s,{cb:u,clear:a}),t?.stores?.enabled?.get()==="on"&&o.set(s,u())},t.ready=()=>{t.stores.enabled.subscribe(s=>{s==="on"&&r.onMountedFired===!1&&(i.forEach(({cb:a},u)=>o.set(u,a())),r.onMountedFired=!0),s!=="on"&&r.onMountedFired===!0&&(o.forEach(a=>a()),o.clear(),i.forEach(({clear:a},u)=>a&&i.delete(u)),r.onMountedFired=!1)})},t.sdk.initializeApp=async s=>{if(t.contextConfig=s,t.stores.enabled.get()==="on")return{enabled:!0};t.storeSubscribe(),t.stores.enabled.setValue("on"),t.stores.status.setValue(he.INITIALIZATION);try{const a=await t.stores.organizationSettings.getValue();return a?(t.stores.status.setValue(he.READY),{enabled:!!a}):(t.stores.status.setValue(he.FAILED),{err:"failed"})}catch(a){return t.stores.enabled.setValue(),t.stores.status.setValue(he.FAILED),{err:`${a}`}}},t.sdk.disableApp=()=>{t.stores.enabled.get()==="on"&&(t.stores.enabled.setValue(),t.stores.status.setValue(he.DISABLED),t.stores.slStreamId.setValue(),t.stores.providerStreamId.setValue(),t.sdk.closeFeature(!0),t.storeUnsubscribe(),t.transport.disconnect())},t.sdk.createEventSession=(s,a)=>{a?t.stores.slStreamId.getStore().set({loading:!1,data:s}):t.stores.providerStreamId.setValue(s)},n()},Oo=(t,e)=>{const{client:n,queryKey:r}=t.createPromiseClient(Ze.Client,{method:"generateDeepLink",params:e});return t.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s,a)=>{if(!s)return{};try{return(await n.generateDeepLink({data:{gamification:!0,externalEventId:a,eventId:s}})).data?.attributes}catch{return}},dedupeTime:1e3*60*60*24,refetchInterval:0})},ko=(t,{web:e,mobile:n})=>{const{client:r}=t.createPromiseClient(di.LinksClient,{method:"generate"});return r.generate({web:e,mobile:n})},jn=(t,e)=>{const n=new URLSearchParams(t);for(const[r,i]of Object.entries(e))n.append(r,i);return n.toString()},_o=(t,e,n,r)=>{const i=H({});return ne.onMount(i,()=>Oo(t,[e,n]).subscribe(async({data:a,loading:u})=>{const d=a===void 0&&u===!1?"https://streamlayer.io":a?.url,c=r.get()||"",f=e.get()||"",p=n.get()||"",w={[kt]:c,[kr]:f,[_r]:p};if(!u&&d){i.setKey("loading",!0);let E=window.location.search,g=window.location.hash;E&&g||g?E=`?${jn(E,w)}`:g=`#${jn("",w)}`;const m=window.location.origin+window.location.pathname+E+g;try{const T=await ko(t,{web:m,mobile:d});i.set({data:T.data?.link,loading:!1})}catch{i.set({loading:!1,error:"Failed to generate short link",data:void 0})}}else i.setKey("loading",!0)})),{$store:i,fetch}};var B;(function(t){t.Unset="unset",t.Required="required",t.Optional="optional",t.Completed="completed",t.Disabled="disabled",t.Unavailable="unavailable"})(B||(B={}));const Co=(t,e,n,r)=>{const{inplayGame:i}=t.featureSettings.get(),o=e.getCurrentSessionId({prefix:"onboarding"});i&&n.add({type:me.ONBOARDING,id:o,action:t.openFeature,close:()=>{t.onboardingProcessed.set(!0)},persistent:!0,autoHideDuration:1e6,data:{questionId:"onboarding",questionType:S.QuestionType.UNSET,onboarding:{...i,instantOpen:!r.getOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""})}}})},ct=(t,e,n,r,i,o,s,a)=>{try{const u=e.userId.get(),d=e.organizationId.get(),c=e.slStreamId.get();if(!u||!d||!c)return;const f=i.getOnboardingStatus({userId:u,organizationId:d,eventId:c});if(f===B.Completed||a?.skipOnboarding){t.set(B.Completed);for(const m of o)m();a?.skipOnboarding&&f!==B.Completed&&(i.saveOnboardingStatus({organizationId:d,userId:u,eventId:c},B.Completed),Or(s,c));return}const p=e.moderation.getStore().value?.data,w=n.featureSettings.get().inplayGame;if(p===void 0||w===void 0)return;const E=p?.options?.onboardingEnabled,g=w?.titleCard?.optIn;E?g?t.set(B.Required):t.set(B.Optional):(g?t.set(B.Unavailable):t.set(B.Disabled),r.close(e.getCurrentSessionId({prefix:"onboarding"}),{markAsViewed:!1}))}catch(u){console.error(u)}},xn=(t,e,n,r,i)=>{let o=!!i?.skipOnboarding;const s=e.storage,a=Q(B.Unset);a.subscribe(c=>{c!==B.Unset&&(c===B.Optional||c===B.Required?o===!1&&(Co(t,e,r,s),o=!0):t.onboardingProcessed.set(!0),c===B.Completed&&e.activeQuestionId.invalidate(),s.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}))});const u=[];return a.get()!==B.Completed&&(u.push(e.userId.listen(c=>{c&&ct(a,e,t,r,s,u,n,i)})),u.push(e.moderation.listen(c=>{c.data&&ct(a,e,t,r,s,u,n,i)})),u.push(t.featureSettings.listen(c=>{c&&ct(a,e,t,r,s,u,n,i)}))),ct(a,e,t,r,s,u,n,i),{$store:a,submitInplay:async()=>{const c=e.slStreamId.get();if(c){await Or(n,c),a.set(B.Completed),s.saveOnboardingStatus({organizationId:e.organizationId.get()||"",userId:e.userId.get()||"",eventId:c},B.Completed),q.emit("poll",{action:"onboardingPassed",payload:{}}),t.openFeature();const f=e.getCurrentSessionId({prefix:"onboarding"});r.close(f)}}}},Po=(t,e,n,r)=>{const i=H(void 0),o=Ar(r),s=async()=>{const u=t.get(),d=e.get(),c=n?n.getStore().get().data?.map(w=>w.slId):[];if(!c||!u||!d)return;const f={eventId:u,userId:d,usersIds:[...c,d]},p=await o(f);i.set(p.data?.attributes)},a=()=>{s()};return ne.onMount(i,()=>{a();const u=t.listen(s),d=n?.listen(s),c=e.listen(s);return()=>{u(),d?.(),c()}}),{$store:i,invalidate:a}},Lo=async(t,e,n,r,i)=>{const o=Ar(i),s=t.get(),a=e.get(),u=n?.getStore().get().data?.map(p=>p.slId)||[],d={eventId:s,userId:r,usersIds:[...u,a]};return(await o(d)).data?.attributes?.summary},Gn=new Set([S.QuestionType.POLL,S.QuestionType.PREDICTION,S.QuestionType.TRIVIA]);class No extends Tr{userSummary;feedList;betPack;friends;leaderboardId;leaderboardList;deepLink;onboardingStatus;openedQuestion;currentUserId;openedUser;closeFeature;openFeature;feedSubscription;activeQuestionId;openedQuestionId;advertisement;onboardingProcessed;friendsTabEnabled;skipOnboarding;notifications;transport;background;storage;submitAnswerTimeout;cancels=new Set;onQuestionActivate;constructor(e,n,r){if(super(e,n),this.background=new so(r),this.advertisement=this.background.advertisement,this.onQuestionActivate=r.onQuestionActivate,this.feedSubscription=this.background.feedSubscription,this.activeQuestionId=this.background.activeQuestionId,this.openedQuestionId=this.background.openedQuestionId,this.storage=this.background.storage,this.feedList=this.background.feedList,this.betPack=this.background.betPack,this.currentUserId=this.background.userId,this.onboardingProcessed=Q(!r.sdk.withAuth),this.leaderboardId=new J(Q(this.settings.getValue("pinnedLeaderboardId")),"pinnedLeaderboardId").getStore(),this.notifications=r.notifications,this.transport=r.transport,this.closeFeature=(i=!0)=>r.sdk.closeFeature(i),this.openFeature=()=>r.sdk.openFeature(V.SdkOverlayType.GAMES),this.openedQuestion=this.background.openedQuestion,this.deepLink=_o(this.transport,this.background.slStreamId,r.stores.providerStreamId.getStore(),this.background.userId),this.userSummary=Po(this.background.slStreamId,this.background.userId,this.friends,this.transport),!r.sdk.options.get().hideFriends){this.friends=new te(xi(this.background.userId,r.transport),"gamification:friends"),this.openedUser=Q(void 0);const i=this.leaderboardList=po(this.transport,this.background.slStreamId,this.background.userId,this.friends);this.cancels.add(this.userSummary.$store.listen((o,s)=>{s?.summary&&o?.summary&&i.invalidate()}))}this.connect(),this.skipOnboarding=!!r.sdk.options.get().skipOnboarding,this.onboardingStatus=xn(this,this.background,r.transport,r.notifications,{skipOnboarding:r.sdk.options.get().skipOnboarding}),r.sdk.options.get().skipOnboarding||(this.onboardingStatus=xn(this,this.background,r.transport,r.notifications,{skipOnboarding:r.sdk.options.get().skipOnboarding})),this.cancels.add(this.onboardingStatus.$store.listen(this.checkInteractiveFlag)),this.cancels.add(this.background.moderation.getStore().listen(this.checkInteractiveFlag)),this.cancels.add(this.settings.subscribe(this.checkInteractiveFlag)),this.cancels.add(this.onboardingStatus.$store.listen((i,o)=>{(o===void 0||i!==B.Unset)&&this.background.activeQuestionId.invalidate()})),this.background.activeQuestionId.listen(this.showInApp),this.friendsTabEnabled=Q(!1),this.cancels.add(r.sdk.options.subscribe(i=>{i.friendsTab==="disabled"?this.friendsTabEnabled.set(!1):i.friendsTab==="enabled"&&this.friendsTabEnabled.set(!0)})),this.cancels.add(this.settings.subscribe(i=>{r.sdk.options.get().friendsTab==="activatedGame"&&this.friendsTabEnabled.set(!!i.inplayGame?.titleCard?.optIn)})),r.sdk.onMount({name:"gamification",clear:!0},()=>()=>{for(const i of this.cancels)i(),this.cancels.delete(i)})}get isInteractiveAllowed(){return this.background.interactiveAllowed.get()===Se.ALLOWED}checkInteractiveFlag=()=>{if(this.skipOnboarding)this.background.interactiveAllowed.set(Se.ALLOWED);else{const e=this.onboardingStatus.$store.get(),n=this.background.moderation.getStore().value?.data?.options?.onboardingEnabled,r=this.settings.getValues().inplayGame?.titleCard?.optIn,i=e===B.Completed,o=!n||i||r!==!0;this.background.interactiveAllowed.set(o?Se.ALLOWED:Se.DISALLOWED)}};connect=()=>{this.onboardingProcessed.subscribe(e=>{e&&this.advertisement&&this.advertisement.connect()}),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-prediction-close",async e=>{if(!this.isInteractiveAllowed)return;const n=e.data?.attributes?.question,r=e.data?.attributes?.feedItem;if(!n||!r?.attributes)return;const{status:i,type:o,id:s,answers:a}=n;if(i===S.QuestionStatus.RESOLVED&&o===S.QuestionType.PREDICTION){const u=this.background.getCurrentSessionId({prefix:`notification-id:${s}`}),d=[...this.feedList.getValues().data||[]],c=d.findIndex(K=>K.id===s),f=d[c];let p=f?.attributes?.attributes?.value?.answerId;const w=qe(s,this.transport),E=w.subscribe(()=>{});await w.get().promise;let g=w.get().data;g||(g=await rn(s,this.transport)),E(),window.requestAnimationFrame(()=>{w.invalidate()}),p||(p=g?.answers.find(({youVoted:K})=>K)?.id);const m=a.find(({correct:K})=>K),T=p?a.find(({id:K})=>K===p):void 0,D=!!T?.correct;if(f&&d[c]?.attributes?.attributes.case==="question"){try{d[c].attributes.attributes.value.answerId=p,d[c].attributes.attributes.value.openForVoting=!1,p&&(d[c].attributes.attributes.value.status=D?ot.PickHistoryStatus.WON:ot.PickHistoryStatus.LOST)}catch{}this.feedList.getStore().mutate(d)}if(!T||!m)return;this.openedQuestionId.get()?.questionId!==n.id&&this.notifications.add({type:me.QUESTION_RESOLVED,action:()=>this.openQuestion(n.id,r),close:()=>this.closeQuestion(s),autoHideDuration:D?15e3:12e3,id:u,emitEvent:!1,data:{questionId:s,questionType:S.QuestionType.PREDICTION,question:{title:D?`Congratulations! You answered correctly! You won ${m.points} pts!`:`Better luck next time! Correct: ${m?.text}!`,votedAnswer:{title:T?.text,points:T?.points},correctAnswerTitle:m?.text,correct:!!D,predictionResult:i===S.QuestionStatus.RESOLVED,questionTitle:n?.subject}}}),this.userSummary.invalidate()}})),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-questions-list",e=>{const n=[...this.feedList.getStore().value?.data||[]],r=e.data?.attributes?.feedItem,i=n.findIndex(o=>o.id===r?.id);if(r?.attributes&&r.attributes.attributes.case!=="promotion"&&!(r.attributes.status!==S.QuestionStatus.ACTIVE&&r.attributes.status!==S.QuestionStatus.RESOLVED)&&!(!this.isInteractiveAllowed&&Gn.has(r.attributes.type))){if(i!==-1)if(r.attributes.attributes.case==="question"&&n[i].attributes?.attributes.case==="question"){const o=n[i];o.attributes&&(n[i]={...n[i],attributes:{...o.attributes,attributes:{...o.attributes.attributes,value:{...o.attributes.attributes.value,...r.attributes.attributes.value,answerId:o.attributes.attributes.value.answerId,status:o.attributes.attributes.value.status,openForVoting:o.attributes.attributes.value.openForVoting}}}})}else{const o=n[i];o.attributes&&r.attributes&&(n[i]={...n[i],attributes:{...o.attributes,attributes:{...o.attributes.attributes,value:{...o.attributes.attributes.value,...r.attributes.attributes.value}}}})}i===-1&&(n.unshift(r),q.emit("poll",{action:"received",payload:{questionId:r.id,questionType:r.attributes?.type}})),this.feedList.getStore().mutate(n)}}))};disconnect=()=>{this.background.feedSubscription.removeListener("feed-subscription-prediction-close"),this.background.feedSubscription.removeListener("feed-subscription-questions-list")};betPackVote=async(e,n)=>{try{await Bn(this.transport,{questionId:e,answerId:n})}catch(o){if(o.message===je.ALREADY_VOTED){const s=qe(e,this.transport),a=s.subscribe(()=>{});s.invalidate(),a()}throw o}const r={...this.betPack.getValues().data?.data},i=r?.[e];i&&(q.emit("poll",{action:"voted",payload:{questionId:e,questionType:i.type}}),i.answers=i.answers.map(o=>o.id===n?{...o,youVoted:!0}:o),this.betPack.getStore().mutate({data:r,timestamp:Date.now()}))};submitAnswer=async(e,n)=>{const r=qe(e,this.transport),i=r.subscribe(()=>{}),o={...r.get().data||{}},s=()=>{const a=this.feedList.getValues().data;if(!a)return;const u=a.findIndex(f=>f.id===e),d=a[u],c=d?.attributes?.attributes.case==="question"&&d.attributes.attributes.value;if(c){q.emit("poll",{action:"voted",payload:{questionId:e,questionType:c.questionType}});const f=r.get().data;if(i(),f){const p=f.answers.find(m=>m.correct===!0),w=f.answers.findIndex(m=>m.id===n),E=f.answers[w],g=f.answers.every(({percentageDecimal:m},T)=>m===o?.answers[T].percentageDecimal);a[u].attributes.attributes.value.answerId=n,a[u].attributes.attributes.value.openForVoting=!1,a[u].attributes.attributes.value.text=E?.text||"",p&&(a[u].attributes.attributes.value.status=p.id===n?ot.PickHistoryStatus.WON:ot.PickHistoryStatus.LOST),this.feedList.getStore().mutate([...a]),f.answers[w].correct=p?.id===n,f.answers[w].youVoted=!0,g&&f.answers.forEach(m=>{m.percentageDecimal=0}),p?.id===n&&(f.answers[w].pointsEarned=f.status===S.QuestionStatus.RESOLVED?0:p.points),r.mutate({...f})}this.submitAnswerTimeout&&clearTimeout(this.submitAnswerTimeout),this.submitAnswerTimeout=setTimeout(()=>{this.userSummary.invalidate()},1e3)}};try{await Bn(this.transport,{questionId:e,answerId:n}),s()}catch(a){if(a.message===je.ALREADY_VOTED){this.userSummary.invalidate();const u=r.subscribe(()=>{});r.invalidate(),u()}throw a}};openQuestion=(e,n)=>{if(!e)return()=>{};const r=n?.openedFrom==="bet-pack";this.notifications.close(this.background.getCurrentSessionId({prefix:"notification",entity:e}),{animateHiding:!1});let i=n?.attributes?.type;!i&&!r&&(i=(this.feedList.getStore().value?.data||[]).find(a=>a.id===e)?.attributes?.type);const o={eventId:this.background.slStreamId.get()||"",userId:this.background.userId.get()||"",organizationId:this.background.organizationId.get()||""};return this.storage.isQuestionOpened(o,e)||(q.emit("poll",{action:"opened",payload:{questionId:e,questionType:i,questionOpenedFrom:n?.openedFrom==="bet-pack"?"list":n?.openedFrom}}),this.storage.saveQuestionOpened(o,e)),r||this.openFeature(),this.background.openQuestion(e,n?{...n,openedFrom:n?.openedFrom==="bet-pack"?"list":n?.openedFrom}:void 0)};getFeedItem=e=>zi(e,this.transport);isOpenedQuestion=e=>!!this.notifications.isViewed(e);closeQuestion=e=>(e&&this.onQuestionActivate({stage:"deactivate",id:e,isViewed:!!this.notifications.isViewed(this.background.getCurrentSessionId({prefix:"notification",entity:e}))}),this.background.closeQuestion(e));openUser=async e=>{if(!this.leaderboardList)return;const n=this.leaderboardList?.$store.get().data?.find(i=>i.userId===e);if(!n){this.openedUser?.set(n);return}if(n.summaryLoaded){this.openedUser?.set(n);return}const r={...n};try{const i=await Lo(this.background.slStreamId,this.background.userId,this.friends,e,this.transport);i?.inTop!==void 0&&(this.leaderboardList?.$store.setKey("data",this.leaderboardList.$store.get().data?.map(o=>(o.userId===e&&(o.inTop=i.inTop),o))),r.inTop=i.inTop)}catch(i){console.error(i)}this.openedUser.set(r)};closeUser=()=>{this.openedUser?.set(void 0)};showInApp=e=>{const n=this.onboardingStatus.$store.get();if(e&&e.data&&n&&n!==B.Unset&&e.data.question?.id!==void 0&&e.data.question?.bypassNotifications?.inAppSilence!==S.SilenceSetting.ON&&e.data.question.status===S.QuestionStatus.ACTIVE&&!e.data.question.marketClosed){if(Gn.has(e.data.question.type))this.isInteractiveAllowed&&e.data.question.notification!==void 0&&this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e.data?.question?.id,e.data?.feedItem),close:()=>this.closeQuestion(e.data?.question?.id),autoHideDuration:1e3*60,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),emitEvent:!0,data:{questionId:e.data.question.id,questionType:e.data.question.type,question:{title:e.data.question.notification.title},inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}});else if(e.data.question.type===S.QuestionType.FACTOID){const r=e.data.question.options?.options.value,i=e.data.question.notification?.title||e.data.question.subject||"",o=e.data.question.notification?.body||r.body,s={heading:i,body:o,imageMode:r?.imageMode,image:r?.image,video:{id:r?.video?.id||"",url:r?.video?.url||"",thumbnailUrl:r?.video?.thumbnailUrl||""},webLink:{label:"",url:""}};this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e?.data?.question?.id,e?.data?.feedItem),close:()=>this.closeQuestion(e?.data?.question?.id),autoHideDuration:1e3*120,emitEvent:!0,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),data:{questionId:e.data.question.id,questionType:e.data.question.type,insight:s,inApp:{useMediaFromContent:r?.useAsNotification===S.UseAsNotification.ENABLED,notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}})}else if(e.data.question.type===S.QuestionType.TWEET&&e.data.question.notification!==void 0){const r=e.data.question.options?.options.value,i={image:"",video:""};if(r.tweetMeta?.tweet?.meta?.extendedEntities?.media?.[0]){const s=r.tweetMeta.tweet.meta.extendedEntities.media;if(s){const a=s.find(({type:u})=>u==="photo")||s[0];i.image=a.mediaUrlHttps,a.type==="video"&&(i.video=a.url)}}const o={title:e.data.question.notification?.title,body:e.data.question.notification?.body,image:e.data.question.notification?.image,account:r?.tweetMeta?.account||"",accountVerified:!!r?.tweetMeta?.accountVerified,tweet:r?.tweetMeta?.tweet,tweetId:e.data.question.id,tweetMedia:i};this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e.data?.question?.id,e.data?.feedItem),close:()=>this.closeQuestion(e.data?.question?.id),autoHideDuration:1e3*120,emitEvent:!0,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),data:{questionId:e.data.question.id,questionType:e.data.question.type,tweet:o,inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}})}}}}const Fo={[V.SdkOverlayType.GAMES]:!0};class Do extends Tr{constructor(e,n){super(e,n)}}const Ro=(t,e,n)=>t.type===V.SdkOverlayType.GAMES?new No(t,e,n):new Do(t,e),Vo=(t,e,n)=>{t.features=new Map,t.sdk.featuresList=new J(Q(new Set),"features-list"),t.activeFeature=new J(Q(V.SdkOverlayType.UNSET),"activeFeature"),t.sdk.getFeatures=()=>t.features,t.sdk.getFeature=r=>t.features.get(r),t.sdk.getActiveFeature=()=>t.activeFeature.getStore(),t.sdk.openFeature=r=>{t.sdk.initializeApp().then(()=>{t.activeFeature.setValue(r)})},t.sdk.closeFeature=(r=!1)=>{const i=t.activeFeature.getValue();if(t.activeFeature.setValue(V.SdkOverlayType.UNSET),r&&i){t.features.delete(i);const o=t.sdk.featuresList.getValue();o&&o.delete(i),t.sdk.featuresList.setValue(o)}},t.initFeature=(r,i=pe.ORGANIZATION)=>{if(r.type in Fo&&!t.features.has(r.type)){const o=Ro(r,i,t);t.features.set(r.type,o);let s=t.sdk.featuresList.getValue();s?s.add(r.type):s=new Set([r.type]),t.sdk.featuresList.setValue(new Set(s))}},t.updateFeature=(r,i)=>{t.features.get(r.type)?.update(r,i)},t.destroyFeature=r=>{t.features.delete(r.type);const i=t.sdk.featuresList.getValue();i&&i.delete(r.type),t.sdk.featuresList.setValue(new Set(i))},t.reinitializeFeatures=async()=>{const r=await t.stores.organizationSettings.getValue();t.features.clear(),t.sdk.featuresList.setValue(new Set);for(const i of r?.overlays||[])t.initFeature(i,pe.ORGANIZATION)},t.stores.providerStreamId.listen(r=>{r||t.reinitializeFeatures()}),t.storeSubscribe=()=>{const r=(o,s)=>{if(s?.overlays&&!(t.contextConfig?.skipOrganizationSettings&&o===pe.ORGANIZATION))for(const a of s.overlays)a.sdkEnable===!0&&(t.features.has(a.type)?t.updateFeature(a,o):t.initFeature(a,o))},i={organizationSettings:o=>{if(o.data)try{r(pe.ORGANIZATION,o.data)}catch(s){console.log(s)}},streamSettings:o=>{if(o.data)try{r(pe.STREAM,o.data)}catch(s){console.log(s)}}};t.store.subscribe(i)},n()};class $o{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="invitation")switch(r.slEventBus.action){case"sent":this.sent(r.slEventBus.payload);break}};return q.listen(n)})}accepted=()=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_ACCEPTED},category:st.InvitationCategory.GAMES,from:st.InvitationFrom.UNSET})};sent=({from:e})=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_SENT},category:st.InvitationCategory.GAMES,from:e||st.InvitationFrom.UNSET})}}class Bo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="interactions")switch(r.slEventBus.action){case"tap":this.tap();break;case"scroll":this.scroll();break}};return q.listen(n)})}tap=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:Dn.InteractionActionType.TAP})};scroll=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:Dn.InteractionActionType.SCROLL})}}const Mo={[S.PromotionType.UNSET]:v.TopicSubType.UNSET,[S.PromotionType.INGAME_IAB21]:v.TopicSubType.PROMOTION_INGAME_IAB21,[S.PromotionType.INGAME_IAB11_LBAR]:v.TopicSubType.PROMOTION_INGAME_IAB11_LBAR,[S.PromotionType.INGAME_IAB11]:v.TopicSubType.PROMOTION_INGAME_IAB11,[S.PromotionType.INGAME_IAB21_LBAR]:v.TopicSubType.PROMOTION_INGAME_IAB21_LBAR,[S.PromotionType.INGAME_IAB61]:v.TopicSubType.PROMOTION_INGAME_IAB61,[S.PromotionType.EXTERNAL_AD]:v.TopicSubType.PROMOTION_GAM,[S.PromotionType.VIDEO_SIDE_BY_SIDE]:v.TopicSubType.PROMOTION_VIDEO_SIDE_BY_SIDE,[S.PromotionType.PICTURE_IN_PICTURE]:v.TopicSubType.PROMOTION_PICTURE_IN_PICTURE,[S.PromotionType.SHOP_LBAR]:v.TopicSubType.PROMOTION_SHOP_LBAR,[S.PromotionType.SHOP_OVERLAY]:v.TopicSubType.PROMOTION_SHOP_OVERLAY,[S.PromotionType.SHOP_SIDEBAR]:v.TopicSubType.PROMOTION_SHOP_SIDEBAR},on=t=>t?Mo[t]:v.TopicSubType.UNSET;class qo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(!r.slEventBus?.skipAnalytics&&r.slEventBus?.type==="advertisement"){const i=on(r.slEventBus.payload.type);switch(r.slEventBus.action){case"videoPlay":this.videoPlay(r.slEventBus.payload,{topicSubType:i});break;case"buttonSelect":this.buttonSelect(r.slEventBus.payload,{topicSubType:i});break;case"bannerSelect":this.bannerSelect(r.slEventBus.payload,{topicSubType:i});break;case"received":this.received(r.slEventBus.payload,{topicSubType:i});break;case"opened":this.opened(r.slEventBus.payload,{topicSubType:i});break;case"viewed":this.viewed(r.slEventBus.payload,{topicSubType:i});break}}};return q.listen(n)})}received=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_RECEIVED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};opened=({id:e,openedFrom:n},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:n==="notification"?v.PollOpenedFrom.IN_APP:v.PollOpenedFrom.UNSET})};viewed=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};videoPlay=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_VIDEO_PLAYED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};buttonSelect=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_BUTTON_NAVIGATED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};bannerSelect=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_BANNER_NAVIGATED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})}}const Je={[S.QuestionType.UNSET]:v.TopicType.UNSET,[S.QuestionType.FACTOID]:v.TopicType.POLLS_INSIGHT,[S.QuestionType.POLL]:v.TopicType.POLLS_POLL,[S.QuestionType.PREDICTION]:v.TopicType.POLLS_PREDICTION,[S.QuestionType.PROMOTION]:v.TopicType.POLLS_PROMOTION,[S.QuestionType.TRIVIA]:v.TopicType.POLLS_TRIVIA,[S.QuestionType.TWEET]:v.TopicType.POLLS_TWITTER};S.QuestionType.UNSET+"",ee.NotificationKind.UNSET,S.QuestionType.FACTOID+"",ee.NotificationKind.POLLS,S.QuestionType.POLL+"",ee.NotificationKind.POLLS,S.QuestionType.PREDICTION+"",ee.NotificationKind.POLLS,S.QuestionType.PROMOTION+"",ee.NotificationKind.POLLS,S.QuestionType.TRIVIA+"",ee.NotificationKind.POLLS,S.QuestionType.TWEET+"",ee.NotificationKind.POLLS;const Uo={[V.SdkOverlayType.UNSET]:v.Category.UNSET,[V.SdkOverlayType.INPLAY]:v.Category.INPLAY,[V.SdkOverlayType.MESSAGING]:v.Category.MESSAGING,[V.SdkOverlayType.STATISTICS]:v.Category.STATS,[V.SdkOverlayType.BETTING]:v.Category.BETTING,[V.SdkOverlayType.TWITTER]:v.Category.TWITTER,[V.SdkOverlayType.MERCHANDISE]:v.Category.MERCHANDISE,[V.SdkOverlayType.CONTESTS]:v.Category.CONTESTS,[V.SdkOverlayType.VOICE_CHAT]:v.Category.CALLING,[V.SdkOverlayType.TICKETS]:v.Category.TICKETS,[V.SdkOverlayType.WHOIS_WATCHING]:v.Category.WHOISWATCHING,[V.SdkOverlayType.PROFILE]:v.Category.PROFILE,[V.SdkOverlayType.GAMES]:v.Category.POLLS,[V.SdkOverlayType.GOLF_STATISTICS]:v.Category.STATS,[V.SdkOverlayType.HIGHLIGHTS]:v.Category.HIGHLIGHTS,[V.SdkOverlayType.PUBLIC_CHAT]:v.Category.PUBLIC_CHAT};class Qo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="notification")switch(r.slEventBus.action){case"rendered":this.received(r.slEventBus.payload);break;case"opened":this.opened(r.slEventBus.payload);break}if(r.slEventBus?.type==="advertisement")switch(r.slEventBus.action){case"notification-received":this.received({questionId:r.slEventBus.payload.id,questionType:S.QuestionType.PROMOTION,topicSubType:on(r.slEventBus.payload.type)});break;case"notification-opened":this.opened({questionId:r.slEventBus.payload.id,questionType:S.QuestionType.PROMOTION,topicSubType:on(r.slEventBus.payload.type)});break}};return q.listen(n)})}received=({questionId:e,questionType:n,topicSubType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_RECEIVED,topicId:e,topicType:n?Je[n]:v.TopicType.UNSET,topicSubType:r},notificationKind:ee.NotificationKind.POLLS,notificationType:ee.NotificationType.IN_APP})};opened=({questionId:e,questionType:n,topicSubType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_OPENED,topicId:e,topicType:n?Je[n]:v.TopicType.UNSET,topicSubType:r},notificationKind:ee.NotificationKind.POLLS,notificationType:ee.NotificationType.IN_APP})}}class jo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="poll")switch(r.slEventBus.action){case"voted":this.voted(r.slEventBus.payload);break;case"navigated":this.navigated();break;case"onboardingPassed":this.onboardingPassed();break;case"received":this.received(r.slEventBus.payload);break;case"opened":this.opened(r.slEventBus.payload);break}};return q.listen(n)})}received=({questionId:e,questionType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_RECEIVED,topicId:e,topicType:n?Je[n]:v.TopicType.UNSET},pollOpenedFrom:v.PollOpenedFrom.UNSET})};opened=({questionId:e,questionType:n,questionOpenedFrom:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:n?Je[n]:v.TopicType.UNSET},pollOpenedFrom:r==="list"?v.PollOpenedFrom.PICK_HISTORY:v.PollOpenedFrom.IN_APP})};voted=({questionId:e,questionType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_VOTE,topicId:e,topicType:n?Je[n]:v.TopicType.UNSET},pollOpenedFrom:v.PollOpenedFrom.UNSET})};onboardingPassed=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.GAMES_JOINED},pollOpenedFrom:v.PollOpenedFrom.UNSET})};navigated=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_NAVIGATED},pollOpenedFrom:v.PollOpenedFrom.UNSET})}}const xo=({transport:t,$commonStore:e})=>{let n;const r=Q(!1),i=3e4,{client:o,queryKey:s}=t.createPromiseClient(mr.AnalyticsService,{method:"send",params:[r]}),a=t.nanoquery.createFetcherStore(s,{fetcher:async()=>{const p=e.getStore().get();try{await o.unary({message:{case:"heartbeat",value:{common:{...p,kind:v.Kind.SESSION_HEARTBEAT}}}})}catch(w){ye.error(w,"send heartbeat failed")}return Date.now()},refetchInterval:i}),u=()=>{ye.debug("mounted heartbeat"),n=a.subscribe(()=>{})},d=()=>{ye.debug("enabled heartbeat"),r.set(!0),a.lc===0&&u()},c=()=>{ye.debug("disabled heartbeat"),r.set(!1)};return{enable:d,disable:c,mount:u,unmount:()=>{ye.debug("unmounted heartbeat"),a.off(),n?.(),n=void 0,c()}}},ye=ce("analytics");class Go{commonStore;notifications;polls;invitation;interactions;advertisement;heartbeat;analyticsClient;listeners;listenersCancels;connected=!1;constructor(e){this.listeners=new Set,this.listenersCancels=new Set,this.commonStore=new Ie(H({}),"common-analytics"),this.connectToSDK(e),this.heartbeat=xo({transport:e.analyticsTransport,$commonStore:this.commonStore}),this.notifications=new Qo(this),this.polls=new jo(this),this.invitation=new $o(this),this.interactions=new Bo(this),this.advertisement=new qo(this);const{client:n}=e.analyticsTransport.createPromiseClient(mr.AnalyticsService,{method:"send"});this.analyticsClient=n}connect=()=>{this.writeCommon("sessionId",Zt.v4()),this.heartbeat.enable(),this.listeners.forEach(e=>this.listenersCancels.add(e())),this.connected=!0,ye.debug("analytics connected")};disconnect=()=>{this.writeCommon("sessionId",""),this.writeCommon("overlaySessionId",""),this.heartbeat.unmount(),this.listenersCancels.forEach(e=>e()),this.connected=!1,ye.debug("analytics disconnected")};write=(e,n)=>{n&&this.analyticsClient.unary({message:{case:e,value:n}}).then(()=>{ye.trace("send analytics success",e,n)}).catch(r=>{ye.error(r,"send analytics failed")})};writeCommon=(e,n)=>{this.commonStore.setValue(e,n)};onConnect=e=>{this.listeners.add(e),this.connected&&this.listenersCancels.add(e())};connectToSDK=e=>{this.onConnect(()=>e.stores.slStreamId.getAtomStore().subscribe(n=>{this.writeCommon("eventId",n)})),this.onConnect(()=>e.sdk.getActiveFeature().subscribe(n=>{n&&this.writeCommon("category",Uo[n]),n!==V.SdkOverlayType.UNSET?this.writeCommon("overlaySessionId",Zt.v4()):this.writeCommon("overlaySessionId","")})),this.onConnect(()=>{const n=window.matchMedia("(orientation: portrait)"),r=i=>{this.writeCommon("screenOrientation",i.matches?v.ScreenOrientation.PORTRAIT:v.ScreenOrientation.LANDSCAPE)};return n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}}),this.onConnect(()=>e.deepLink.$store.subscribe(n=>{n?.handled&&this.invitation.accepted()}))}}const Ko=(t,e,n)=>{t.analytics=new Go(t),t.sdk.onMount({name:"analytics"},()=>(t.analytics.connect(),()=>{t.analytics.disconnect()})),n()};var mn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var bn={exports:{}},vn={exports:{}};function Ho(t){var e=new t,n=e;function r(){var o=e;return o.next?e=o.next:(e=new t,n=e),o.next=null,o}function i(o){n.next=o,n=o}return{get:r,release:i}}var Wo=Ho,Yo=Wo;function Cr(t,e,n){if(typeof t=="function"&&(n=e,e=t,t=null),!(n>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");var r=Yo(Jo),i=null,o=null,s=0,a=null,u={push:g,drain:Y,saturated:Y,pause:c,paused:!1,get concurrency(){return n},set concurrency(N){if(!(N>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(n=N,!u.paused)for(;i&&s<n;)s++,T()},running:d,resume:w,idle:E,length:f,getQueue:p,unshift:m,empty:Y,kill:D,killAndDrain:K,error:X};return u;function d(){return s}function c(){u.paused=!0}function f(){for(var N=i,$=0;N;)N=N.next,$++;return $}function p(){for(var N=i,$=[];N;)$.push(N.value),N=N.next;return $}function w(){if(u.paused){if(u.paused=!1,i===null){s++,T();return}for(;i&&s<n;)s++,T()}}function E(){return s===0&&u.length()===0}function g(N,$){var _=r.get();_.context=t,_.release=T,_.value=N,_.callback=$||Y,_.errorHandler=a,s>=n||u.paused?o?(o.next=_,o=_):(i=_,o=_,u.saturated()):(s++,e.call(t,_.value,_.worked))}function m(N,$){var _=r.get();_.context=t,_.release=T,_.value=N,_.callback=$||Y,_.errorHandler=a,s>=n||u.paused?i?(_.next=i,i=_):(i=_,o=_,u.saturated()):(s++,e.call(t,_.value,_.worked))}function T(N){N&&r.release(N);var $=i;$&&s<=n?u.paused?s--:(o===i&&(o=null),i=$.next,$.next=null,e.call(t,$.value,$.worked),o===null&&u.empty()):--s===0&&u.drain()}function D(){i=null,o=null,u.drain=Y}function K(){i=null,o=null,u.drain(),u.drain=Y}function X(N){a=N}}function Y(){}function Jo(){this.value=null,this.callback=Y,this.next=null,this.release=Y,this.context=null,this.errorHandler=null;var t=this;this.worked=function(n,r){var i=t.callback,o=t.errorHandler,s=t.value;t.value=null,t.callback=Y,t.errorHandler&&o(n,s),i.call(t.context,n,r),t.release(t)}}function Xo(t,e,n){typeof t=="function"&&(n=e,e=t,t=null);function r(c,f){e.call(this,c).then(function(p){f(null,p)},f)}var i=Cr(t,r,n),o=i.push,s=i.unshift;return i.push=a,i.unshift=u,i.drained=d,i;function a(c){var f=new Promise(function(p,w){o(c,function(E,g){if(E){w(E);return}p(g)})});return f.catch(Y),f}function u(c){var f=new Promise(function(p,w){s(c,function(E,g){if(E){w(E);return}p(g)})});return f.catch(Y),f}function d(){if(i.idle())return new Promise(function(p){p()});var c=i.drain,f=new Promise(function(p){i.drain=function(){c(),p()}});return f}}vn.exports=Cr;vn.exports.promise=Xo;var Pr=vn.exports,Sn={exports:{}},Ue=typeof Reflect=="object"?Reflect:null,Kn=Ue&&typeof Ue.apply=="function"?Ue.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},lt;Ue&&typeof Ue.ownKeys=="function"?lt=Ue.ownKeys:Object.getOwnPropertySymbols?lt=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:lt=function(e){return Object.getOwnPropertyNames(e)};function Zo(t){console&&console.warn&&console.warn(t)}var Lr=Number.isNaN||function(e){return e!==e};function F(){F.init.call(this)}Sn.exports=F;Sn.exports.once=rs;F.EventEmitter=F;F.prototype._events=void 0;F.prototype._eventsCount=0;F.prototype._maxListeners=void 0;var zn=10;function _t(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(F,"defaultMaxListeners",{enumerable:!0,get:function(){return zn},set:function(t){if(typeof t!="number"||t<0||Lr(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");zn=t}});F.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};F.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Lr(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Nr(t){return t._maxListeners===void 0?F.defaultMaxListeners:t._maxListeners}F.prototype.getMaxListeners=function(){return Nr(this)};F.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(n.length>0&&(s=n[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var u=o[e];if(u===void 0)return!1;if(typeof u=="function")Kn(u,this,n);else for(var d=u.length,c=$r(u,d),r=0;r<d;++r)Kn(c[r],this,n);return!0};function Fr(t,e,n,r){var i,o,s;if(_t(n),o=t._events,o===void 0?(o=t._events=Object.create(null),t._eventsCount=0):(o.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),o=t._events),s=o[e]),s===void 0)s=o[e]=n,++t._eventsCount;else if(typeof s=="function"?s=o[e]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=Nr(t),i>0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,Zo(a)}return t}F.prototype.addListener=function(e,n){return Fr(this,e,n,!1)};F.prototype.on=F.prototype.addListener;F.prototype.prependListener=function(e,n){return Fr(this,e,n,!0)};function es(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Dr(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=es.bind(r);return i.listener=n,r.wrapFn=i,i}F.prototype.once=function(e,n){return _t(n),this.on(e,Dr(this,e,n)),this};F.prototype.prependOnceListener=function(e,n){return _t(n),this.prependListener(e,Dr(this,e,n)),this};F.prototype.removeListener=function(e,n){var r,i,o,s,a;if(_t(n),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(o=-1,s=r.length-1;s>=0;s--)if(r[s]===n||r[s].listener===n){a=r[s].listener,o=s;break}if(o<0)return this;o===0?r.shift():ts(r,o),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||n)}return this};F.prototype.off=F.prototype.removeListener;F.prototype.removeAllListeners=function(e){var n,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var o=Object.keys(r),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=r[e],typeof n=="function")this.removeListener(e,n);else if(n!==void 0)for(i=n.length-1;i>=0;i--)this.removeListener(e,n[i]);return this};function Rr(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?ns(i):$r(i,i.length)}F.prototype.listeners=function(e){return Rr(this,e,!0)};F.prototype.rawListeners=function(e){return Rr(this,e,!1)};F.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Vr.call(t,e)};F.prototype.listenerCount=Vr;function Vr(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}F.prototype.eventNames=function(){return this._eventsCount>0?lt(this._events):[]};function $r(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function ts(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function ns(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function rs(t,e){return new Promise(function(n,r){function i(s){t.removeListener(e,o),r(s)}function o(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}Br(t,e,o,{once:!0}),e!=="error"&&is(t,i,{once:!0})})}function is(t,e,n){typeof t.on=="function"&&Br(t,"error",e,n)}function Br(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(o){r.once&&t.removeEventListener(e,i),n(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Mr=Sn.exports,Ct={},qr={},Ur=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},n=Symbol("test"),r=Object(n);if(typeof n=="string"||Object.prototype.toString.call(n)!=="[object Symbol]"||Object.prototype.toString.call(r)!=="[object Symbol]")return!1;var i=42;e[n]=i;for(n in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var o=Object.getOwnPropertySymbols(e);if(o.length!==1||o[0]!==n||!Object.prototype.propertyIsEnumerable.call(e,n))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(e,n);if(s.value!==i||s.enumerable!==!0)return!1}return!0},os=Ur,Pt=function(){return os()&&!!Symbol.toStringTag},ss=Error,as=EvalError,us=RangeError,cs=ReferenceError,Qr=SyntaxError,Lt=TypeError,ds=URIError,Hn=typeof Symbol<"u"&&Symbol,ls=Ur,fs=function(){return typeof Hn!="function"||typeof Symbol!="function"||typeof Hn("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:ls()},Vt={__proto__:null,foo:{}},ps=Object,hs=function(){return{__proto__:Vt}.foo===Vt.foo&&!(Vt instanceof ps)},ys="Function.prototype.bind called on incompatible ",gs=Object.prototype.toString,ms=Math.max,bs="[object Function]",Wn=function(e,n){for(var r=[],i=0;i<e.length;i+=1)r[i]=e[i];for(var o=0;o<n.length;o+=1)r[o+e.length]=n[o];return r},vs=function(e,n){for(var r=[],i=n,o=0;i<e.length;i+=1,o+=1)r[o]=e[i];return r},Ss=function(t,e){for(var n="",r=0;r<t.length;r+=1)n+=t[r],r+1<t.length&&(n+=e);return n},ws=function(e){var n=this;if(typeof n!="function"||gs.apply(n)!==bs)throw new TypeError(ys+n);for(var r=vs(arguments,1),i,o=function(){if(this instanceof i){var c=n.apply(this,Wn(r,arguments));return Object(c)===c?c:this}return n.apply(e,Wn(r,arguments))},s=ms(0,n.length-r.length),a=[],u=0;u<s;u++)a[u]="$"+u;if(i=Function("binder","return function ("+Ss(a,",")+"){ return binder.apply(this,arguments); }")(o),n.prototype){var d=function(){};d.prototype=n.prototype,i.prototype=new d,d.prototype=null}return i},Ts=ws,wn=Function.prototype.bind||Ts,Es=Function.prototype.call,As=Object.prototype.hasOwnProperty,Is=wn,Os=Is.call(Es,As),k,ks=ss,_s=as,Cs=us,Ps=cs,xe=Qr,Qe=Lt,Ls=ds,jr=Function,$t=function(t){try{return jr('"use strict"; return ('+t+").constructor;")()}catch{}},Oe=Object.getOwnPropertyDescriptor;if(Oe)try{Oe({},"")}catch{Oe=null}var Bt=function(){throw new Qe},Ns=Oe?function(){try{return arguments.callee,Bt}catch{try{return Oe(arguments,"callee").get}catch{return Bt}}}():Bt,De=fs(),Fs=hs(),j=Object.getPrototypeOf||(Fs?function(t){return t.__proto__}:null),Ve={},Ds=typeof Uint8Array>"u"||!j?k:j(Uint8Array),ke={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?k:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?k:ArrayBuffer,"%ArrayIteratorPrototype%":De&&j?j([][Symbol.iterator]()):k,"%AsyncFromSyncIteratorPrototype%":k,"%AsyncFunction%":Ve,"%AsyncGenerator%":Ve,"%AsyncGeneratorFunction%":Ve,"%AsyncIteratorPrototype%":Ve,"%Atomics%":typeof Atomics>"u"?k:Atomics,"%BigInt%":typeof BigInt>"u"?k:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?k:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?k:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?k:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":ks,"%eval%":eval,"%EvalError%":_s,"%Float32Array%":typeof Float32Array>"u"?k:Float32Array,"%Float64Array%":typeof Float64Array>"u"?k:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?k:FinalizationRegistry,"%Function%":jr,"%GeneratorFunction%":Ve,"%Int8Array%":typeof Int8Array>"u"?k:Int8Array,"%Int16Array%":typeof Int16Array>"u"?k:Int16Array,"%Int32Array%":typeof Int32Array>"u"?k:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":De&&j?j(j([][Symbol.iterator]())):k,"%JSON%":typeof JSON=="object"?JSON:k,"%Map%":typeof Map>"u"?k:Map,"%MapIteratorPrototype%":typeof Map>"u"||!De||!j?k:j(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?k:Promise,"%Proxy%":typeof Proxy>"u"?k:Proxy,"%RangeError%":Cs,"%ReferenceError%":Ps,"%Reflect%":typeof Reflect>"u"?k:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?k:Set,"%SetIteratorPrototype%":typeof Set>"u"||!De||!j?k:j(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?k:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":De&&j?j(""[Symbol.iterator]()):k,"%Symbol%":De?Symbol:k,"%SyntaxError%":xe,"%ThrowTypeError%":Ns,"%TypedArray%":Ds,"%TypeError%":Qe,"%Uint8Array%":typeof Uint8Array>"u"?k:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?k:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?k:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?k:Uint32Array,"%URIError%":Ls,"%WeakMap%":typeof WeakMap>"u"?k:WeakMap,"%WeakRef%":typeof WeakRef>"u"?k:WeakRef,"%WeakSet%":typeof WeakSet>"u"?k:WeakSet};if(j)try{null.error}catch(t){var Rs=j(j(t));ke["%Error.prototype%"]=Rs}var Vs=function t(e){var n;if(e==="%AsyncFunction%")n=$t("async function () {}");else if(e==="%GeneratorFunction%")n=$t("function* () {}");else if(e==="%AsyncGeneratorFunction%")n=$t("async function* () {}");else if(e==="%AsyncGenerator%"){var r=t("%AsyncGeneratorFunction%");r&&(n=r.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&j&&(n=j(i.prototype))}return ke[e]=n,n},Yn={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},et=wn,vt=Os,$s=et.call(Function.call,Array.prototype.concat),Bs=et.call(Function.apply,Array.prototype.splice),Jn=et.call(Function.call,String.prototype.replace),St=et.call(Function.call,String.prototype.slice),Ms=et.call(Function.call,RegExp.prototype.exec),qs=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Us=/\\(\\)?/g,Qs=function(e){var n=St(e,0,1),r=St(e,-1);if(n==="%"&&r!=="%")throw new xe("invalid intrinsic syntax, expected closing `%`");if(r==="%"&&n!=="%")throw new xe("invalid intrinsic syntax, expected opening `%`");var i=[];return Jn(e,qs,function(o,s,a,u){i[i.length]=a?Jn(u,Us,"$1"):s||o}),i},js=function(e,n){var r=e,i;if(vt(Yn,r)&&(i=Yn[r],r="%"+i[0]+"%"),vt(ke,r)){var o=ke[r];if(o===Ve&&(o=Vs(r)),typeof o>"u"&&!n)throw new Qe("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:r,value:o}}throw new xe("intrinsic "+e+" does not exist!")},tt=function(e,n){if(typeof e!="string"||e.length===0)throw new Qe("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof n!="boolean")throw new Qe('"allowMissing" argument must be a boolean');if(Ms(/^%?[^%]*%?$/,e)===null)throw new xe("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=Qs(e),i=r.length>0?r[0]:"",o=js("%"+i+"%",n),s=o.name,a=o.value,u=!1,d=o.alias;d&&(i=d[0],Bs(r,$s([0,1],d)));for(var c=1,f=!0;c<r.length;c+=1){var p=r[c],w=St(p,0,1),E=St(p,-1);if((w==='"'||w==="'"||w==="`"||E==='"'||E==="'"||E==="`")&&w!==E)throw new xe("property names with quotes must have matching quotes");if((p==="constructor"||!f)&&(u=!0),i+="."+p,s="%"+i+"%",vt(ke,s))a=ke[s];else if(a!=null){if(!(p in a)){if(!n)throw new Qe("base intrinsic for "+e+" exists, but the property is not available.");return}if(Oe&&c+1>=r.length){var g=Oe(a,p);f=!!g,f&&"get"in g&&!("originalValue"in g.get)?a=g.get:a=a[p]}else f=vt(a,p),a=a[p];f&&!u&&(ke[s]=a)}}return a},xr={exports:{}},Mt,Xn;function Tn(){if(Xn)return Mt;Xn=1;var t=tt,e=t("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Mt=e,Mt}var xs=tt,ft=xs("%Object.getOwnPropertyDescriptor%",!0);if(ft)try{ft([],"length")}catch{ft=null}var Nt=ft,Zn=Tn(),Gs=Qr,Re=Lt,er=Nt,Ks=function(e,n,r){if(!e||typeof e!="object"&&typeof e!="function")throw new Re("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new Re("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Re("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Re("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Re("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Re("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,o=arguments.length>4?arguments[4]:null,s=arguments.length>5?arguments[5]:null,a=arguments.length>6?arguments[6]:!1,u=!!er&&er(e,n);if(Zn)Zn(e,n,{configurable:s===null&&u?u.configurable:!s,enumerable:i===null&&u?u.enumerable:!i,value:r,writable:o===null&&u?u.writable:!o});else if(a||!i&&!o&&!s)e[n]=r;else throw new Gs("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},sn=Tn(),Gr=function(){return!!sn};Gr.hasArrayLengthDefineBug=function(){if(!sn)return null;try{return sn([],"length",{value:1}).length!==1}catch{return!0}};var zs=Gr,Hs=tt,tr=Ks,Ws=zs(),nr=Nt,rr=Lt,Ys=Hs("%Math.floor%"),Js=function(e,n){if(typeof e!="function")throw new rr("`fn` is not a function");if(typeof n!="number"||n<0||n>4294967295||Ys(n)!==n)throw new rr("`length` must be a positive 32-bit integer");var r=arguments.length>2&&!!arguments[2],i=!0,o=!0;if("length"in e&&nr){var s=nr(e,"length");s&&!s.configurable&&(i=!1),s&&!s.writable&&(o=!1)}return(i||o||!r)&&(Ws?tr(e,"length",n,!0,!0):tr(e,"length",n)),e};(function(t){var e=wn,n=tt,r=Js,i=Lt,o=n("%Function.prototype.apply%"),s=n("%Function.prototype.call%"),a=n("%Reflect.apply%",!0)||e.call(s,o),u=Tn(),d=n("%Math.max%");t.exports=function(p){if(typeof p!="function")throw new i("a function is required");var w=a(e,s,arguments);return r(w,1+d(0,p.length-(arguments.length-1)),!0)};var c=function(){return a(e,o,arguments)};u?u(t.exports,"apply",{value:c}):t.exports.apply=c})(xr);var En=xr.exports,Kr=tt,zr=En,Xs=zr(Kr("String.prototype.indexOf")),An=function(e,n){var r=Kr(e,!!n);return typeof r=="function"&&Xs(e,".prototype.")>-1?zr(r):r},Zs=Pt(),ea=An,an=ea("Object.prototype.toString"),Ft=function(e){return Zs&&e&&typeof e=="object"&&Symbol.toStringTag in e?!1:an(e)==="[object Arguments]"},Hr=function(e){return Ft(e)?!0:e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&an(e)!=="[object Array]"&&an(e.callee)==="[object Function]"},ta=function(){return Ft(arguments)}();Ft.isLegacyArguments=Hr;var na=ta?Ft:Hr,ra=Object.prototype.toString,ia=Function.prototype.toString,oa=/^\s*(?:function)?\*/,Wr=Pt(),qt=Object.getPrototypeOf,sa=function(){if(!Wr)return!1;try{return Function("return function*() {}")()}catch{}},Ut,aa=function(e){if(typeof e!="function")return!1;if(oa.test(ia.call(e)))return!0;if(!Wr){var n=ra.call(e);return n==="[object GeneratorFunction]"}if(!qt)return!1;if(typeof Ut>"u"){var r=sa();Ut=r?qt(r):!1}return qt(e)===Ut},Yr=Function.prototype.toString,Be=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,un,pt;if(typeof Be=="function"&&typeof Object.defineProperty=="function")try{un=Object.defineProperty({},"length",{get:function(){throw pt}}),pt={},Be(function(){throw 42},null,un)}catch(t){t!==pt&&(Be=null)}else Be=null;var ua=/^\s*class\b/,cn=function(e){try{var n=Yr.call(e);return ua.test(n)}catch{return!1}},Qt=function(e){try{return cn(e)?!1:(Yr.call(e),!0)}catch{return!1}},ht=Object.prototype.toString,ca="[object Object]",da="[object Function]",la="[object GeneratorFunction]",fa="[object HTMLAllCollection]",pa="[object HTML document.all class]",ha="[object HTMLCollection]",ya=typeof Symbol=="function"&&!!Symbol.toStringTag,ga=!(0 in[,]),dn=function(){return!1};if(typeof document=="object"){var ma=document.all;ht.call(ma)===ht.call(document.all)&&(dn=function(e){if((ga||!e)&&(typeof e>"u"||typeof e=="object"))try{var n=ht.call(e);return(n===fa||n===pa||n===ha||n===ca)&&e("")==null}catch{}return!1})}var ba=Be?function(e){if(dn(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Be(e,null,un)}catch(n){if(n!==pt)return!1}return!cn(e)&&Qt(e)}:function(e){if(dn(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(ya)return Qt(e);if(cn(e))return!1;var n=ht.call(e);return n!==da&&n!==la&&!/^\[object HTML/.test(n)?!1:Qt(e)},va=ba,Sa=Object.prototype.toString,Jr=Object.prototype.hasOwnProperty,wa=function(e,n,r){for(var i=0,o=e.length;i<o;i++)Jr.call(e,i)&&(r==null?n(e[i],i,e):n.call(r,e[i],i,e))},Ta=function(e,n,r){for(var i=0,o=e.length;i<o;i++)r==null?n(e.charAt(i),i,e):n.call(r,e.charAt(i),i,e)},Ea=function(e,n,r){for(var i in e)Jr.call(e,i)&&(r==null?n(e[i],i,e):n.call(r,e[i],i,e))},Aa=function(e,n,r){if(!va(n))throw new TypeError("iterator must be a function");var i;arguments.length>=3&&(i=r),Sa.call(e)==="[object Array]"?wa(e,n,i):typeof e=="string"?Ta(e,n,i):Ea(e,n,i)},Xr=Aa,Ia=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],jt=Ia,Oa=typeof globalThis>"u"?mn:globalThis,Zr=function(){for(var e=[],n=0;n<jt.length;n++)typeof Oa[jt[n]]=="function"&&(e[e.length]=jt[n]);return e},wt=Xr,ka=Zr,ir=En,In=An,yt=Nt,_a=In("Object.prototype.toString"),ei=Pt(),or=typeof globalThis>"u"?mn:globalThis,ln=ka(),On=In("String.prototype.slice"),xt=Object.getPrototypeOf,Ca=In("Array.prototype.indexOf",!0)||function(e,n){for(var r=0;r<e.length;r+=1)if(e[r]===n)return r;return-1},Tt={__proto__:null};ei&&yt&&xt?wt(ln,function(t){var e=new or[t];if(Symbol.toStringTag in e){var n=xt(e),r=yt(n,Symbol.toStringTag);if(!r){var i=xt(n);r=yt(i,Symbol.toStringTag)}Tt["$"+t]=ir(r.get)}}):wt(ln,function(t){var e=new or[t],n=e.slice||e.set;n&&(Tt["$"+t]=ir(n))});var Pa=function(e){var n=!1;return wt(Tt,function(r,i){if(!n)try{"$"+r(e)===i&&(n=On(i,1))}catch{}}),n},La=function(e){var n=!1;return wt(Tt,function(r,i){if(!n)try{r(e),n=On(i,1)}catch{}}),n},Na=function(e){if(!e||typeof e!="object")return!1;if(!ei){var n=On(_a(e),8,-1);return Ca(ln,n)>-1?n:n!=="Object"?!1:La(e)}return yt?Pa(e):null},Et=Xr,Fa=Zr,sr=En,kn=An,gt=Nt,Da=kn("Object.prototype.toString"),ti=Pt(),ar=typeof globalThis>"u"?mn:globalThis,fn=Fa(),_n=kn("String.prototype.slice"),Gt=Object.getPrototypeOf,Ra=kn("Array.prototype.indexOf",!0)||function(e,n){for(var r=0;r<e.length;r+=1)if(e[r]===n)return r;return-1},At={__proto__:null};ti&&gt&&Gt?Et(fn,function(t){var e=new ar[t];if(Symbol.toStringTag in e){var n=Gt(e),r=gt(n,Symbol.toStringTag);if(!r){var i=Gt(n);r=gt(i,Symbol.toStringTag)}At["$"+t]=sr(r.get)}}):Et(fn,function(t){var e=new ar[t],n=e.slice||e.set;n&&(At["$"+t]=sr(n))});var Va=function(e){var n=!1;return Et(At,function(r,i){if(!n)try{"$"+r(e)===i&&(n=_n(i,1))}catch{}}),n},$a=function(e){var n=!1;return Et(At,function(r,i){if(!n)try{r(e),n=_n(i,1)}catch{}}),n},Ba=function(e){if(!e||typeof e!="object")return!1;if(!ti){var n=_n(Da(e),8,-1);return Ra(fn,n)>-1?n:n!=="Object"?!1:$a(e)}return gt?Va(e):null},Ma=Ba,qa=function(e){return!!Ma(e)};(function(t){var e=na,n=aa,r=Na,i=qa;function o(y){return y.call.bind(y)}var s=typeof BigInt<"u",a=typeof Symbol<"u",u=o(Object.prototype.toString),d=o(Number.prototype.valueOf),c=o(String.prototype.valueOf),f=o(Boolean.prototype.valueOf);if(s)var p=o(BigInt.prototype.valueOf);if(a)var w=o(Symbol.prototype.valueOf);function E(y,ui){if(typeof y!="object")return!1;try{return ui(y),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=n,t.isTypedArray=i;function g(y){return typeof Promise<"u"&&y instanceof Promise||y!==null&&typeof y=="object"&&typeof y.then=="function"&&typeof y.catch=="function"}t.isPromise=g;function m(y){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(y):i(y)||h(y)}t.isArrayBufferView=m;function T(y){return r(y)==="Uint8Array"}t.isUint8Array=T;function D(y){return r(y)==="Uint8ClampedArray"}t.isUint8ClampedArray=D;function K(y){return r(y)==="Uint16Array"}t.isUint16Array=K;function X(y){return r(y)==="Uint32Array"}t.isUint32Array=X;function N(y){return r(y)==="Int8Array"}t.isInt8Array=N;function $(y){return r(y)==="Int16Array"}t.isInt16Array=$;function _(y){return r(y)==="Int32Array"}t.isInt32Array=_;function re(y){return r(y)==="Float32Array"}t.isFloat32Array=re;function ie(y){return r(y)==="Float64Array"}t.isFloat64Array=ie;function _e(y){return r(y)==="BigInt64Array"}t.isBigInt64Array=_e;function we(y){return r(y)==="BigUint64Array"}t.isBigUint64Array=we;function de(y){return u(y)==="[object Map]"}de.working=typeof Map<"u"&&de(new Map);function Dt(y){return typeof Map>"u"?!1:de.working?de(y):y instanceof Map}t.isMap=Dt;function ve(y){return u(y)==="[object Set]"}ve.working=typeof Set<"u"&&ve(new Set);function He(y){return typeof Set>"u"?!1:ve.working?ve(y):y instanceof Set}t.isSet=He;function Ce(y){return u(y)==="[object WeakMap]"}Ce.working=typeof WeakMap<"u"&&Ce(new WeakMap);function Rt(y){return typeof WeakMap>"u"?!1:Ce.working?Ce(y):y instanceof WeakMap}t.isWeakMap=Rt;function Pe(y){return u(y)==="[object WeakSet]"}Pe.working=typeof WeakSet<"u"&&Pe(new WeakSet);function le(y){return Pe(y)}t.isWeakSet=le;function Le(y){return u(y)==="[object ArrayBuffer]"}Le.working=typeof ArrayBuffer<"u"&&Le(new ArrayBuffer);function nt(y){return typeof ArrayBuffer>"u"?!1:Le.working?Le(y):y instanceof ArrayBuffer}t.isArrayBuffer=nt;function l(y){return u(y)==="[object DataView]"}l.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&l(new DataView(new ArrayBuffer(1),0,1));function h(y){return typeof DataView>"u"?!1:l.working?l(y):y instanceof DataView}t.isDataView=h;var b=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function A(y){return u(y)==="[object SharedArrayBuffer]"}function P(y){return typeof b>"u"?!1:(typeof A.working>"u"&&(A.working=A(new b)),A.working?A(y):y instanceof b)}t.isSharedArrayBuffer=P;function L(y){return u(y)==="[object AsyncFunction]"}t.isAsyncFunction=L;function O(y){return u(y)==="[object Map Iterator]"}t.isMapIterator=O;function C(y){return u(y)==="[object Set Iterator]"}t.isSetIterator=C;function R(y){return u(y)==="[object Generator]"}t.isGeneratorObject=R;function z(y){return u(y)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=z;function Te(y){return E(y,d)}t.isNumberObject=Te;function rt(y){return E(y,c)}t.isStringObject=rt;function Ne(y){return E(y,f)}t.isBooleanObject=Ne;function it(y){return s&&E(y,p)}t.isBigIntObject=it;function Ln(y){return a&&E(y,w)}t.isSymbolObject=Ln;function si(y){return Te(y)||rt(y)||Ne(y)||it(y)||Ln(y)}t.isBoxedPrimitive=si;function ai(y){return typeof Uint8Array<"u"&&(nt(y)||P(y))}t.isAnyArrayBuffer=ai,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(y){Object.defineProperty(t,y,{enumerable:!1,value:function(){throw new Error(y+" is not supported in userland")}})})})(qr);var Ua=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"},pn={exports:{}};typeof Object.create=="function"?pn.exports=function(e,n){n&&(e.super_=n,e.prototype=Object.create(n.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:pn.exports=function(e,n){if(n){e.super_=n;var r=function(){};r.prototype=n.prototype,e.prototype=new r,e.prototype.constructor=e}};var Qa=pn.exports;(function(t){var e=Object.getOwnPropertyDescriptors||function(h){for(var b=Object.keys(h),A={},P=0;P<b.length;P++)A[b[P]]=Object.getOwnPropertyDescriptor(h,b[P]);return A},n=/%[sdj%]/g;t.format=function(l){if(!N(l)){for(var h=[],b=0;b<arguments.length;b++)h.push(s(arguments[b]));return h.join(" ")}for(var b=1,A=arguments,P=A.length,L=String(l).replace(n,function(C){if(C==="%%")return"%";if(b>=P)return C;switch(C){case"%s":return String(A[b++]);case"%d":return Number(A[b++]);case"%j":try{return JSON.stringify(A[b++])}catch{return"[Circular]"}default:return C}}),O=A[b];b<P;O=A[++b])D(O)||!ie(O)?L+=" "+O:L+=" "+s(O);return L},t.deprecate=function(l,h){if(typeof I<"u"&&I.noDeprecation===!0)return l;if(typeof I>"u")return function(){return t.deprecate(l,h).apply(this,arguments)};var b=!1;function A(){if(!b){if(I.throwDeprecation)throw new Error(h);I.traceDeprecation?console.trace(h):console.error(h),b=!0}return l.apply(this,arguments)}return A};var r={},i=/^$/;if(I.env.NODE_DEBUG){var o=I.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}t.debuglog=function(l){if(l=l.toUpperCase(),!r[l])if(i.test(l)){var h=I.pid;r[l]=function(){var b=t.format.apply(t,arguments);console.error("%s %d: %s",l,h,b)}}else r[l]=function(){};return r[l]};function s(l,h){var b={seen:[],stylize:u};return arguments.length>=3&&(b.depth=arguments[2]),arguments.length>=4&&(b.colors=arguments[3]),T(h)?b.showHidden=h:h&&t._extend(b,h),_(b.showHidden)&&(b.showHidden=!1),_(b.depth)&&(b.depth=2),_(b.colors)&&(b.colors=!1),_(b.customInspect)&&(b.customInspect=!0),b.colors&&(b.stylize=a),c(b,l,b.depth)}t.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(l,h){var b=s.styles[h];return b?"\x1B["+s.colors[b][0]+"m"+l+"\x1B["+s.colors[b][1]+"m":l}function u(l,h){return l}function d(l){var h={};return l.forEach(function(b,A){h[b]=!0}),h}function c(l,h,b){if(l.customInspect&&h&&de(h.inspect)&&h.inspect!==t.inspect&&!(h.constructor&&h.constructor.prototype===h)){var A=h.inspect(b,l);return N(A)||(A=c(l,A,b)),A}var P=f(l,h);if(P)return P;var L=Object.keys(h),O=d(L);if(l.showHidden&&(L=Object.getOwnPropertyNames(h)),we(h)&&(L.indexOf("message")>=0||L.indexOf("description")>=0))return p(h);if(L.length===0){if(de(h)){var C=h.name?": "+h.name:"";return l.stylize("[Function"+C+"]","special")}if(re(h))return l.stylize(RegExp.prototype.toString.call(h),"regexp");if(_e(h))return l.stylize(Date.prototype.toString.call(h),"date");if(we(h))return p(h)}var R="",z=!1,Te=["{","}"];if(m(h)&&(z=!0,Te=["[","]"]),de(h)){var rt=h.name?": "+h.name:"";R=" [Function"+rt+"]"}if(re(h)&&(R=" "+RegExp.prototype.toString.call(h)),_e(h)&&(R=" "+Date.prototype.toUTCString.call(h)),we(h)&&(R=" "+p(h)),L.length===0&&(!z||h.length==0))return Te[0]+R+Te[1];if(b<0)return re(h)?l.stylize(RegExp.prototype.toString.call(h),"regexp"):l.stylize("[Object]","special");l.seen.push(h);var Ne;return z?Ne=w(l,h,b,O,L):Ne=L.map(function(it){return E(l,h,b,O,it,z)}),l.seen.pop(),g(Ne,R,Te)}function f(l,h){if(_(h))return l.stylize("undefined","undefined");if(N(h)){var b="'"+JSON.stringify(h).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return l.stylize(b,"string")}if(X(h))return l.stylize(""+h,"number");if(T(h))return l.stylize(""+h,"boolean");if(D(h))return l.stylize("null","null")}function p(l){return"["+Error.prototype.toString.call(l)+"]"}function w(l,h,b,A,P){for(var L=[],O=0,C=h.length;O<C;++O)Pe(h,String(O))?L.push(E(l,h,b,A,String(O),!0)):L.push("");return P.forEach(function(R){R.match(/^\d+$/)||L.push(E(l,h,b,A,R,!0))}),L}function E(l,h,b,A,P,L){var O,C,R;if(R=Object.getOwnPropertyDescriptor(h,P)||{value:h[P]},R.get?R.set?C=l.stylize("[Getter/Setter]","special"):C=l.stylize("[Getter]","special"):R.set&&(C=l.stylize("[Setter]","special")),Pe(A,P)||(O="["+P+"]"),C||(l.seen.indexOf(R.value)<0?(D(b)?C=c(l,R.value,null):C=c(l,R.value,b-1),C.indexOf(`
2
+ `+r)}catch(i){Er(i)&&window.sessionStorage.removeItem("slstreamlogs"),window.sessionStorage.setItem("slstreamlogs",r)}}};addListener=(e,n)=>this.listeners.has(e)?(this.addStateLog(`listener '${e}' not added, already exists`),()=>{}):(this.listeners.set(e,n),this.addStateLog(`listener '${e}' added`),()=>this.removeListener(e));removeListener=e=>{this.listeners.delete(e),this.addStateLog(`listener '${e}' removed`)};connect=()=>{this.updateState(Z.Connecting),this.streamCancel&&(this.addStateLog("disconnect prev connection"),this.streamCancel.abort(),this.streamCancel=void 0);const e="get"in this.params&&typeof this.params.get=="function"?this.params.get():this.params;(async()=>{this.streamCancel=new AbortController;try{const r={headers:this.headers.getValues(),signal:this.streamCancel.signal},i=this.method(e,r);for await(const o of i)this.attempt=0,this.onData(o)}catch(r){r instanceof M.ConnectError&&r.code!=M.Code.Canceled&&this.onStreamError(r)}})(),this.updateState(Z.Connected)};disconnect=()=>{this.streamCancel&&this.streamCancel.abort(),this.listeners.clear(),this.paramsListener?.(),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.updateState(Z.Disconnected)};reconnect=()=>{if(this.reconnectTimeout)this.addStateLog("already reconnecting");else if(this.attempt<this.options.reconnectMaxAttempts){this.updateState(Z.Reconnect);const e=Math.min(this.options.reconnectMaxDelay,Math.pow(2,this.attempt)*this.options.reconnectDelay),n=Math.round(e*(1+Math.random())/2);this.reconnectTimeout=setTimeout(()=>{this.attempt++,this.updateState(Z.Reconnecting),this.addStateLog(`reconnect attempt ${this.attempt} after ${n}ms`),this.connect(),this.reconnectTimeout=void 0},n)}else this.addStateLog("max reconnect attempts reached"),this.disconnect()};getStore=()=>this.store?.getStore();onData=e=>{try{this.addStateLog(`received data => ${JSON.stringify(e)}`),this.store&&this.store.setValue(e);for(const[,n]of this.listeners)n(e);this.addStateLog(`data routed to ${this.listeners.size} listeners`)}catch(n){this.addStateLog(`error process data => ${n}`)}};onStreamError=e=>{if(this.addStateLog(`error => ${e?JSON.stringify(e):"undefined"}}`),e!==void 0){if(e instanceof M.ConnectError&&e.code!==M.Code.Canceled){this.updateState(Z.Failed),this.state.setValue("error",e),e.code===M.Code.Unknown&&e.cause==="missing trailer"&&(this.attempt=0),this.reconnect();return}this.disconnect()}}}const Ii=new Set([M.Code.Unknown,M.Code.Internal,M.Code.DeadlineExceeded,M.Code.ResourceExhausted,M.Code.FailedPrecondition,M.Code.Unavailable,M.Code.DataLoss]),Vn=ce("grpc:retry"),Oi=t=>async e=>{const n=e.contextValues.get(nn.retryAttempts),r=300,i=e.contextValues.get(nn.retryDelay);if(e.stream||n===0)return t(e);Vn.trace({url:e.url,attempts:n,maxDelay:i},"retry options");for(let o=0;;o++)try{return await t(e)}catch(s){Vn.trace({attempt:o,error:s,url:e.url},"retry attempt");const a=M.ConnectError.from(s);if(o>=n||!(a instanceof M.ConnectError)||!Ii.has(a.code))throw s;const u=Math.min(i,Math.pow(2,o)*r),d=Math.round(u*(1+Math.random())/2);await new Promise(c=>setTimeout(c,d))}},nn={retryAttempts:M.createContextKey(10,{description:"Number of attempts to retry"}),retryDelay:M.createContextKey(3e4,{description:"Max delay between retries in milliseconds"})},ki=()=>{const t=localStorage.getItem("sl-device-id");if(t)return t;const e=Zt.v4();return localStorage.setItem("sl-device-id",e),e},_i=()=>navigator.userAgentData?.platform||navigator.platform;class $n{toJsonOptions={emitDefaultValues:!1,enumAsInteger:!0,useProtoFieldName:!1};transport;streamTransport;nanoquery;host;$headers;interceptors=[];clients;streamClients;subscriptions;opts;constructor(e,n){this.host=e,this.opts=n,this.$headers=new Ie(H({"sl-device-id":ki(),"sl-device-os":_i()}),"transport:headers"),this.initInterceptors(),this.clients=new Map,this.streamClients=new Map,this.subscriptions=new Map;const[r,i,o]=Fn.nanoquery({dedupeTime:n?.dedupeTime,refetchInterval:n?.refetchInterval});this.nanoquery={createFetcherStore:r,createMutatorStore:i,utils:o},this.transport=Nn.createGrpcWebTransport({baseUrl:e,defaultTimeoutMs:1e4,interceptors:this.interceptors}),this.streamTransport=Nn.createGrpcWebTransport({baseUrl:e,interceptors:this.interceptors})}addSubscription=(e,n,r)=>{const i=this.subscriptions.get(n);if(i)return i;const o=new Ai(this.$headers,e,n,r);return this.subscriptions.set(n,o),o};removeSubscription=e=>{e.disconnect(),this.subscriptions.delete(e.params)};disconnect=()=>{for(const[i,o]of this.subscriptions)o.disconnect(),this.subscriptions.delete(i);this.clients.clear(),this.streamClients.clear(),this.subscriptions.clear();const[e,n,r]=Fn.nanoquery({dedupeTime:this.opts?.dedupeTime,refetchInterval:this.opts?.refetchInterval});this.nanoquery={createFetcherStore:e,createMutatorStore:n,utils:r}};registerInterceptor=e=>{this.interceptors.push(e)};removeInterceptor=e=>{this.interceptors=this.interceptors.filter(n=>n!==e)};getClient=e=>{const n=e.typeName;if(this.clients.has(n))return this.clients.get(n);const r=M.createClient(e,this.transport);return this.clients.set(n,r),r};getStreamClient=e=>{const n=`stream-${e.typeName}`;if(this.clients.has(n))return this.clients.get(n);const r=M.createClient(e,this.streamTransport);return this.clients.set(n,r),r};createPromiseClient=(e,{params:n=[],method:r})=>{const i=this.getClient(e),o=e.methods[r].name,s=[e.typeName,o.charAt(0).toLowerCase()+o.slice(1),...Array.isArray(n)?n:[n]],a=[e.typeName,o.charAt(0).toLowerCase()+o.slice(1)];return{client:i,createRequestOptions:d=>{const c=M.createContextValues();for(const f in d){const p=nn[f];c.set(p,d[f])}return c},queryKey:s,queryKeyStr:a.join("")}};createStreamClient=e=>({client:this.getStreamClient(e)});setSdkKey=e=>{this.$headers.setValue("sdk",e)};setAuth=(e,n)=>{this.$headers.setValue("authorization",e),this.$headers.setValue("sl-user-id",n)};setHeader=(e,n)=>this.$headers.setValue(e,n);getHeader=e=>this.$headers.getValue(e);getHeaders=()=>this.$headers.getValues();initInterceptors=()=>{if(this.interceptors.length!==0)return;const e=n=>r=>{const i=this.$headers.getValues();for(const o in i)r.header.set(o,i[o]);return n(r)};this.interceptors.push(e),this.interceptors.push(Ei()),this.opts?.retryable&&this.interceptors.push(Oi)}}const Ci=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(yr.Events,{method:"retrieveEventId",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s||typeof s!="string")return"";try{return(await n.retrieveEventId({id:s})).data?.id||""}catch{return""}}})},Pi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"getStream",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>s?(await n.getStream({id:s})).data?.attributes:void 0})},Li=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(yr.Events,{method:"summary",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>s?(await n.summary({id:s})).data?.attributes:void 0})},Ni=(t,e)=>{const{queryKey:n,client:r}=e.createPromiseClient(gn.Users,{method:"me",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>{if(!e.getHeader("authorization"))return{data:void 0};const{data:o}=await r.me({});return{data:o}}})},Fi=t=>{const{client:e,createRequestOptions:n}=t.createPromiseClient(gn.Users,{method:"bypassAuth"}),r=n({retryAttempts:0});return({userKey:i,schema:o,init:s,inviterKey:a})=>e.bypassAuth({userKey:i,schema:o,init:s,inviterKey:a},{contextValues:r})},Di=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>(await n.get({})).data?.attributes})},Ri=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"getOrganization",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>{const i=await n.getOrganization({});return i.data?{...i.data.attributes,id:i.data.id}:void 0}})},Vi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"getOrganizationAdvertising",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>(await n.getOrganizationAdvertising({})).data?.attributes})},$i=(t,e,n)=>{t.transport=new $n(e.host,{dedupeTime:1e3*60*5,refetchInterval:1e3*60*5,retryable:!0}),t.analyticsTransport=new $n(e.analyticsHost),t.sdk.host=t.transport.host,t.transport.setSdkKey(e.sdkKey),t.transport.setHeader("sl-sdk-version",e.version||"-"),t.transport.$headers.subscribe(r=>{t.analyticsTransport.$headers.getStore().set(r)}),t.sdk.onMount({name:"transport"},()=>()=>{t.transport.disconnect(),t.analyticsTransport.disconnect()}),n()};var fe;(function(t){t.SCHEMA="schema",t.EXTERNAL_TOKEN="eToken",t.TOKEN="token"})(fe||(fe={}));class $e extends Ke{constructor(){super("user")}setSchema=e=>{this.write(fe.SCHEMA,e)};getSchema=()=>this.read(fe.SCHEMA);setToken=e=>{this.write(fe.TOKEN,e)};getToken=()=>this.read(fe.TOKEN);setExternalToken=e=>{this.write(fe.EXTERNAL_TOKEN,e)};getExternalToken=()=>this.read(fe.EXTERNAL_TOKEN);removeToken=()=>{this.remove(fe.TOKEN)}}var he;(function(t){t.DISABLED="disabled",t.INITIALIZATION="initialization",t.READY="ready",t.FAILED="failed",t.SUSPENDED="suspended"})(he||(he={}));const Bi=t=>{const e=new $e,n=new J(Q(e.getExternalToken()),"userKey"),r=new J(Q(e.getToken()),"userToken"),i=new te(Ni(r.getStore(),t),"user",({data:s,error:a,loading:u},d)=>{if(!a)return s?.data?.id?s.data.id:u===!1?void 0:d}),o=new te(Di(r.getStore(),t),"userSettings");return{userKey:n,userToken:r,user:i,userSettings:o}},Mi=t=>{const e=new J(Q(void 0),"providerStreamId"),n=new te(Ci(e.getStore(),t),"slStreamId",o=>o?.data),r=new te(Pi(n.getAtomStore(),t),"streamSettings"),i=new te(Li(n.getAtomStore(),t),"streamSettings");return n.getAtomStore().listen(o=>{(o===""||o===void 0)&&(r.getStore().mutate(void 0),i.getStore().mutate(void 0))}),{providerStreamId:e,slStreamId:n,streamSettings:r,streamSummary:i}},qi=t=>{const e=new J(Q(void 0),"enabled"),n=new J(Q(he.DISABLED),"status"),r=new te(Ri(e.getStore(),t),"organizationSettings",a=>a?.data?.id),i=new te(Vi(r.getAtomStore(),t),"organizationAdvertising"),o=Bi(t),s=Mi(t);return{enabled:e,status:n,providerStreamId:s.providerStreamId,slStreamId:s.slStreamId,streamSettings:s.streamSettings,streamSummary:s.streamSummary,user:o.user,userKey:o.userKey,userToken:o.userToken,userSettings:o.userSettings,organizationSettings:r,organizationAdvertising:i}};class Ui extends Ot{stores;constructor(e){const n=qi(e),r=Si(n);super(r,"core"),this.stores=n}getValue(){throw new Error("Not implemented")}getValues(){return this.stores}setValue(){throw new Error("Not implemented")}subscribe=e=>{let n;for(n in this.stores){const r=e[n];n in e&&r!==void 0&&this.stores[n].subscribe(e[n])}};unsubscribe=()=>this.getStore().off()}const Qi=(t,e,n)=>{t.store=new Ui(t.transport),t.stores=t.store.getValues(),t.sdk.enabled=t.stores.enabled.getStore(),t.sdk.status=t.stores.status.getStore(),t.sdk.sdkStore=Object.fromEntries(Object.entries(t.stores).map(([r,i])=>[r,i.getStore()])),t.sdk.organizationStore=()=>t.stores.organizationSettings.getStore(),t.sdk.streamStore=()=>t.stores.streamSettings.getStore(),t.sdk.streamSummary=()=>t.stores.streamSummary.getStore(),t.storeUnsubscribe=()=>{t.store.unsubscribe()},n()},ji=t=>{const{client:e}=t.createPromiseClient(gr.Leaderboard,{method:"list"});return n=>e.list(n)},Ar=t=>{const{client:e}=t.createPromiseClient(gr.Leaderboard,{method:"summary"});return n=>e.summary(n)},xi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(gn.Users,{method:"getFriends",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s)return[];try{return(await n.getFriends({})).data}catch{return[]}}})},Gi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(W.Feed,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>(await n.get({eventId:s})).data?.attributes,refetchInterval:0,dedupeTime:1e3*60*60})},Ki=(t,e,n)=>{const{client:r,queryKey:i}=n.createPromiseClient(W.Feed,{method:"syncQuestion",params:[t,e?"true":""]});return n.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>{if(!a||u)return;const d=await r.syncQuestion({filter:{eventId:a}});if(d.data?.attributes?.question?.type!==S.QuestionType.PROMOTION)return d.data?.attributes},dedupeTime:1e3*60*10,refetchInterval:0})},zi=async(t,e)=>{const{client:n}=e.createPromiseClient(W.Feed,{method:"item",params:[t]});return(await n.item({id:t})).data},Hi=(t,e)=>{const{client:n}=e.createStreamClient(W.Feed),r=ne.atom({eventId:t.get()||"",feedId:""});return t.subscribe((o="")=>{r.set({eventId:o,feedId:""})}),e.addSubscription(n.subscription,r,{name:"feedSubscription"})},Wi=(t,e)=>{const{client:n}=e.createStreamClient(W.Feed);return e.addSubscription(n.questionSubscription,{questionId:t},{name:"questionSubscription"})},rn=async(t,e)=>{const{client:n}=e.createPromiseClient(W.Feed,{method:"questionByUser",params:[t]});return(await n.questionByUser({questionId:t})).data?.attributes?.question},qe=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(W.Feed,{method:"questionByUser",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>(await n.questionByUser({questionId:s})).data?.attributes?.question,dedupeTime:1e3*60*5})},Ir=async(t,e)=>{if(!t)return;const{client:n}=e.createPromiseClient(W.Feed,{method:"getQuestion",params:[t]}),r=await n.getQuestion({id:t});if(!r.data?.attributes)return;const{options:i,notification:o,...s}=r.data.attributes,a=i?.options.case==="promotion"?i?.options.value:void 0;return{id:s.id,question:s,promotion:a,notification:o}},Yi=(t,e,n,r)=>{const{client:i,queryKey:o}=r.createPromiseClient(W.Feed,{method:"list",params:[t,e,n?"true":""]});return r.nanoquery.createFetcherStore(o,{fetcher:async(s,a,u,d,c)=>!u||c?[]:(await i.list({eventId:u,filter:{types:d===Se.ALLOWED?[]:[S.QuestionType.FACTOID,S.QuestionType.PROMOTION,S.QuestionType.TWEET],statuses:[S.QuestionStatus.ACTIVE,S.QuestionStatus.RESOLVED]}})).data,dedupeTime:0,refetchInterval:0})},Ji=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(W.Feed,{method:"list",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s)return;const u=(await n.list({eventId:s,filter:{types:[S.QuestionType.PROMOTION],statuses:[S.QuestionStatus.ACTIVE]},pagination:{page:0,pageSize:1}})).data?.[0];if(u.type==="promotion")return Ir(u.id,e)},dedupeTime:0,refetchInterval:0})},Xi=(t,e,n,r,i)=>{const{client:o,queryKey:s}=i.createPromiseClient(W.Feed,{method:"betPack",params:[t,e,n]});return i.nanoquery.createFetcherStore(s,{fetcher:async(a,u,d,c,f)=>{if(!d||!c||!f)return{timestamp:Date.now(),data:null};const p=await o.betPack({eventId:d,types:[S.QuestionType.PREDICTION],statuses:[S.QuestionStatus.ACTIVE,S.QuestionStatus.RESOLVED],limit:5,sort:{field:"activated_at",order:"asc"}});return!p.data||!p.data.length?{timestamp:Date.now(),data:null}:{timestamp:Date.now(),data:p.data?.reduce((w,E)=>{const g=E?.attributes?.question;if(!g?.id)return w;const m={eventId:d,userId:c,organizationId:f};return r.isBetPackQuestionReceived(m,g.id)||(q.emit("poll",{action:"received",payload:{questionId:g.id,questionType:g.type}}),r.saveBetPackQuestionReceived(m,g.id)),{...w,[g.id]:g}},{})}},dedupeTime:0,refetchInterval:0})},Zi=(t,e,n)=>{const r=ne.batched([e,n],()=>{const a=e.get();if(!a)return;const u=n.get().data?.find(c=>c.id===a?.questionId),d=a?.question?.openedFrom;return u?(u.openedFrom=d,u):a.question}),i=ne.batched(r,a=>a&&a.type==="question"?a.id:void 0),o=qe(i,t);return{$store:r,$extendedStore:o,updateExtendedQuestion:a=>{const u=o.get().data,d=(c,f)=>{if(!c||!f)return c||f||[];const p=[];for(let w=0;w<c.length;w++)p.push({...c[w],...f[w],correct:c[w].correct,youVoted:c[w].youVoted,pointsEarned:c[w].pointsEarned});return p};o.mutate({...a,options:u?.options,subject:u?.subject,appearance:u?.appearance,answers:d(u?.answers,a?.answers)})}}};var mt;(function(t){t.SHOWED="showed"})(mt||(mt={}));class eo extends Ke{constructor(){super("advertisement")}setShowed=e=>{this.write(mt.SHOWED,e,"true")};isViewed=e=>this.read(mt.SHOWED,e)}const to=t=>{const e=t.data?.attributes?.question;if((t.data?.attributes?.feedItem?.type==="promotion"?t.data.attributes.feedItem:void 0)===void 0||!e)return;const{options:r,notification:i,...o}=e,s=r?.options.case==="promotion"?r.options.value:void 0;return{id:o.id,question:o,notification:i,promotion:s}},at=t=>t.startsWith("http://")||t.startsWith("https://")?new URL(t).toString():t,no=({gamOptions:t,gamBaseUrl:e})=>{const n=`${e}?`,r=[];for(const i in t){const o=i.replace(/([a-zA-Z])(?=[A-Z])/g,"$1_").toLowerCase(),s=t[i];if(s)if(typeof s=="string")r.push(`${o}=${at(s)}`);else if(Array.isArray(s))r.push(`${o}=${s.map(at).join(",")}`);else{const a=Object.entries(s).map(([u,d])=>Array.isArray(d)?`${u}=${d.map(at).join(",")}`:typeof d=="string"?`${u}=${at(d)}`:`${u}=${d}`).join("&").replaceAll("=","%3D").replaceAll("&","%26").replaceAll(",","%2C");r.push(`${o}=${a}`)}}return n+r.join("&")},Fe=t=>(t?.promotion?.type===S.PromotionType.INGAME_IAB11_LBAR||t?.promotion?.type===S.PromotionType.INGAME_IAB21_LBAR)&&!!t.promotion.additionalBanner?.imageUrl,ro=(t,e,n)=>{let r=!1;const i=n.transport,o=ce("advertisement"),s=new eo,a=H({}),u=Ji(t,i),d=g=>{const m=a.get(),T=m.data?.question.id,D=m.data?.promotion?.type;T&&(q.emit("advertisement",{action:"opened",payload:{id:T,type:D,hasBanner:Fe(m.data),openedFrom:g?.fromNotification?"notification":"auto"}}),g?.fromNotification&&(a.setKey("hasNotification",!1),q.emit("advertisement",{action:"notification-opened",payload:{id:T,type:D,hasBanner:Fe(m.data)}})))},c=()=>{const g=a.get(),m=g.data?.question.id,T=g.data?.promotion?.type,D=a.get()?.isOpened;m&&!D&&(o.debug({id:m},"markAsViewed: %o"),s.setShowed(m),a.setKey("isOpened",!0),q.emit("advertisement",{action:"viewed",payload:{id:m,type:T,hasBanner:Fe(g.data)}}))},f=(g,m)=>{m?a.set({loading:!1,error:void 0,data:m,hasNotification:m?.notification?.enabled===S.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>p(m.question.id),togglePause:T=>w(m.question.id,T),isViewed:!!s.isViewed(m.question.id)}):(a.setKey("loading",!0),Ir(g,i).then(T=>a.set({loading:!1,error:void 0,data:T,hasNotification:T?.notification?.enabled===S.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>p(T?.question.id),togglePause:D=>w(T?.question.id,D),isViewed:T&&!!s.isViewed(T.question.id)})).catch(T=>a.set({loading:!1,error:T,data:void 0})))};a.subscribe((g,m)=>{if(!(g.data?.id===m?.data?.id&&g.isPaused!==m?.isPaused)){if(g.data?.promotion?.type===S.PromotionType.EXTERNAL_AD&&!g?.externalAd&&g.data.promotion.adCampaigns?.gamOptions&&g.data.promotion.adCampaigns?.gamBaseUrl){const T=no(g.data.promotion.adCampaigns);a.setKey("externalAd",{type:"gam",url:T})}g.data?.promotion&&!g.isOpened&&(q.emit("advertisement",{action:"received",payload:{id:g.data.question.id,type:g.data.promotion.type,hasNotification:!!g.hasNotification,hasBanner:Fe(g.data),isViewed:!!s.isViewed(g.data.question.id)},skipAnalytics:g.data.question.id===m?.data?.question.id}),g.data.question.id!==m?.data?.question.id&&!s.isViewed(g.data.question.id)&&q.emit("advertisement",{action:"notification-received",payload:{id:g.data.question.id,type:g.data.promotion.type,hasNotification:!0,hasBanner:Fe(g.data),isViewed:!1}})),!g?.data&&m?.data&&q.emit("advertisement",{action:"closed",payload:{id:m.data.question.id,type:m.data.promotion?.type,hasNotification:!!m.hasNotification,hasBanner:Fe(m.data),isViewed:!!s.isViewed(m.data.question.id)}})}});const p=g=>{(!g||a.get()?.data?.question.id===g)&&a.set({})},w=(g,m)=>{a.get()?.data?.question.id===g&&a.setKey("isPaused",m)};return{connect:()=>{r||(r=!0,u.subscribe((g,m)=>{g.data&&(!m?.data||g.data.id!==m.data.id)&&f(g.data.question.id,g.data)}),e.addListener("promotion",g=>{const m=to(g);if(m){if(m.question.status===S.QuestionStatus.RESOLVED){p(m.question.id),o.debug({promotion:m},"resolved: %o");return}if(m.question.status===S.QuestionStatus.ACTIVE){o.debug({promotion:m},"active: %o"),f(m.question.id,m);return}o.debug({promotion:m},"skip: %o")}}))},hide:p,show:f,open:d,markAsViewed:c,$store:a}};var oe;(function(t){t.ONBOARDING="onboarding",t.ONBOARDING_IO="onboarding_io",t.BET_PACK_ITEM_RECEIVED="bp-item-received",t.QUESTION_OPENED="q-opened"})(oe||(oe={}));class io extends Ke{constructor(){super("gamification-session",window.sessionStorage)}writeValue=(e,n)=>{this.write(...e,n)};readValue=e=>this.read(...e)}class oo extends Ke{sessionStorage;constructor(){super("gamification"),this.sessionStorage=new io}saveBetPackQuestionReceived=({userId:e,eventId:n,organizationId:r},i)=>{this.write(oe.BET_PACK_ITEM_RECEIVED,r,e,n,i)};isBetPackQuestionReceived=({userId:e,eventId:n,organizationId:r},i)=>!!this.read(oe.BET_PACK_ITEM_RECEIVED,r,e,n,i);saveQuestionOpened=({userId:e,eventId:n,organizationId:r},i)=>{this.write(oe.QUESTION_OPENED,r,e,n,i,"1")};isQuestionOpened=({userId:e,eventId:n,organizationId:r},i)=>!!this.read(oe.QUESTION_OPENED,r,e,n,i);saveOnboardingStatus=({userId:e,eventId:n,organizationId:r},i)=>{this.write(oe.ONBOARDING,r,e,n,i)};getOnboardingStatus=({userId:e,eventId:n,organizationId:r})=>this.read(oe.ONBOARDING,r,e,n);setOnboardingInstantOpen=({userId:e,eventId:n,organizationId:r})=>{this.sessionStorage.writeValue([oe.ONBOARDING_IO,r,e,n],"1")};getOnboardingInstantOpen=({userId:e,eventId:n,organizationId:r})=>this.sessionStorage.readValue([oe.ONBOARDING_IO,r,e,n])}var Se;(function(t){t.ALLOWED="allowed",t.DISALLOWED="disallowed"})(Se||(Se={}));class so{slStreamId;organizationId;userId;interactiveAllowed;openedQuestionId;openedQuestion;activeQuestionId;feedList;betPack;moderationId;moderation;feedSubscription;questionSubscription;advertisement;storage;notifications;log;transport;cancels=new Set;constructor(e){this.transport=e.transport,this.log=ce("gamification-background"),this.storage=new oo,this.slStreamId=e.stores.slStreamId.getAtomStore(),this.organizationId=e.stores.organizationSettings.getAtomStore(),this.userId=e.stores.user.getAtomStore(),this.moderationId=new J(Q(void 0),"moderationId").getStore(),this.interactiveAllowed=new J(Q(Se.DISALLOWED),"interactiveAllowed").getStore(),this.openedQuestionId=new J(Q(void 0),"openedQuestionId").getStore(),this.notifications=e.notifications,this.moderation=new te(Gi(this.slStreamId,e.transport),"gamification:moderation");const n=!!e.sdk.options.get().betPack;this.feedList=new te(Yi(this.slStreamId,this.interactiveAllowed,n,e.transport),"gamification:feedList"),this.betPack=new te(Xi(this.slStreamId,this.userId,this.organizationId,this.storage,e.transport),"gamification:betPack"),this.activeQuestionId=Ki(this.slStreamId,n,e.transport),this.openedQuestion=Zi(e.transport,this.openedQuestionId,this.feedList.getStore()),this.cancels.add(this.openedQuestionId.listen(r=>{this.log.debug({item:r},"received question"),r?.questionId?(this.questionSubscription=Wi(r.questionId,e.transport),this.questionSubscription.addListener("feed-subscription-opened-question",async i=>{const o=i.data?.attributes?.question;if(this.openedQuestion.updateExtendedQuestion(o),o?.type===S.QuestionType.PREDICTION&&(o.status===S.QuestionStatus.ACTIVE||o.status===S.QuestionStatus.RESOLVED)){const s=this.betPack.getValues().data?.data||{};if(s?.[o.id]||Object.keys(s).length<5){const u=qe(o.id,this.transport),d=u.subscribe(()=>{});await u.get().promise;let c=u.get().data;c||(c=await rn(o.id,this.transport)),d(),window.requestAnimationFrame(()=>{u.invalidate()}),this.betPack.getStore().mutate({timestamp:Date.now(),data:{...s,[o.id]:c}})}}}),this.questionSubscription.connect()):(this.log.info("cleanup on close question"),this.questionSubscription!==void 0&&(e.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0))})),this.feedSubscription=Hi(this.slStreamId,e.transport),this.cancels.add(this.feedSubscription.addListener("bet-pack-update",async r=>{const i=r.data?.attributes?.question;if(i?.type===S.QuestionType.PREDICTION&&(i.status===S.QuestionStatus.ACTIVE||i.status===S.QuestionStatus.RESOLVED)){const o=this.betPack.getValues().data?.data||{};if(o?.[i.id]||Object.keys(o).length<5){const a=qe(i.id,this.transport),u=a.subscribe(()=>{});await a.get().promise;let d=a.get().data;d||(d=await rn(i.id,this.transport)),u(),window.requestAnimationFrame(()=>{a.invalidate()}),this.betPack.getStore().mutate({timestamp:Date.now(),data:{...o,[i.id]:d}})}}})),this.cancels.add(this.feedSubscription.addListener("feed-subscription-active-question",r=>{const i=this.activeQuestionId.get().data?.question?.id,o=r.data?.attributes?.question;if(!(!o||o.type===S.QuestionType.PROMOTION)){if(o.status===S.QuestionStatus.RESOLVED){i===o.id&&this.activeQuestionId.mutate(void 0);return}window.requestAnimationFrame(()=>{this.activeQuestionId.mutate(r.data?.attributes)})}})),this.cancels.add(this.feedSubscription.addListener("moderation update",r=>{window.requestAnimationFrame(()=>{r.data?.attributes?.question===void 0&&r.data?.attributes?.moderation&&this.moderation.invalidate()})})),this.cancels.add(this.activeQuestionId.subscribe((r,i)=>{r.data?.feedItem&&r.data?.feedItem?.id!==i?.data?.feedItem?.id&&e.onQuestionActivate({stage:"activate",id:r.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:r.data.feedItem.id})),hasNotification:!0,type:r.data.feedItem.type}),!r.data?.feedItem&&i?.data?.feedItem&&e.onQuestionActivate({stage:"deactivate",id:i.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:i.data.feedItem.id})),hasNotification:!0,type:i.data.feedItem.type})})),this.feedSubscription.connect(),this.cancels.add(this.interactiveAllowed.listen(()=>{window.requestAnimationFrame(()=>{this.activeQuestionId.invalidate()})})),e.sdk.onMount({name:"gamification-background"},()=>()=>{this.activeQuestionId.off();for(const r of this.cancels)r(),this.cancels.delete(r)}),n||(this.advertisement=ro(this.slStreamId,this.feedSubscription,e))}getCurrentSessionId=e=>{const n=e.eventId||this.slStreamId.get()||"",r=e.userId||this.userId.get()||"",i=e.organizationId||this.organizationId.get()||"",o=e.entity||"",s=e.prefix||"";return[i,n,r,s,o].join(":")};disconnect=()=>{this.feedSubscription?.disconnect(),this.questionSubscription!==void 0&&(this.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0)};openQuestion=(e,n)=>{this.openedQuestionId.set({questionId:e,question:n}),this.notifications.markAsViewed(this.getCurrentSessionId({prefix:"notification",entity:e}))};closeQuestion=e=>{this.openedQuestionId.set(void 0),e&&this.notifications.markAsViewed(this.getCurrentSessionId({prefix:"notification",entity:e}))}}class ao{notificationsList;store;timeouts;waitingQueue;activeQueue;options;logger;constructor(e){this.options=e,this.logger=ce("notifications"),this.store=new Map,this.timeouts=new Map,this.waitingQueue=new Set,this.activeQueue=new Set,this.notificationsList=Q(new Map)}addToQueue=e=>{if(this.store.has(e.id)){this.logger.debug({notification:e},"skip existed notification: %o");return}const n=e.close,r=e.action;if(this.store.set(e.id,{...e,close:(...i)=>{n&&n(...i),this.closeNotification(e.id)},action:(...i)=>{r&&r(...i),this.closeNotification(e.id,{animateHiding:!1})}}),this.waitingQueue.add(e.id),this.activeQueue.size===this.options.concurrency){const[i]=this.activeQueue;if(this.store.get(i)?.persistent!==!0)this.closeNotification(i);else{const[s]=this.waitingQueue;this.waitingQueue.size>1&&this.closeNotification(s),this.tickWaitingQueue()}}else this.tickWaitingQueue()};tickWaitingQueue=()=>{if(this.activeQueue.size<this.options.concurrency){const[e]=this.waitingQueue;if(!e)return;this.activeQueue.add(e),this.waitingQueue.delete(e),this.logger.debug({job:e},"waiting queue tick"),this.tickActiveQueue(e)}else this.logger.debug({queueSize:this.activeQueue.size,concurrency:this.options.concurrency},"waiting queue tick skipped")};tickActiveQueue=e=>{if(!e)return;const n=this.store.get(e);if(!n){this.logger.debug({notificationId:e},"active queue tick skipped, notification not exist");return}q.emit("notification",{action:"received",payload:{type:n.type,questionId:n.data.questionId,questionType:n.data.questionType}});const r=setTimeout(()=>{const i=e,o=new Map(this.notificationsList.get());o.set(n.id,n),this.notificationsList.set(o);const s=setTimeout(()=>{this.logger.debug({notificationId:i,delay:n.autoHideDuration||5e3},"notification hiding by autoHideDuration"),this.closeNotification(i)},n.autoHideDuration||5e3);this.timeouts.set(i,s),this.logger.debug({notificationId:i,queue:[...o.values()]},"notification displayed")},n.delay||0);this.timeouts.set(e,r),this.logger.debug({notificationId:e},"active queue tick completed"),this.tickWaitingQueue()};closeNotification=(e,{animateHiding:n=!0}={})=>{const r=new Map(this.notificationsList.get()),i=r.get(e);if(i){i.hiding=!(this.waitingQueue.size>=this.options.concurrency)&&n,this.notificationsList.set(r);const o=setTimeout(()=>{const s=new Map(this.notificationsList.get());s.delete(e),this.notificationsList.set(s);const a=this.timeouts.get(e);a!==void 0&&(clearTimeout(a),this.timeouts.delete(e)),this.logger.debug({notificationId:e},"notification hidden"),i.hiding&&q.emit("notification",{action:"closed",payload:{type:i.type,questionId:i.data.questionId,questionType:i.data.questionType}})},this.options.animationDelay||0);this.timeouts.set(e,o)}return this.store.delete(e),this.activeQueue.delete(e),this.waitingQueue.delete(e),this.tickWaitingQueue(),this.logger.debug({notificationId:e},"notification hiding"),i};drain=()=>{this.store.clear(),this.timeouts.clear(),this.waitingQueue.clear(),this.activeQueue.clear(),this.notificationsList.off(),this.notificationsList.set(new Map)}}var bt;(function(t){t.OPENED="opened"})(bt||(bt={}));class uo extends Ke{constructor(){super("notification")}setOpened=e=>{this.write(bt.OPENED,e,"true")};isOpened=e=>this.read(bt.OPENED,e);clearNotification=()=>{this.clear()}}class co{queue;storage;constructor(e={}){this.storage=new uo,this.queue=new ao({concurrency:1,animationDelay:1600,...e})}isViewed=e=>this.storage.isOpened(e);add=e=>{if(!this.isViewed(e.id)){if(e.data&&e.emitEvent){const r=e.action;e.action=(...i)=>{r&&r(...i),q.emit("notification",{action:"opened",payload:{questionId:e.data.questionId,questionType:e.data.questionType}})}}this.queue.addToQueue(e)}};close=(e,{markAsViewed:n=!0,animateHiding:r}={})=>{this.queue.closeNotification(e,{animateHiding:r}),n&&this.markAsViewed(e)};getActiveNotification=()=>{const e=this.queue.notificationsList.get();if(!e?.size)return null;for(const r of e.values())if(r.type===me.ONBOARDING)return r;return e.values().next().value};getQueueStore=()=>this.queue.notificationsList;markAsViewed=e=>{this.storage.setOpened(e)}}const lo=(t,e,n)=>{t.notifications=new co(void 0),t.addNotification=t.notifications.add,t.sdk.getNotificationsStore=()=>t.notifications.getQueueStore(),t.sdk.getActiveNotification=()=>t.notifications.getActiveNotification(),t.sdk.onMount({name:"notifications"},()=>()=>{t.notifications.queue.drain()}),n()};var je;(function(t){t.UNKNOWN="unknown",t.ALREADY_VOTED="already_voted"})(je||(je={}));const Bn=async(t,e)=>{const{client:n,createRequestOptions:r}=t.createPromiseClient(W.Feed,{method:"submitAnswer"}),i=r({retryAttempts:0});try{return await n.submitAnswer({data:e},{contextValues:i})}catch(o){throw M.ConnectError.from(o)?.code===M.Code.AlreadyExists?new Error(je.ALREADY_VOTED):new Error(je.UNKNOWN)}},Or=(t,e)=>{const{client:n,createRequestOptions:r}=t.createPromiseClient(W.Feed,{method:"submitInplay"}),i=r({retryAttempts:0});return n.submitInplay({data:{eventId:+e}},{contextValues:i})},fo={pageSize:10},po=(t,e,n,r,i)=>{let o=0;const s=Q({pageSize:fo.pageSize,page:0}),a=H({data:[],key:Date.now(),hasMore:!0,loading:void 0,error:void 0}),u=ji(t),d=async()=>{const p=e.get(),w=r?.getStore().get().data?.map(E=>E.slId)||[];if(p&&w?.length){const E=n.get();E&&w.push(E),a.setKey("loading",!0),a.setKey("data",[]);const m=await u({eventId:p,usersIds:w});a.set({data:m.data.map((T,D)=>({...T.attributes,friendsRank:D+1})),hasMore:!1,key:Date.now(),loading:!1}),m.meta&&(o=Math.round(m.meta.count/m.meta.pageSize))}},c=()=>{d()},f=p=>{const w=s.get(),E=p||w.page+1;E<=o&&s.set({...w,page:E})};return ne.onMount(a,()=>{const p=e.listen(d),w=r?.listen(d);return()=>{p(),w?.()}}),{$store:a,fetchMore:f,invalidate:c}};class ho extends Ke{get=this.read;set=this.write;del=this.remove;constructor(){super("deep-link-context",window.sessionStorage)}}const Mn="sldl",kt="sldl_uid",kr="sldl_eid",_r="sldl_e_eid",yo=new Set([kt,kr,_r]),qn=t=>{const e={},n={};for(const[r,i]of t)yo.has(r)?e[r]=i:n[r]=i;return{result:e,remain:n}},go=({hash:t,search:e})=>{if(t&&t.includes(Mn)){const n=new URLSearchParams(t.substr(1));return{hash:qn(n)}}if(e&&e.includes(Mn)){const n=new URLSearchParams(e);return{search:qn(n)}}return null},Un=ce("deep_link"),ue={debug:(...t)=>{Un.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Un.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},mo=(t,e)=>{const{hash:n,search:r}=window.location;if(ue.debug({hash:n,search:r},"get deep link data from"),n||r){const i=go({hash:n,search:r});if(ue.debug(i,"parse deep link result"),i){const{hash:o,search:s}=i,{result:a,remain:u}=o||s;if(Object.keys(a).length!==0){t.setValue("data",a);const d=Object.keys(u).length!==0;if(o){let c="";d&&(c=`#${new URLSearchParams(u).toString()}`,ue.debug({updatedHash:c},"update hash")),window.history.replaceState(null,"",window.location.pathname+window.location.search+c)}if(s){let c="";d&&(c=`?${new URLSearchParams(u).toString()}`,ue.debug({updatedSearch:c},"update search")),window.history.replaceState(null,"",window.location.pathname+c+window.location.hash)}e(a)}}}t.setValue("parsed",!0)},bo=(t,e,n)=>{const r=new ho,i=r.get("sl-deep-link-store");let o={};if(i)try{o=JSON.parse(i)}catch(a){ue.debug(a)}t.deepLink={$store:new Ie(H(o),"deep-link-context"),getDeepLinkData:()=>{const{data:a,used:u}=t.deepLink.$store.getValues();return{data:a,used:u}},deepLinkUsed:a=>{ue.debug(`logged in with inviterId: ${a}`),t.deepLink.$store.setValue("used",!0)},onDeepLinkHandlers:new Set},t.sdk.getInviter=()=>{const{data:a,used:u}=t.deepLink.getDeepLinkData();return u?a?.[kt]:void 0},t.sdk.inviteDisplayed=()=>{t.deepLink.$store.getStore().set({}),t.deepLink.$store.getStore().off(),r.del("sl-deep-link-store")},t.deepLink.$store.subscribe(a=>r.set("sl-deep-link-store",JSON.stringify(a))),t.sdk.addDeepLinkHandler=a=>{localStorage.getItem("SL_DEBUG")&&ue.trace("adding deep link handler"),t.deepLink.onDeepLinkHandlers.add(a)},e.onDeepLinkHandled&&t.sdk.addDeepLinkHandler(e.onDeepLinkHandled),t.sdk.removeDeepLinkHandler=a=>{ue.trace("removing deep link handler"),t.deepLink.onDeepLinkHandlers.delete(a)};const s=a=>{t.deepLink.$store.setValue("handled",!0),ue.trace({size:t.deepLink.onDeepLinkHandlers.size},"deep link handled, call callbacks");for(const u of t.deepLink.onDeepLinkHandlers)try{ue.trace("called handler"),u(a)}catch(d){console.error(d)}};mo(t.deepLink.$store,s),n()},vo=ce("bypass");class So extends vi{$coreStore;deepLink;transport;bypassLogin;constructor(e,n,r){super(),this.$coreStore=e,this.deepLink=r,this.transport=n,this.bypassLogin=Fi(this.transport),this.connect()}me=async()=>(this.$coreStore.getValues().user.invalidate(),(await this.$coreStore.getValues().user.getValue())?.data);login=async(e,n)=>{this.$coreStore.getValues().userKey.setValue(n);const{used:r,data:i}=this.deepLink.getDeepLinkData(),o=r?"":i?.[kt];vo.debug({inviterKey:o},"login with inviterKey");const s=await this.bypassLogin({schema:e,userKey:n,inviterKey:o,init:!1}),a=s.meta?.jwt,u=s.data?.id;if(!a||!u)throw new Error("internal: token missing");return s.meta?.inviterKey&&this.deepLink.deepLinkUsed(s.meta.inviterKey),this.$coreStore.getValues().user.getStore().mutate({data:s.data}),this.saveUser(a,u),a};isAuthenticated=()=>this.me();logout=()=>{this.$coreStore.getValues().user.setValue(),this.$coreStore.getValues().userKey.setValue(),this.$coreStore.getValues().userToken.setValue(),this.transport.setAuth("",""),new $e().clear()};softLogout=()=>{const e=new $e;this.transport.setAuth("",""),e.setToken(""),this.reLogin()};reLogin=({skipLogin:e}={skipLogin:!1})=>{const n=new $e,r=n.getToken(),i=n.getExternalToken();if(this.$coreStore.getValues().userKey.setValue(i),r)return this.saveUser(r,""),this.me().then(o=>{if(o?.id){const s=o.id;this.saveUser(r,s)}return o});if(i&&!r&&!e){const o=n.getSchema();o&&i&&this.login(o,i).catch(()=>{this.logout()})}};saveUser=(e,n)=>{this.transport.setAuth(e,n),this.$coreStore.getValues().userToken.setValue(e),new $e().setToken(e)};connect=()=>{this.transport.registerInterceptor(e=>async n=>{try{return await e(n)}catch(r){throw r.code&&(r.code===7||r.code===16)&&this.transport.getHeader("authorization")&&this.softLogout(),r}})}}const We=new $e,wo=(t,e,n)=>{t.auth=new So(t.store,t.transport,t.deepLink),t.stores.status.listen(r=>{r===he.READY&&t.auth.reLogin()}),t.sdk.userId=t.stores.user.getAtomStore,t.sdk.authorizationBypass=async(r,i)=>{if(!(We.getSchema()===r&&We.getExternalToken()===i&&t.transport.getHeader("authorization")))try{await t.auth.login(r,i),We.setSchema(r),We.setExternalToken(i)}catch{t.sdk.logout()}},t.sdk.logout=()=>{t.auth.logout(),We.clear()},t.sdk.getUserStore=()=>t.stores.user.getStore(),t.sdk.isUserAuthorized=()=>t.auth.isAuthenticated(),n()},Qn=ce("video_player"),ut={debug:(...t)=>{Qn.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Qn.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},To=(t,e,n)=>{t.videoPlayer={controllers:new Set},t.sdk.addVideoPlayerController=r=>{ut.trace("adding video player controller"),t.videoPlayer.controllers.add(r)},e.videoPlayerController&&t.sdk.addVideoPlayerController(e.videoPlayerController),t.sdk.removeVideoPlayerController=r=>{ut.trace("removing video player controller"),t.videoPlayer.controllers.delete(r)},t.sdk.controlVideoPlayer=r=>{ut.trace("controlling video player");for(const i of t.videoPlayer.controllers){ut.trace("calling video player controller");try{i(r)}catch(o){console.error(o)}}},n()},Eo={[S.QuestionType.FACTOID]:"insight",[S.QuestionType.POLL]:"poll",[S.QuestionType.TRIVIA]:"trivia",[S.QuestionType.PREDICTION]:"prediction",[S.QuestionType.TWEET]:"tweet"},Ao=(t,e,n)=>{t.sdk.uiState=H({}),t.ui={enableAppNotification:function(){t.sdk.uiState.setKey("appNotification",!0)},disableAppNotification:function(){t.sdk.uiState.get().app||t.sdk.uiState.setKey("appNotification",!1)},enableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!0)},disableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!1)},enableApp:function(){t.sdk.uiState.set({app:!0,appNotification:!0})},disableApp:function(){t.sdk.uiState.set({...t.sdk.uiState.get(),onboardingNotification:!1,appNotification:!1,app:!1})}},e.onContentActivate&&(t.ui.onContentActivate=e.onContentActivate);const r=i=>{t.ui.onContentActivate&&t.ui.onContentActivate({...i,type:"advertisement"})};t.onQuestionActivate=({questionType:i,...o})=>{if(t.ui.onContentActivate){const s=o.type||i&&Eo[i]||"question";t.ui.enableAppNotification(),t.ui.onContentActivate({...o,type:s})}},t.sdk.onMount({name:"ui"},()=>{const i=a=>{if(a.slEventBus?.type==="app")switch(a.slEventBus.action){case"open":t.ui.enableApp();break;case"close":t.ui.disableApp();break}if(a.slEventBus?.type==="notification"){const u=a.slEventBus.action;if(a.slEventBus.payload.type===me.ONBOARDING)switch(u){case"received":t.ui.enableOnboardingNotification();break;case"closed":t.ui.disableOnboardingNotification();break}else switch(u){case"received":t.ui.enableAppNotification();break;case"closed":t.ui.disableAppNotification();break}}if(a.slEventBus?.type==="advertisement"&&e.withAd){const u=a.slEventBus,{hasNotification:d,hasBanner:c,id:f,isViewed:p,type:w}=u.payload;switch(u.action){case"notification-opened":t.sdk.uiState.set({promotionExternalAd:w===S.PromotionType.EXTERNAL_AD,promotionBanner:c,promotionNotification:!1,promotionOverlay:!0,promotionSidebar:!0});break;case"received":if(t.sdk.closeFeature(),r({stage:"activate",id:f,hasNotification:d,hasBanner:c,isViewed:p}),!e.withAdNotification){t.sdk.uiState.set({promotionBanner:c,onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionOverlay:!0,promotionSidebar:!0,promotionExternalAd:w===S.PromotionType.EXTERNAL_AD});break}d?t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionNotification:!0}):t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionBanner:c,promotionOverlay:!0,promotionSidebar:!0,promotionExternalAd:w===S.PromotionType.EXTERNAL_AD});break;case"closed":t.sdk.uiState.set({...t.sdk.uiState.get(),promotionNotification:!1,promotionBanner:!1,promotionOverlay:!1,promotionExternalAd:!1,promotionSidebar:!1}),r({stage:"deactivate",id:f,hasNotification:d,hasBanner:c,isViewed:p});break}}},o=q.listen(i),s=t.activeFeature.subscribe(a=>{a?(t.ui.enableApp(),t.sdk.uiState.set({app:!0})):t.ui.disableApp()});return()=>{o(),s()}}),n()},Io=(t,e,n)=>{const r={onMountedFired:!1},i=new Map,o=new Map;t.sdk=Object.create(null),t.sdk.options=H(e),t.sdk.withAuth=!1,t.sdk.onMount=({name:s,clear:a},u)=>{if(i.has(s)){const d=o.get(s);d&&d(),i.delete(s),o.delete(s)}i.set(s,{cb:u,clear:a}),t?.stores?.enabled?.get()==="on"&&o.set(s,u())},t.ready=()=>{t.stores.enabled.subscribe(s=>{s==="on"&&r.onMountedFired===!1&&(i.forEach(({cb:a},u)=>o.set(u,a())),r.onMountedFired=!0),s!=="on"&&r.onMountedFired===!0&&(o.forEach(a=>a()),o.clear(),i.forEach(({clear:a},u)=>a&&i.delete(u)),r.onMountedFired=!1)})},t.sdk.initializeApp=async s=>{if(t.contextConfig=s,t.stores.enabled.get()==="on")return{enabled:!0};t.storeSubscribe(),t.stores.enabled.setValue("on"),t.stores.status.setValue(he.INITIALIZATION);try{const a=await t.stores.organizationSettings.getValue();return a?(t.stores.status.setValue(he.READY),{enabled:!!a}):(t.stores.status.setValue(he.FAILED),{err:"failed"})}catch(a){return t.stores.enabled.setValue(),t.stores.status.setValue(he.FAILED),{err:`${a}`}}},t.sdk.disableApp=()=>{t.stores.enabled.get()==="on"&&(t.stores.enabled.setValue(),t.stores.status.setValue(he.DISABLED),t.stores.slStreamId.setValue(),t.stores.providerStreamId.setValue(),t.sdk.closeFeature(!0),t.storeUnsubscribe(),t.transport.disconnect())},t.sdk.createEventSession=(s,a)=>{a?t.stores.slStreamId.getStore().set({loading:!1,data:s}):t.stores.providerStreamId.setValue(s)},n()},Oo=(t,e)=>{const{client:n,queryKey:r}=t.createPromiseClient(Ze.Client,{method:"generateDeepLink",params:e});return t.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s,a)=>{if(!s)return{};try{return(await n.generateDeepLink({data:{gamification:!0,externalEventId:a,eventId:s}})).data?.attributes}catch{return}},dedupeTime:1e3*60*60*24,refetchInterval:0})},ko=(t,{web:e,mobile:n})=>{const{client:r}=t.createPromiseClient(di.LinksClient,{method:"generate"});return r.generate({web:e,mobile:n})},jn=(t,e)=>{const n=new URLSearchParams(t);for(const[r,i]of Object.entries(e))n.append(r,i);return n.toString()},_o=(t,e,n,r)=>{const i=H({});return ne.onMount(i,()=>Oo(t,[e,n]).subscribe(async({data:a,loading:u})=>{const d=a===void 0&&u===!1?"https://streamlayer.io":a?.url,c=r.get()||"",f=e.get()||"",p=n.get()||"",w={[kt]:c,[kr]:f,[_r]:p};if(!u&&d){i.setKey("loading",!0);let E=window.location.search,g=window.location.hash;E&&g||g?E=`?${jn(E,w)}`:g=`#${jn("",w)}`;const m=window.location.origin+window.location.pathname+E+g;try{const T=await ko(t,{web:m,mobile:d});i.set({data:T.data?.link,loading:!1})}catch{i.set({loading:!1,error:"Failed to generate short link",data:void 0})}}else i.setKey("loading",!0)})),{$store:i,fetch}};var B;(function(t){t.Unset="unset",t.Required="required",t.Optional="optional",t.Completed="completed",t.Disabled="disabled",t.Unavailable="unavailable"})(B||(B={}));const Co=(t,e,n,r)=>{const{inplayGame:i}=t.featureSettings.get(),o=e.getCurrentSessionId({prefix:"onboarding"});i&&n.add({type:me.ONBOARDING,id:o,action:t.openFeature,close:()=>{t.onboardingProcessed.set(!0)},persistent:!0,autoHideDuration:1e6,data:{questionId:"onboarding",questionType:S.QuestionType.UNSET,onboarding:{...i,instantOpen:!r.getOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""})}}})},ct=(t,e,n,r,i,o,s,a)=>{try{const u=e.userId.get(),d=e.organizationId.get(),c=e.slStreamId.get();if(!u||!d||!c)return;const f=i.getOnboardingStatus({userId:u,organizationId:d,eventId:c});if(f===B.Completed||a?.skipOnboarding){t.set(B.Completed);for(const m of o)m();a?.skipOnboarding&&f!==B.Completed&&(i.saveOnboardingStatus({organizationId:d,userId:u,eventId:c},B.Completed),Or(s,c));return}const p=e.moderation.getStore().value?.data,w=n.featureSettings.get().inplayGame;if(p===void 0||w===void 0)return;const E=p?.options?.onboardingEnabled,g=w?.titleCard?.optIn;E?g?t.set(B.Required):t.set(B.Optional):(g?t.set(B.Unavailable):t.set(B.Disabled),r.close(e.getCurrentSessionId({prefix:"onboarding"}),{markAsViewed:!1}))}catch(u){console.error(u)}},xn=(t,e,n,r,i)=>{let o=!!i?.skipOnboarding;const s=e.storage,a=Q(B.Unset);a.subscribe(c=>{c!==B.Unset&&(c===B.Optional||c===B.Required?o===!1&&(Co(t,e,r,s),o=!0):t.onboardingProcessed.set(!0),c===B.Completed&&e.activeQuestionId.invalidate(),s.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}))});const u=[];return a.get()!==B.Completed&&(u.push(e.userId.listen(c=>{c&&ct(a,e,t,r,s,u,n,i)})),u.push(e.moderation.listen(c=>{c.data&&ct(a,e,t,r,s,u,n,i)})),u.push(t.featureSettings.listen(c=>{c&&ct(a,e,t,r,s,u,n,i)}))),ct(a,e,t,r,s,u,n,i),{$store:a,submitInplay:async()=>{const c=e.slStreamId.get();if(c){await Or(n,c),a.set(B.Completed),s.saveOnboardingStatus({organizationId:e.organizationId.get()||"",userId:e.userId.get()||"",eventId:c},B.Completed),q.emit("poll",{action:"onboardingPassed",payload:{}}),t.openFeature();const f=e.getCurrentSessionId({prefix:"onboarding"});r.close(f)}}}},Po=(t,e,n,r)=>{const i=H(void 0),o=Ar(r),s=async()=>{const u=t.get(),d=e.get(),c=n?n.getStore().get().data?.map(w=>w.slId):[];if(!c||!u||!d)return;const f={eventId:u,userId:d,usersIds:[...c,d]},p=await o(f);i.set(p.data?.attributes)},a=()=>{s()};return ne.onMount(i,()=>{a();const u=t.listen(s),d=n?.listen(s),c=e.listen(s);return()=>{u(),d?.(),c()}}),{$store:i,invalidate:a}},Lo=async(t,e,n,r,i)=>{const o=Ar(i),s=t.get(),a=e.get(),u=n?.getStore().get().data?.map(p=>p.slId)||[],d={eventId:s,userId:r,usersIds:[...u,a]};return(await o(d)).data?.attributes?.summary},Gn=new Set([S.QuestionType.POLL,S.QuestionType.PREDICTION,S.QuestionType.TRIVIA]);class No extends Tr{userSummary;feedList;betPack;friends;leaderboardId;leaderboardList;deepLink;onboardingStatus;openedQuestion;currentUserId;openedUser;closeFeature;openFeature;feedSubscription;activeQuestionId;openedQuestionId;advertisement;onboardingProcessed;friendsTabEnabled;skipOnboarding;notifications;transport;background;storage;submitAnswerTimeout;cancels=new Set;onQuestionActivate;constructor(e,n,r){if(super(e,n),this.background=new so(r),this.advertisement=this.background.advertisement,this.onQuestionActivate=r.onQuestionActivate,this.feedSubscription=this.background.feedSubscription,this.activeQuestionId=this.background.activeQuestionId,this.openedQuestionId=this.background.openedQuestionId,this.storage=this.background.storage,this.feedList=this.background.feedList,this.betPack=this.background.betPack,this.currentUserId=this.background.userId,this.onboardingProcessed=Q(!r.sdk.withAuth),this.leaderboardId=new J(Q(this.settings.getValue("pinnedLeaderboardId")),"pinnedLeaderboardId").getStore(),this.notifications=r.notifications,this.transport=r.transport,this.closeFeature=(i=!0)=>r.sdk.closeFeature(i),this.openFeature=()=>r.sdk.openFeature(V.SdkOverlayType.GAMES),this.openedQuestion=this.background.openedQuestion,this.deepLink=_o(this.transport,this.background.slStreamId,r.stores.providerStreamId.getStore(),this.background.userId),this.userSummary=Po(this.background.slStreamId,this.background.userId,this.friends,this.transport),!r.sdk.options.get().hideFriends){this.friends=new te(xi(this.background.userId,r.transport),"gamification:friends"),this.openedUser=Q(void 0);const i=this.leaderboardList=po(this.transport,this.background.slStreamId,this.background.userId,this.friends);this.cancels.add(this.userSummary.$store.listen((o,s)=>{s?.summary&&o?.summary&&i.invalidate()}))}this.connect(),this.skipOnboarding=!!r.sdk.options.get().skipOnboarding,this.onboardingStatus=xn(this,this.background,r.transport,r.notifications,{skipOnboarding:r.sdk.options.get().skipOnboarding}),r.sdk.options.get().skipOnboarding||(this.onboardingStatus=xn(this,this.background,r.transport,r.notifications,{skipOnboarding:r.sdk.options.get().skipOnboarding})),this.cancels.add(this.onboardingStatus.$store.listen(this.checkInteractiveFlag)),this.cancels.add(this.background.moderation.getStore().listen(this.checkInteractiveFlag)),this.cancels.add(this.settings.subscribe(this.checkInteractiveFlag)),this.cancels.add(this.onboardingStatus.$store.listen((i,o)=>{(o===void 0||i!==B.Unset)&&this.background.activeQuestionId.invalidate()})),this.background.activeQuestionId.listen(this.showInApp),this.friendsTabEnabled=Q(!1),this.cancels.add(r.sdk.options.subscribe(i=>{i.friendsTab==="disabled"?this.friendsTabEnabled.set(!1):i.friendsTab==="enabled"&&this.friendsTabEnabled.set(!0)})),this.cancels.add(this.settings.subscribe(i=>{r.sdk.options.get().friendsTab==="activatedGame"&&this.friendsTabEnabled.set(!!i.inplayGame?.titleCard?.optIn)})),r.sdk.onMount({name:"gamification",clear:!0},()=>()=>{for(const i of this.cancels)i(),this.cancels.delete(i)})}get isInteractiveAllowed(){return this.background.interactiveAllowed.get()===Se.ALLOWED}checkInteractiveFlag=()=>{if(this.skipOnboarding)this.background.interactiveAllowed.set(Se.ALLOWED);else{const e=this.onboardingStatus.$store.get(),n=this.background.moderation.getStore().value?.data?.options?.onboardingEnabled,r=this.settings.getValues().inplayGame?.titleCard?.optIn,i=e===B.Completed,o=!n||i||r!==!0;this.background.interactiveAllowed.set(o?Se.ALLOWED:Se.DISALLOWED)}};connect=()=>{this.onboardingProcessed.subscribe(e=>{e&&this.advertisement&&this.advertisement.connect()}),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-prediction-close",async e=>{if(!this.isInteractiveAllowed)return;const n=e.data?.attributes?.question,r=e.data?.attributes?.feedItem;if(!n||!r?.attributes)return;const{status:i,type:o,id:s,answers:a}=n;if(i===S.QuestionStatus.RESOLVED&&o===S.QuestionType.PREDICTION){const u=this.background.getCurrentSessionId({prefix:`notification-id:${s}`}),d=[...this.feedList.getValues().data||[]],c=d.findIndex(K=>K.id===s),f=d[c];let p=f?.attributes?.attributes?.value?.answerId;const w=qe(s,this.transport),E=w.subscribe(()=>{});await w.get().promise;let g=w.get().data;g||(g=await rn(s,this.transport)),E(),window.requestAnimationFrame(()=>{w.invalidate()}),p||(p=g?.answers.find(({youVoted:K})=>K)?.id);const m=a.find(({correct:K})=>K),T=p?a.find(({id:K})=>K===p):void 0,D=!!T?.correct;if(f&&d[c]?.attributes?.attributes.case==="question"){try{d[c].attributes.attributes.value.answerId=p,d[c].attributes.attributes.value.openForVoting=!1,p&&(d[c].attributes.attributes.value.status=D?ot.PickHistoryStatus.WON:ot.PickHistoryStatus.LOST)}catch{}this.feedList.getStore().mutate(d)}if(!T||!m)return;this.openedQuestionId.get()?.questionId!==n.id&&this.notifications.add({type:me.QUESTION_RESOLVED,action:()=>this.openQuestion(n.id,r),close:()=>this.closeQuestion(s),autoHideDuration:D?15e3:12e3,id:u,emitEvent:!1,data:{questionId:s,questionType:S.QuestionType.PREDICTION,question:{title:D?`Congratulations! You answered correctly! You won ${m.points} pts!`:`Better luck next time! Correct: ${m?.text}!`,votedAnswer:{title:T?.text,points:T?.points},correctAnswerTitle:m?.text,correct:!!D,predictionResult:i===S.QuestionStatus.RESOLVED,questionTitle:n?.subject}}}),this.userSummary.invalidate()}})),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-questions-list",e=>{const n=[...this.feedList.getStore().value?.data||[]],r=e.data?.attributes?.feedItem,i=n.findIndex(o=>o.id===r?.id);if(r?.attributes&&r.attributes.attributes.case!=="promotion"&&!(r.attributes.status!==S.QuestionStatus.ACTIVE&&r.attributes.status!==S.QuestionStatus.RESOLVED)&&!(!this.isInteractiveAllowed&&Gn.has(r.attributes.type))){if(i!==-1)if(r.attributes.attributes.case==="question"&&n[i].attributes?.attributes.case==="question"){const o=n[i];o.attributes&&(n[i]={...n[i],attributes:{...o.attributes,attributes:{...o.attributes.attributes,value:{...o.attributes.attributes.value,...r.attributes.attributes.value,answerId:o.attributes.attributes.value.answerId,status:o.attributes.attributes.value.status,openForVoting:o.attributes.attributes.value.openForVoting}}}})}else{const o=n[i];o.attributes&&r.attributes&&(n[i]={...n[i],attributes:{...o.attributes,attributes:{...o.attributes.attributes,value:{...o.attributes.attributes.value,...r.attributes.attributes.value}}}})}i===-1&&(n.unshift(r),q.emit("poll",{action:"received",payload:{questionId:r.id,questionType:r.attributes?.type}})),this.feedList.getStore().mutate(n)}}))};disconnect=()=>{this.background.feedSubscription.removeListener("feed-subscription-prediction-close"),this.background.feedSubscription.removeListener("feed-subscription-questions-list")};betPackVote=async(e,n)=>{try{await Bn(this.transport,{questionId:e,answerId:n})}catch(o){if(o.message===je.ALREADY_VOTED){const s=qe(e,this.transport),a=s.subscribe(()=>{});s.invalidate(),a()}throw o}const r={...this.betPack.getValues().data?.data},i=r?.[e];i&&(q.emit("poll",{action:"voted",payload:{questionId:e,questionType:i.type}}),i.answers=i.answers.map(o=>o.id===n?{...o,youVoted:!0}:o),this.betPack.getStore().mutate({data:r,timestamp:Date.now()}))};submitAnswer=async(e,n)=>{const r=qe(e,this.transport),i=r.subscribe(()=>{}),o={...r.get().data||{}},s=()=>{const a=this.feedList.getValues().data;if(!a)return;const u=a.findIndex(f=>f.id===e),d=a[u],c=d?.attributes?.attributes.case==="question"&&d.attributes.attributes.value;if(c){q.emit("poll",{action:"voted",payload:{questionId:e,questionType:c.questionType}});const f=r.get().data;if(i(),f){const p=f.answers.find(m=>m.correct===!0),w=f.answers.findIndex(m=>m.id===n),E=f.answers[w],g=f.answers.every(({percentageDecimal:m},T)=>m===o?.answers[T].percentageDecimal);a[u].attributes.attributes.value.answerId=n,a[u].attributes.attributes.value.openForVoting=!1,a[u].attributes.attributes.value.text=E?.text||"",p&&(a[u].attributes.attributes.value.status=p.id===n?ot.PickHistoryStatus.WON:ot.PickHistoryStatus.LOST),this.feedList.getStore().mutate([...a]),f.answers[w].correct=p?.id===n,f.answers[w].youVoted=!0,g&&f.answers.forEach(m=>{m.percentageDecimal=0}),p?.id===n&&(f.answers[w].pointsEarned=f.status===S.QuestionStatus.RESOLVED?0:p.points),r.mutate({...f})}this.submitAnswerTimeout&&clearTimeout(this.submitAnswerTimeout),this.submitAnswerTimeout=setTimeout(()=>{this.userSummary.invalidate()},1e3)}};try{await Bn(this.transport,{questionId:e,answerId:n}),s()}catch(a){if(a.message===je.ALREADY_VOTED){this.userSummary.invalidate();const u=r.subscribe(()=>{});r.invalidate(),u()}throw a}};openQuestion=(e,n)=>{if(!e)return()=>{};const r=n?.openedFrom==="bet-pack";this.notifications.close(this.background.getCurrentSessionId({prefix:"notification",entity:e}),{animateHiding:!1});let i=n?.attributes?.type;!i&&!r&&(i=(this.feedList.getStore().value?.data||[]).find(a=>a.id===e)?.attributes?.type);const o={eventId:this.background.slStreamId.get()||"",userId:this.background.userId.get()||"",organizationId:this.background.organizationId.get()||""};return this.storage.isQuestionOpened(o,e)||(q.emit("poll",{action:"opened",payload:{questionId:e,questionType:i,questionOpenedFrom:n?.openedFrom==="bet-pack"?"list":n?.openedFrom}}),this.storage.saveQuestionOpened(o,e)),r||this.openFeature(),this.background.openQuestion(e,n?{...n,openedFrom:n?.openedFrom==="bet-pack"?"list":n?.openedFrom}:void 0)};getFeedItem=e=>zi(e,this.transport);isOpenedQuestion=e=>!!this.notifications.isViewed(e);closeQuestion=e=>(e&&this.onQuestionActivate({stage:"deactivate",id:e,isViewed:!!this.notifications.isViewed(this.background.getCurrentSessionId({prefix:"notification",entity:e}))}),this.background.closeQuestion(e));openUser=async e=>{if(!this.leaderboardList)return;const n=this.leaderboardList?.$store.get().data?.find(i=>i.userId===e);if(!n){this.openedUser?.set(n);return}if(n.summaryLoaded){this.openedUser?.set(n);return}const r={...n};try{const i=await Lo(this.background.slStreamId,this.background.userId,this.friends,e,this.transport);i?.inTop!==void 0&&(this.leaderboardList?.$store.setKey("data",this.leaderboardList.$store.get().data?.map(o=>(o.userId===e&&(o.inTop=i.inTop),o))),r.inTop=i.inTop)}catch(i){console.error(i)}this.openedUser.set(r)};closeUser=()=>{this.openedUser?.set(void 0)};showInApp=e=>{const n=this.onboardingStatus.$store.get();if(e&&e.data&&n&&n!==B.Unset&&e.data.question?.id!==void 0&&e.data.question?.bypassNotifications?.inAppSilence!==S.SilenceSetting.ON&&e.data.question.status===S.QuestionStatus.ACTIVE&&!e.data.question.marketClosed){if(Gn.has(e.data.question.type))this.isInteractiveAllowed&&e.data.question.notification!==void 0&&this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e.data?.question?.id,e.data?.feedItem),close:()=>this.closeQuestion(e.data?.question?.id),autoHideDuration:1e3*60,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),emitEvent:!0,data:{questionId:e.data.question.id,questionType:e.data.question.type,question:{title:e.data.question.notification.title},inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}});else if(e.data.question.type===S.QuestionType.FACTOID){const r=e.data.question.options?.options.value,i=e.data.question.notification?.title||e.data.question.subject||"",o=e.data.question.notification?.body||r.body,s={heading:i,body:o,imageMode:r?.imageMode,image:r?.image,video:{id:r?.video?.id||"",url:r?.video?.url||"",thumbnailUrl:r?.video?.thumbnailUrl||""},webLink:{label:"",url:""}};this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e?.data?.question?.id,e?.data?.feedItem),close:()=>this.closeQuestion(e?.data?.question?.id),autoHideDuration:1e3*120,emitEvent:!0,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),data:{questionId:e.data.question.id,questionType:e.data.question.type,insight:s,inApp:{useMediaFromContent:r?.useAsNotification===S.UseAsNotification.ENABLED,notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}})}else if(e.data.question.type===S.QuestionType.TWEET&&e.data.question.notification!==void 0){const r=e.data.question.options?.options.value,i={image:"",video:""};if(r.tweetMeta?.tweet?.meta?.extendedEntities?.media?.[0]){const s=r.tweetMeta.tweet.meta.extendedEntities.media;if(s){const a=s.find(({type:u})=>u==="photo")||s[0];i.image=a.mediaUrlHttps,a.type==="video"&&(i.video=a.url)}}const o={title:e.data.question.notification?.title,body:e.data.question.notification?.body,image:e.data.question.notification?.image,account:r?.tweetMeta?.account||"",accountVerified:!!r?.tweetMeta?.accountVerified,tweet:r?.tweetMeta?.tweet,tweetId:e.data.question.id,tweetMedia:i};this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e.data?.question?.id,e.data?.feedItem),close:()=>this.closeQuestion(e.data?.question?.id),autoHideDuration:1e3*120,emitEvent:!0,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),data:{questionId:e.data.question.id,questionType:e.data.question.type,tweet:o,inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}})}}}}const Fo={[V.SdkOverlayType.GAMES]:!0};class Do extends Tr{constructor(e,n){super(e,n)}}const Ro=(t,e,n)=>t.type===V.SdkOverlayType.GAMES?new No(t,e,n):new Do(t,e),Vo=(t,e,n)=>{t.features=new Map,t.sdk.featuresList=new J(Q(new Set),"features-list"),t.activeFeature=new J(Q(V.SdkOverlayType.UNSET),"activeFeature"),t.sdk.getFeatures=()=>t.features,t.sdk.getFeature=r=>t.features.get(r),t.sdk.getActiveFeature=()=>t.activeFeature.getStore(),t.sdk.openFeature=r=>{t.sdk.initializeApp().then(()=>{t.activeFeature.setValue(r)})},t.sdk.closeFeature=(r=!1)=>{const i=t.activeFeature.getValue();if(t.activeFeature.setValue(V.SdkOverlayType.UNSET),r&&i){t.features.delete(i);const o=t.sdk.featuresList.getValue();o&&o.delete(i),t.sdk.featuresList.setValue(o)}},t.initFeature=(r,i=pe.ORGANIZATION)=>{if(r.type in Fo&&!t.features.has(r.type)){const o=Ro(r,i,t);t.features.set(r.type,o);let s=t.sdk.featuresList.getValue();s?s.add(r.type):s=new Set([r.type]),t.sdk.featuresList.setValue(new Set(s))}},t.updateFeature=(r,i)=>{t.features.get(r.type)?.update(r,i)},t.destroyFeature=r=>{t.features.delete(r.type);const i=t.sdk.featuresList.getValue();i&&i.delete(r.type),t.sdk.featuresList.setValue(new Set(i))},t.reinitializeFeatures=async()=>{const r=await t.stores.organizationSettings.getValue();t.features.clear(),t.sdk.featuresList.setValue(new Set);for(const i of r?.overlays||[])t.initFeature(i,pe.ORGANIZATION)},t.stores.providerStreamId.listen(r=>{r||t.reinitializeFeatures()}),t.storeSubscribe=()=>{const r=(o,s)=>{if(s?.overlays&&!(t.contextConfig?.skipOrganizationSettings&&o===pe.ORGANIZATION))for(const a of s.overlays)a.sdkEnable===!0&&(t.features.has(a.type)?t.updateFeature(a,o):t.initFeature(a,o))},i={organizationSettings:o=>{if(o.data)try{r(pe.ORGANIZATION,o.data)}catch(s){console.log(s)}},streamSettings:o=>{if(o.data)try{r(pe.STREAM,o.data)}catch(s){console.log(s)}}};t.store.subscribe(i)},n()};class $o{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="invitation")switch(r.slEventBus.action){case"sent":this.sent(r.slEventBus.payload);break}};return q.listen(n)})}accepted=()=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_ACCEPTED},category:st.InvitationCategory.GAMES,from:st.InvitationFrom.UNSET})};sent=({from:e})=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_SENT},category:st.InvitationCategory.GAMES,from:e||st.InvitationFrom.UNSET})}}class Bo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="interactions")switch(r.slEventBus.action){case"tap":this.tap();break;case"scroll":this.scroll();break}};return q.listen(n)})}tap=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:Dn.InteractionActionType.TAP})};scroll=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:Dn.InteractionActionType.SCROLL})}}const Mo={[S.PromotionType.UNSET]:v.TopicSubType.UNSET,[S.PromotionType.INGAME_IAB21]:v.TopicSubType.PROMOTION_INGAME_IAB21,[S.PromotionType.INGAME_IAB11_LBAR]:v.TopicSubType.PROMOTION_INGAME_IAB11_LBAR,[S.PromotionType.INGAME_IAB11]:v.TopicSubType.PROMOTION_INGAME_IAB11,[S.PromotionType.INGAME_IAB21_LBAR]:v.TopicSubType.PROMOTION_INGAME_IAB21_LBAR,[S.PromotionType.INGAME_IAB61]:v.TopicSubType.PROMOTION_INGAME_IAB61,[S.PromotionType.EXTERNAL_AD]:v.TopicSubType.PROMOTION_GAM,[S.PromotionType.VIDEO_SIDE_BY_SIDE]:v.TopicSubType.PROMOTION_VIDEO_SIDE_BY_SIDE,[S.PromotionType.PICTURE_IN_PICTURE]:v.TopicSubType.PROMOTION_PICTURE_IN_PICTURE,[S.PromotionType.SHOP_LBAR]:v.TopicSubType.PROMOTION_SHOP_LBAR,[S.PromotionType.SHOP_OVERLAY]:v.TopicSubType.PROMOTION_SHOP_OVERLAY,[S.PromotionType.SHOP_SIDEBAR]:v.TopicSubType.PROMOTION_SHOP_SIDEBAR},on=t=>t?Mo[t]:v.TopicSubType.UNSET;class qo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(!r.slEventBus?.skipAnalytics&&r.slEventBus?.type==="advertisement"){const i=on(r.slEventBus.payload.type);switch(r.slEventBus.action){case"videoPlay":this.videoPlay(r.slEventBus.payload,{topicSubType:i});break;case"buttonSelect":this.buttonSelect(r.slEventBus.payload,{topicSubType:i});break;case"bannerSelect":this.bannerSelect(r.slEventBus.payload,{topicSubType:i});break;case"received":this.received(r.slEventBus.payload,{topicSubType:i});break;case"opened":this.opened(r.slEventBus.payload,{topicSubType:i});break;case"viewed":this.viewed(r.slEventBus.payload,{topicSubType:i});break}}};return q.listen(n)})}received=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_RECEIVED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};opened=({id:e,openedFrom:n},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:n==="notification"?v.PollOpenedFrom.IN_APP:v.PollOpenedFrom.UNSET})};viewed=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};videoPlay=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_VIDEO_PLAYED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};buttonSelect=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_BUTTON_NAVIGATED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};bannerSelect=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_BANNER_NAVIGATED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})}}const Je={[S.QuestionType.UNSET]:v.TopicType.UNSET,[S.QuestionType.FACTOID]:v.TopicType.POLLS_INSIGHT,[S.QuestionType.POLL]:v.TopicType.POLLS_POLL,[S.QuestionType.PREDICTION]:v.TopicType.POLLS_PREDICTION,[S.QuestionType.PROMOTION]:v.TopicType.POLLS_PROMOTION,[S.QuestionType.TRIVIA]:v.TopicType.POLLS_TRIVIA,[S.QuestionType.TWEET]:v.TopicType.POLLS_TWITTER};S.QuestionType.UNSET+"",ee.NotificationKind.UNSET,S.QuestionType.FACTOID+"",ee.NotificationKind.POLLS,S.QuestionType.POLL+"",ee.NotificationKind.POLLS,S.QuestionType.PREDICTION+"",ee.NotificationKind.POLLS,S.QuestionType.PROMOTION+"",ee.NotificationKind.POLLS,S.QuestionType.TRIVIA+"",ee.NotificationKind.POLLS,S.QuestionType.TWEET+"",ee.NotificationKind.POLLS;const Uo={[V.SdkOverlayType.UNSET]:v.Category.UNSET,[V.SdkOverlayType.INPLAY]:v.Category.INPLAY,[V.SdkOverlayType.MESSAGING]:v.Category.MESSAGING,[V.SdkOverlayType.STATISTICS]:v.Category.STATS,[V.SdkOverlayType.BETTING]:v.Category.BETTING,[V.SdkOverlayType.TWITTER]:v.Category.TWITTER,[V.SdkOverlayType.MERCHANDISE]:v.Category.MERCHANDISE,[V.SdkOverlayType.CONTESTS]:v.Category.CONTESTS,[V.SdkOverlayType.VOICE_CHAT]:v.Category.CALLING,[V.SdkOverlayType.TICKETS]:v.Category.TICKETS,[V.SdkOverlayType.WHOIS_WATCHING]:v.Category.WHOISWATCHING,[V.SdkOverlayType.PROFILE]:v.Category.PROFILE,[V.SdkOverlayType.GAMES]:v.Category.POLLS,[V.SdkOverlayType.GOLF_STATISTICS]:v.Category.STATS,[V.SdkOverlayType.HIGHLIGHTS]:v.Category.HIGHLIGHTS,[V.SdkOverlayType.PUBLIC_CHAT]:v.Category.PUBLIC_CHAT};class Qo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="notification")switch(r.slEventBus.action){case"rendered":this.received(r.slEventBus.payload);break;case"opened":this.opened(r.slEventBus.payload);break}if(r.slEventBus?.type==="advertisement")switch(r.slEventBus.action){case"notification-received":this.received({questionId:r.slEventBus.payload.id,questionType:S.QuestionType.PROMOTION,topicSubType:on(r.slEventBus.payload.type)});break;case"notification-opened":this.opened({questionId:r.slEventBus.payload.id,questionType:S.QuestionType.PROMOTION,topicSubType:on(r.slEventBus.payload.type)});break}};return q.listen(n)})}received=({questionId:e,questionType:n,topicSubType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_RECEIVED,topicId:e,topicType:n?Je[n]:v.TopicType.UNSET,topicSubType:r},notificationKind:ee.NotificationKind.POLLS,notificationType:ee.NotificationType.IN_APP})};opened=({questionId:e,questionType:n,topicSubType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_OPENED,topicId:e,topicType:n?Je[n]:v.TopicType.UNSET,topicSubType:r},notificationKind:ee.NotificationKind.POLLS,notificationType:ee.NotificationType.IN_APP})}}class jo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="poll")switch(r.slEventBus.action){case"voted":this.voted(r.slEventBus.payload);break;case"navigated":this.navigated();break;case"onboardingPassed":this.onboardingPassed();break;case"received":this.received(r.slEventBus.payload);break;case"opened":this.opened(r.slEventBus.payload);break}};return q.listen(n)})}received=({questionId:e,questionType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_RECEIVED,topicId:e,topicType:n?Je[n]:v.TopicType.UNSET},pollOpenedFrom:v.PollOpenedFrom.UNSET})};opened=({questionId:e,questionType:n,questionOpenedFrom:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:n?Je[n]:v.TopicType.UNSET},pollOpenedFrom:r==="list"?v.PollOpenedFrom.PICK_HISTORY:v.PollOpenedFrom.IN_APP})};voted=({questionId:e,questionType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_VOTE,topicId:e,topicType:n?Je[n]:v.TopicType.UNSET},pollOpenedFrom:v.PollOpenedFrom.UNSET})};onboardingPassed=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.GAMES_JOINED},pollOpenedFrom:v.PollOpenedFrom.UNSET})};navigated=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_NAVIGATED},pollOpenedFrom:v.PollOpenedFrom.UNSET})}}const xo=({transport:t,$commonStore:e})=>{let n;const r=Q(!1),i=3e4,{client:o,queryKey:s}=t.createPromiseClient(mr.AnalyticsService,{method:"send",params:[r]}),a=t.nanoquery.createFetcherStore(s,{fetcher:async()=>{const p=e.getStore().get();try{await o.unary({message:{case:"heartbeat",value:{common:{...p,kind:v.Kind.SESSION_HEARTBEAT}}}})}catch(w){ye.error(w,"send heartbeat failed")}return Date.now()},refetchInterval:i}),u=()=>{ye.debug("mounted heartbeat"),n=a.subscribe(()=>{})},d=()=>{ye.debug("enabled heartbeat"),r.set(!0),a.lc===0&&u()},c=()=>{ye.debug("disabled heartbeat"),r.set(!1)};return{enable:d,disable:c,mount:u,unmount:()=>{ye.debug("unmounted heartbeat"),a.off(),n?.(),n=void 0,c()}}},ye=ce("analytics");class Go{commonStore;notifications;polls;invitation;interactions;advertisement;heartbeat;analyticsClient;listeners;listenersCancels;connected=!1;constructor(e){this.listeners=new Set,this.listenersCancels=new Set,this.commonStore=new Ie(H({}),"common-analytics"),this.connectToSDK(e),this.heartbeat=xo({transport:e.analyticsTransport,$commonStore:this.commonStore}),this.notifications=new Qo(this),this.polls=new jo(this),this.invitation=new $o(this),this.interactions=new Bo(this),this.advertisement=new qo(this);const{client:n}=e.analyticsTransport.createPromiseClient(mr.AnalyticsService,{method:"send"});this.analyticsClient=n}connect=()=>{this.writeCommon("sessionId",Zt.v4()),this.heartbeat.enable(),this.listeners.forEach(e=>this.listenersCancels.add(e())),this.connected=!0,ye.debug("analytics connected")};disconnect=()=>{this.writeCommon("sessionId",""),this.writeCommon("overlaySessionId",""),this.heartbeat.unmount(),this.listenersCancels.forEach(e=>e()),this.connected=!1,ye.debug("analytics disconnected")};write=(e,n)=>{n&&this.analyticsClient.unary({message:{case:e,value:n}}).then(()=>{ye.trace("send analytics success",e,n)}).catch(r=>{ye.error(r,"send analytics failed")})};writeCommon=(e,n)=>{this.commonStore.setValue(e,n)};onConnect=e=>{this.listeners.add(e),this.connected&&this.listenersCancels.add(e())};connectToSDK=e=>{this.onConnect(()=>e.stores.slStreamId.getAtomStore().subscribe(n=>{this.writeCommon("eventId",n)})),this.onConnect(()=>e.sdk.getActiveFeature().subscribe(n=>{n&&this.writeCommon("category",Uo[n]),n!==V.SdkOverlayType.UNSET?this.writeCommon("overlaySessionId",Zt.v4()):this.writeCommon("overlaySessionId","")})),this.onConnect(()=>{const n=window.matchMedia("(orientation: portrait)"),r=i=>{this.writeCommon("screenOrientation",i.matches?v.ScreenOrientation.PORTRAIT:v.ScreenOrientation.LANDSCAPE)};return n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}}),this.onConnect(()=>e.deepLink.$store.subscribe(n=>{n?.handled&&this.invitation.accepted()}))}}const Ko=(t,e,n)=>{t.analytics=new Go(t),t.sdk.onMount({name:"analytics"},()=>(t.analytics.connect(),()=>{t.analytics.disconnect()})),n()};var mn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var bn={exports:{}},vn={exports:{}};function Ho(t){var e=new t,n=e;function r(){var o=e;return o.next?e=o.next:(e=new t,n=e),o.next=null,o}function i(o){n.next=o,n=o}return{get:r,release:i}}var Wo=Ho,Yo=Wo;function Cr(t,e,n){if(typeof t=="function"&&(n=e,e=t,t=null),!(n>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");var r=Yo(Jo),i=null,o=null,s=0,a=null,u={push:g,drain:Y,saturated:Y,pause:c,paused:!1,get concurrency(){return n},set concurrency(N){if(!(N>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(n=N,!u.paused)for(;i&&s<n;)s++,T()},running:d,resume:w,idle:E,length:f,getQueue:p,unshift:m,empty:Y,kill:D,killAndDrain:K,error:X};return u;function d(){return s}function c(){u.paused=!0}function f(){for(var N=i,$=0;N;)N=N.next,$++;return $}function p(){for(var N=i,$=[];N;)$.push(N.value),N=N.next;return $}function w(){if(u.paused){if(u.paused=!1,i===null){s++,T();return}for(;i&&s<n;)s++,T()}}function E(){return s===0&&u.length()===0}function g(N,$){var _=r.get();_.context=t,_.release=T,_.value=N,_.callback=$||Y,_.errorHandler=a,s>=n||u.paused?o?(o.next=_,o=_):(i=_,o=_,u.saturated()):(s++,e.call(t,_.value,_.worked))}function m(N,$){var _=r.get();_.context=t,_.release=T,_.value=N,_.callback=$||Y,_.errorHandler=a,s>=n||u.paused?i?(_.next=i,i=_):(i=_,o=_,u.saturated()):(s++,e.call(t,_.value,_.worked))}function T(N){N&&r.release(N);var $=i;$&&s<=n?u.paused?s--:(o===i&&(o=null),i=$.next,$.next=null,e.call(t,$.value,$.worked),o===null&&u.empty()):--s===0&&u.drain()}function D(){i=null,o=null,u.drain=Y}function K(){i=null,o=null,u.drain(),u.drain=Y}function X(N){a=N}}function Y(){}function Jo(){this.value=null,this.callback=Y,this.next=null,this.release=Y,this.context=null,this.errorHandler=null;var t=this;this.worked=function(n,r){var i=t.callback,o=t.errorHandler,s=t.value;t.value=null,t.callback=Y,t.errorHandler&&o(n,s),i.call(t.context,n,r),t.release(t)}}function Xo(t,e,n){typeof t=="function"&&(n=e,e=t,t=null);function r(c,f){e.call(this,c).then(function(p){f(null,p)},f)}var i=Cr(t,r,n),o=i.push,s=i.unshift;return i.push=a,i.unshift=u,i.drained=d,i;function a(c){var f=new Promise(function(p,w){o(c,function(E,g){if(E){w(E);return}p(g)})});return f.catch(Y),f}function u(c){var f=new Promise(function(p,w){s(c,function(E,g){if(E){w(E);return}p(g)})});return f.catch(Y),f}function d(){if(i.idle())return new Promise(function(p){p()});var c=i.drain,f=new Promise(function(p){i.drain=function(){c(),p()}});return f}}vn.exports=Cr;vn.exports.promise=Xo;var Pr=vn.exports,Sn={exports:{}},Ue=typeof Reflect=="object"?Reflect:null,Kn=Ue&&typeof Ue.apply=="function"?Ue.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},lt;Ue&&typeof Ue.ownKeys=="function"?lt=Ue.ownKeys:Object.getOwnPropertySymbols?lt=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:lt=function(e){return Object.getOwnPropertyNames(e)};function Zo(t){console&&console.warn&&console.warn(t)}var Lr=Number.isNaN||function(e){return e!==e};function F(){F.init.call(this)}Sn.exports=F;Sn.exports.once=rs;F.EventEmitter=F;F.prototype._events=void 0;F.prototype._eventsCount=0;F.prototype._maxListeners=void 0;var zn=10;function _t(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(F,"defaultMaxListeners",{enumerable:!0,get:function(){return zn},set:function(t){if(typeof t!="number"||t<0||Lr(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");zn=t}});F.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};F.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Lr(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Nr(t){return t._maxListeners===void 0?F.defaultMaxListeners:t._maxListeners}F.prototype.getMaxListeners=function(){return Nr(this)};F.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(n.length>0&&(s=n[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var u=o[e];if(u===void 0)return!1;if(typeof u=="function")Kn(u,this,n);else for(var d=u.length,c=$r(u,d),r=0;r<d;++r)Kn(c[r],this,n);return!0};function Fr(t,e,n,r){var i,o,s;if(_t(n),o=t._events,o===void 0?(o=t._events=Object.create(null),t._eventsCount=0):(o.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),o=t._events),s=o[e]),s===void 0)s=o[e]=n,++t._eventsCount;else if(typeof s=="function"?s=o[e]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=Nr(t),i>0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,Zo(a)}return t}F.prototype.addListener=function(e,n){return Fr(this,e,n,!1)};F.prototype.on=F.prototype.addListener;F.prototype.prependListener=function(e,n){return Fr(this,e,n,!0)};function es(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Dr(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=es.bind(r);return i.listener=n,r.wrapFn=i,i}F.prototype.once=function(e,n){return _t(n),this.on(e,Dr(this,e,n)),this};F.prototype.prependOnceListener=function(e,n){return _t(n),this.prependListener(e,Dr(this,e,n)),this};F.prototype.removeListener=function(e,n){var r,i,o,s,a;if(_t(n),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(o=-1,s=r.length-1;s>=0;s--)if(r[s]===n||r[s].listener===n){a=r[s].listener,o=s;break}if(o<0)return this;o===0?r.shift():ts(r,o),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||n)}return this};F.prototype.off=F.prototype.removeListener;F.prototype.removeAllListeners=function(e){var n,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var o=Object.keys(r),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=r[e],typeof n=="function")this.removeListener(e,n);else if(n!==void 0)for(i=n.length-1;i>=0;i--)this.removeListener(e,n[i]);return this};function Rr(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?ns(i):$r(i,i.length)}F.prototype.listeners=function(e){return Rr(this,e,!0)};F.prototype.rawListeners=function(e){return Rr(this,e,!1)};F.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Vr.call(t,e)};F.prototype.listenerCount=Vr;function Vr(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}F.prototype.eventNames=function(){return this._eventsCount>0?lt(this._events):[]};function $r(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function ts(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function ns(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function rs(t,e){return new Promise(function(n,r){function i(s){t.removeListener(e,o),r(s)}function o(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}Br(t,e,o,{once:!0}),e!=="error"&&is(t,i,{once:!0})})}function is(t,e,n){typeof t.on=="function"&&Br(t,"error",e,n)}function Br(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(o){r.once&&t.removeEventListener(e,i),n(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Mr=Sn.exports,Ct={},qr={},Ur=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},n=Symbol("test"),r=Object(n);if(typeof n=="string"||Object.prototype.toString.call(n)!=="[object Symbol]"||Object.prototype.toString.call(r)!=="[object Symbol]")return!1;var i=42;e[n]=i;for(n in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var o=Object.getOwnPropertySymbols(e);if(o.length!==1||o[0]!==n||!Object.prototype.propertyIsEnumerable.call(e,n))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(e,n);if(s.value!==i||s.enumerable!==!0)return!1}return!0},os=Ur,Pt=function(){return os()&&!!Symbol.toStringTag},ss=Error,as=EvalError,us=RangeError,cs=ReferenceError,Qr=SyntaxError,Lt=TypeError,ds=URIError,Hn=typeof Symbol<"u"&&Symbol,ls=Ur,fs=function(){return typeof Hn!="function"||typeof Symbol!="function"||typeof Hn("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:ls()},Vt={__proto__:null,foo:{}},ps=Object,hs=function(){return{__proto__:Vt}.foo===Vt.foo&&!(Vt instanceof ps)},ys="Function.prototype.bind called on incompatible ",gs=Object.prototype.toString,ms=Math.max,bs="[object Function]",Wn=function(e,n){for(var r=[],i=0;i<e.length;i+=1)r[i]=e[i];for(var o=0;o<n.length;o+=1)r[o+e.length]=n[o];return r},vs=function(e,n){for(var r=[],i=n,o=0;i<e.length;i+=1,o+=1)r[o]=e[i];return r},Ss=function(t,e){for(var n="",r=0;r<t.length;r+=1)n+=t[r],r+1<t.length&&(n+=e);return n},ws=function(e){var n=this;if(typeof n!="function"||gs.apply(n)!==bs)throw new TypeError(ys+n);for(var r=vs(arguments,1),i,o=function(){if(this instanceof i){var c=n.apply(this,Wn(r,arguments));return Object(c)===c?c:this}return n.apply(e,Wn(r,arguments))},s=ms(0,n.length-r.length),a=[],u=0;u<s;u++)a[u]="$"+u;if(i=Function("binder","return function ("+Ss(a,",")+"){ return binder.apply(this,arguments); }")(o),n.prototype){var d=function(){};d.prototype=n.prototype,i.prototype=new d,d.prototype=null}return i},Ts=ws,wn=Function.prototype.bind||Ts,Es=Function.prototype.call,As=Object.prototype.hasOwnProperty,Is=wn,Os=Is.call(Es,As),k,ks=ss,_s=as,Cs=us,Ps=cs,xe=Qr,Qe=Lt,Ls=ds,jr=Function,$t=function(t){try{return jr('"use strict"; return ('+t+").constructor;")()}catch{}},Oe=Object.getOwnPropertyDescriptor;if(Oe)try{Oe({},"")}catch{Oe=null}var Bt=function(){throw new Qe},Ns=Oe?function(){try{return arguments.callee,Bt}catch{try{return Oe(arguments,"callee").get}catch{return Bt}}}():Bt,De=fs(),Fs=hs(),j=Object.getPrototypeOf||(Fs?function(t){return t.__proto__}:null),Ve={},Ds=typeof Uint8Array>"u"||!j?k:j(Uint8Array),ke={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?k:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?k:ArrayBuffer,"%ArrayIteratorPrototype%":De&&j?j([][Symbol.iterator]()):k,"%AsyncFromSyncIteratorPrototype%":k,"%AsyncFunction%":Ve,"%AsyncGenerator%":Ve,"%AsyncGeneratorFunction%":Ve,"%AsyncIteratorPrototype%":Ve,"%Atomics%":typeof Atomics>"u"?k:Atomics,"%BigInt%":typeof BigInt>"u"?k:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?k:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?k:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?k:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":ks,"%eval%":eval,"%EvalError%":_s,"%Float32Array%":typeof Float32Array>"u"?k:Float32Array,"%Float64Array%":typeof Float64Array>"u"?k:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?k:FinalizationRegistry,"%Function%":jr,"%GeneratorFunction%":Ve,"%Int8Array%":typeof Int8Array>"u"?k:Int8Array,"%Int16Array%":typeof Int16Array>"u"?k:Int16Array,"%Int32Array%":typeof Int32Array>"u"?k:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":De&&j?j(j([][Symbol.iterator]())):k,"%JSON%":typeof JSON=="object"?JSON:k,"%Map%":typeof Map>"u"?k:Map,"%MapIteratorPrototype%":typeof Map>"u"||!De||!j?k:j(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?k:Promise,"%Proxy%":typeof Proxy>"u"?k:Proxy,"%RangeError%":Cs,"%ReferenceError%":Ps,"%Reflect%":typeof Reflect>"u"?k:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?k:Set,"%SetIteratorPrototype%":typeof Set>"u"||!De||!j?k:j(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?k:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":De&&j?j(""[Symbol.iterator]()):k,"%Symbol%":De?Symbol:k,"%SyntaxError%":xe,"%ThrowTypeError%":Ns,"%TypedArray%":Ds,"%TypeError%":Qe,"%Uint8Array%":typeof Uint8Array>"u"?k:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?k:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?k:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?k:Uint32Array,"%URIError%":Ls,"%WeakMap%":typeof WeakMap>"u"?k:WeakMap,"%WeakRef%":typeof WeakRef>"u"?k:WeakRef,"%WeakSet%":typeof WeakSet>"u"?k:WeakSet};if(j)try{null.error}catch(t){var Rs=j(j(t));ke["%Error.prototype%"]=Rs}var Vs=function t(e){var n;if(e==="%AsyncFunction%")n=$t("async function () {}");else if(e==="%GeneratorFunction%")n=$t("function* () {}");else if(e==="%AsyncGeneratorFunction%")n=$t("async function* () {}");else if(e==="%AsyncGenerator%"){var r=t("%AsyncGeneratorFunction%");r&&(n=r.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&j&&(n=j(i.prototype))}return ke[e]=n,n},Yn={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},et=wn,vt=Os,$s=et.call(Function.call,Array.prototype.concat),Bs=et.call(Function.apply,Array.prototype.splice),Jn=et.call(Function.call,String.prototype.replace),St=et.call(Function.call,String.prototype.slice),Ms=et.call(Function.call,RegExp.prototype.exec),qs=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Us=/\\(\\)?/g,Qs=function(e){var n=St(e,0,1),r=St(e,-1);if(n==="%"&&r!=="%")throw new xe("invalid intrinsic syntax, expected closing `%`");if(r==="%"&&n!=="%")throw new xe("invalid intrinsic syntax, expected opening `%`");var i=[];return Jn(e,qs,function(o,s,a,u){i[i.length]=a?Jn(u,Us,"$1"):s||o}),i},js=function(e,n){var r=e,i;if(vt(Yn,r)&&(i=Yn[r],r="%"+i[0]+"%"),vt(ke,r)){var o=ke[r];if(o===Ve&&(o=Vs(r)),typeof o>"u"&&!n)throw new Qe("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:r,value:o}}throw new xe("intrinsic "+e+" does not exist!")},tt=function(e,n){if(typeof e!="string"||e.length===0)throw new Qe("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof n!="boolean")throw new Qe('"allowMissing" argument must be a boolean');if(Ms(/^%?[^%]*%?$/,e)===null)throw new xe("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=Qs(e),i=r.length>0?r[0]:"",o=js("%"+i+"%",n),s=o.name,a=o.value,u=!1,d=o.alias;d&&(i=d[0],Bs(r,$s([0,1],d)));for(var c=1,f=!0;c<r.length;c+=1){var p=r[c],w=St(p,0,1),E=St(p,-1);if((w==='"'||w==="'"||w==="`"||E==='"'||E==="'"||E==="`")&&w!==E)throw new xe("property names with quotes must have matching quotes");if((p==="constructor"||!f)&&(u=!0),i+="."+p,s="%"+i+"%",vt(ke,s))a=ke[s];else if(a!=null){if(!(p in a)){if(!n)throw new Qe("base intrinsic for "+e+" exists, but the property is not available.");return}if(Oe&&c+1>=r.length){var g=Oe(a,p);f=!!g,f&&"get"in g&&!("originalValue"in g.get)?a=g.get:a=a[p]}else f=vt(a,p),a=a[p];f&&!u&&(ke[s]=a)}}return a},xr={exports:{}},Mt,Xn;function Tn(){if(Xn)return Mt;Xn=1;var t=tt,e=t("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Mt=e,Mt}var xs=tt,ft=xs("%Object.getOwnPropertyDescriptor%",!0);if(ft)try{ft([],"length")}catch{ft=null}var Nt=ft,Zn=Tn(),Gs=Qr,Re=Lt,er=Nt,Ks=function(e,n,r){if(!e||typeof e!="object"&&typeof e!="function")throw new Re("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new Re("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Re("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Re("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Re("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Re("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,o=arguments.length>4?arguments[4]:null,s=arguments.length>5?arguments[5]:null,a=arguments.length>6?arguments[6]:!1,u=!!er&&er(e,n);if(Zn)Zn(e,n,{configurable:s===null&&u?u.configurable:!s,enumerable:i===null&&u?u.enumerable:!i,value:r,writable:o===null&&u?u.writable:!o});else if(a||!i&&!o&&!s)e[n]=r;else throw new Gs("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},sn=Tn(),Gr=function(){return!!sn};Gr.hasArrayLengthDefineBug=function(){if(!sn)return null;try{return sn([],"length",{value:1}).length!==1}catch{return!0}};var zs=Gr,Hs=tt,tr=Ks,Ws=zs(),nr=Nt,rr=Lt,Ys=Hs("%Math.floor%"),Js=function(e,n){if(typeof e!="function")throw new rr("`fn` is not a function");if(typeof n!="number"||n<0||n>4294967295||Ys(n)!==n)throw new rr("`length` must be a positive 32-bit integer");var r=arguments.length>2&&!!arguments[2],i=!0,o=!0;if("length"in e&&nr){var s=nr(e,"length");s&&!s.configurable&&(i=!1),s&&!s.writable&&(o=!1)}return(i||o||!r)&&(Ws?tr(e,"length",n,!0,!0):tr(e,"length",n)),e};(function(t){var e=wn,n=tt,r=Js,i=Lt,o=n("%Function.prototype.apply%"),s=n("%Function.prototype.call%"),a=n("%Reflect.apply%",!0)||e.call(s,o),u=Tn(),d=n("%Math.max%");t.exports=function(p){if(typeof p!="function")throw new i("a function is required");var w=a(e,s,arguments);return r(w,1+d(0,p.length-(arguments.length-1)),!0)};var c=function(){return a(e,o,arguments)};u?u(t.exports,"apply",{value:c}):t.exports.apply=c})(xr);var En=xr.exports,Kr=tt,zr=En,Xs=zr(Kr("String.prototype.indexOf")),An=function(e,n){var r=Kr(e,!!n);return typeof r=="function"&&Xs(e,".prototype.")>-1?zr(r):r},Zs=Pt(),ea=An,an=ea("Object.prototype.toString"),Ft=function(e){return Zs&&e&&typeof e=="object"&&Symbol.toStringTag in e?!1:an(e)==="[object Arguments]"},Hr=function(e){return Ft(e)?!0:e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&an(e)!=="[object Array]"&&an(e.callee)==="[object Function]"},ta=function(){return Ft(arguments)}();Ft.isLegacyArguments=Hr;var na=ta?Ft:Hr,ra=Object.prototype.toString,ia=Function.prototype.toString,oa=/^\s*(?:function)?\*/,Wr=Pt(),qt=Object.getPrototypeOf,sa=function(){if(!Wr)return!1;try{return Function("return function*() {}")()}catch{}},Ut,aa=function(e){if(typeof e!="function")return!1;if(oa.test(ia.call(e)))return!0;if(!Wr){var n=ra.call(e);return n==="[object GeneratorFunction]"}if(!qt)return!1;if(typeof Ut>"u"){var r=sa();Ut=r?qt(r):!1}return qt(e)===Ut},Yr=Function.prototype.toString,Be=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,un,pt;if(typeof Be=="function"&&typeof Object.defineProperty=="function")try{un=Object.defineProperty({},"length",{get:function(){throw pt}}),pt={},Be(function(){throw 42},null,un)}catch(t){t!==pt&&(Be=null)}else Be=null;var ua=/^\s*class\b/,cn=function(e){try{var n=Yr.call(e);return ua.test(n)}catch{return!1}},Qt=function(e){try{return cn(e)?!1:(Yr.call(e),!0)}catch{return!1}},ht=Object.prototype.toString,ca="[object Object]",da="[object Function]",la="[object GeneratorFunction]",fa="[object HTMLAllCollection]",pa="[object HTML document.all class]",ha="[object HTMLCollection]",ya=typeof Symbol=="function"&&!!Symbol.toStringTag,ga=!(0 in[,]),dn=function(){return!1};if(typeof document=="object"){var ma=document.all;ht.call(ma)===ht.call(document.all)&&(dn=function(e){if((ga||!e)&&(typeof e>"u"||typeof e=="object"))try{var n=ht.call(e);return(n===fa||n===pa||n===ha||n===ca)&&e("")==null}catch{}return!1})}var ba=Be?function(e){if(dn(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Be(e,null,un)}catch(n){if(n!==pt)return!1}return!cn(e)&&Qt(e)}:function(e){if(dn(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(ya)return Qt(e);if(cn(e))return!1;var n=ht.call(e);return n!==da&&n!==la&&!/^\[object HTML/.test(n)?!1:Qt(e)},va=ba,Sa=Object.prototype.toString,Jr=Object.prototype.hasOwnProperty,wa=function(e,n,r){for(var i=0,o=e.length;i<o;i++)Jr.call(e,i)&&(r==null?n(e[i],i,e):n.call(r,e[i],i,e))},Ta=function(e,n,r){for(var i=0,o=e.length;i<o;i++)r==null?n(e.charAt(i),i,e):n.call(r,e.charAt(i),i,e)},Ea=function(e,n,r){for(var i in e)Jr.call(e,i)&&(r==null?n(e[i],i,e):n.call(r,e[i],i,e))},Aa=function(e,n,r){if(!va(n))throw new TypeError("iterator must be a function");var i;arguments.length>=3&&(i=r),Sa.call(e)==="[object Array]"?wa(e,n,i):typeof e=="string"?Ta(e,n,i):Ea(e,n,i)},Xr=Aa,Ia=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],jt=Ia,Oa=typeof globalThis>"u"?mn:globalThis,Zr=function(){for(var e=[],n=0;n<jt.length;n++)typeof Oa[jt[n]]=="function"&&(e[e.length]=jt[n]);return e},wt=Xr,ka=Zr,ir=En,In=An,yt=Nt,_a=In("Object.prototype.toString"),ei=Pt(),or=typeof globalThis>"u"?mn:globalThis,ln=ka(),On=In("String.prototype.slice"),xt=Object.getPrototypeOf,Ca=In("Array.prototype.indexOf",!0)||function(e,n){for(var r=0;r<e.length;r+=1)if(e[r]===n)return r;return-1},Tt={__proto__:null};ei&&yt&&xt?wt(ln,function(t){var e=new or[t];if(Symbol.toStringTag in e){var n=xt(e),r=yt(n,Symbol.toStringTag);if(!r){var i=xt(n);r=yt(i,Symbol.toStringTag)}Tt["$"+t]=ir(r.get)}}):wt(ln,function(t){var e=new or[t],n=e.slice||e.set;n&&(Tt["$"+t]=ir(n))});var Pa=function(e){var n=!1;return wt(Tt,function(r,i){if(!n)try{"$"+r(e)===i&&(n=On(i,1))}catch{}}),n},La=function(e){var n=!1;return wt(Tt,function(r,i){if(!n)try{r(e),n=On(i,1)}catch{}}),n},Na=function(e){if(!e||typeof e!="object")return!1;if(!ei){var n=On(_a(e),8,-1);return Ca(ln,n)>-1?n:n!=="Object"?!1:La(e)}return yt?Pa(e):null},Et=Xr,Fa=Zr,sr=En,kn=An,gt=Nt,Da=kn("Object.prototype.toString"),ti=Pt(),ar=typeof globalThis>"u"?mn:globalThis,fn=Fa(),_n=kn("String.prototype.slice"),Gt=Object.getPrototypeOf,Ra=kn("Array.prototype.indexOf",!0)||function(e,n){for(var r=0;r<e.length;r+=1)if(e[r]===n)return r;return-1},At={__proto__:null};ti&&gt&&Gt?Et(fn,function(t){var e=new ar[t];if(Symbol.toStringTag in e){var n=Gt(e),r=gt(n,Symbol.toStringTag);if(!r){var i=Gt(n);r=gt(i,Symbol.toStringTag)}At["$"+t]=sr(r.get)}}):Et(fn,function(t){var e=new ar[t],n=e.slice||e.set;n&&(At["$"+t]=sr(n))});var Va=function(e){var n=!1;return Et(At,function(r,i){if(!n)try{"$"+r(e)===i&&(n=_n(i,1))}catch{}}),n},$a=function(e){var n=!1;return Et(At,function(r,i){if(!n)try{r(e),n=_n(i,1)}catch{}}),n},Ba=function(e){if(!e||typeof e!="object")return!1;if(!ti){var n=_n(Da(e),8,-1);return Ra(fn,n)>-1?n:n!=="Object"?!1:$a(e)}return gt?Va(e):null},Ma=Ba,qa=function(e){return!!Ma(e)};(function(t){var e=na,n=aa,r=Na,i=qa;function o(y){return y.call.bind(y)}var s=typeof BigInt<"u",a=typeof Symbol<"u",u=o(Object.prototype.toString),d=o(Number.prototype.valueOf),c=o(String.prototype.valueOf),f=o(Boolean.prototype.valueOf);if(s)var p=o(BigInt.prototype.valueOf);if(a)var w=o(Symbol.prototype.valueOf);function E(y,ui){if(typeof y!="object")return!1;try{return ui(y),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=n,t.isTypedArray=i;function g(y){return typeof Promise<"u"&&y instanceof Promise||y!==null&&typeof y=="object"&&typeof y.then=="function"&&typeof y.catch=="function"}t.isPromise=g;function m(y){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(y):i(y)||h(y)}t.isArrayBufferView=m;function T(y){return r(y)==="Uint8Array"}t.isUint8Array=T;function D(y){return r(y)==="Uint8ClampedArray"}t.isUint8ClampedArray=D;function K(y){return r(y)==="Uint16Array"}t.isUint16Array=K;function X(y){return r(y)==="Uint32Array"}t.isUint32Array=X;function N(y){return r(y)==="Int8Array"}t.isInt8Array=N;function $(y){return r(y)==="Int16Array"}t.isInt16Array=$;function _(y){return r(y)==="Int32Array"}t.isInt32Array=_;function re(y){return r(y)==="Float32Array"}t.isFloat32Array=re;function ie(y){return r(y)==="Float64Array"}t.isFloat64Array=ie;function _e(y){return r(y)==="BigInt64Array"}t.isBigInt64Array=_e;function we(y){return r(y)==="BigUint64Array"}t.isBigUint64Array=we;function de(y){return u(y)==="[object Map]"}de.working=typeof Map<"u"&&de(new Map);function Dt(y){return typeof Map>"u"?!1:de.working?de(y):y instanceof Map}t.isMap=Dt;function ve(y){return u(y)==="[object Set]"}ve.working=typeof Set<"u"&&ve(new Set);function He(y){return typeof Set>"u"?!1:ve.working?ve(y):y instanceof Set}t.isSet=He;function Ce(y){return u(y)==="[object WeakMap]"}Ce.working=typeof WeakMap<"u"&&Ce(new WeakMap);function Rt(y){return typeof WeakMap>"u"?!1:Ce.working?Ce(y):y instanceof WeakMap}t.isWeakMap=Rt;function Pe(y){return u(y)==="[object WeakSet]"}Pe.working=typeof WeakSet<"u"&&Pe(new WeakSet);function le(y){return Pe(y)}t.isWeakSet=le;function Le(y){return u(y)==="[object ArrayBuffer]"}Le.working=typeof ArrayBuffer<"u"&&Le(new ArrayBuffer);function nt(y){return typeof ArrayBuffer>"u"?!1:Le.working?Le(y):y instanceof ArrayBuffer}t.isArrayBuffer=nt;function l(y){return u(y)==="[object DataView]"}l.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&l(new DataView(new ArrayBuffer(1),0,1));function h(y){return typeof DataView>"u"?!1:l.working?l(y):y instanceof DataView}t.isDataView=h;var b=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function A(y){return u(y)==="[object SharedArrayBuffer]"}function P(y){return typeof b>"u"?!1:(typeof A.working>"u"&&(A.working=A(new b)),A.working?A(y):y instanceof b)}t.isSharedArrayBuffer=P;function L(y){return u(y)==="[object AsyncFunction]"}t.isAsyncFunction=L;function O(y){return u(y)==="[object Map Iterator]"}t.isMapIterator=O;function C(y){return u(y)==="[object Set Iterator]"}t.isSetIterator=C;function R(y){return u(y)==="[object Generator]"}t.isGeneratorObject=R;function z(y){return u(y)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=z;function Te(y){return E(y,d)}t.isNumberObject=Te;function rt(y){return E(y,c)}t.isStringObject=rt;function Ne(y){return E(y,f)}t.isBooleanObject=Ne;function it(y){return s&&E(y,p)}t.isBigIntObject=it;function Ln(y){return a&&E(y,w)}t.isSymbolObject=Ln;function si(y){return Te(y)||rt(y)||Ne(y)||it(y)||Ln(y)}t.isBoxedPrimitive=si;function ai(y){return typeof Uint8Array<"u"&&(nt(y)||P(y))}t.isAnyArrayBuffer=ai,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(y){Object.defineProperty(t,y,{enumerable:!1,value:function(){throw new Error(y+" is not supported in userland")}})})})(qr);var Ua=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"},pn={exports:{}};typeof Object.create=="function"?pn.exports=function(e,n){n&&(e.super_=n,e.prototype=Object.create(n.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:pn.exports=function(e,n){if(n){e.super_=n;var r=function(){};r.prototype=n.prototype,e.prototype=new r,e.prototype.constructor=e}};var Qa=pn.exports;(function(t){var e=Object.getOwnPropertyDescriptors||function(h){for(var b=Object.keys(h),A={},P=0;P<b.length;P++)A[b[P]]=Object.getOwnPropertyDescriptor(h,b[P]);return A},n=/%[sdj%]/g;t.format=function(l){if(!N(l)){for(var h=[],b=0;b<arguments.length;b++)h.push(s(arguments[b]));return h.join(" ")}for(var b=1,A=arguments,P=A.length,L=String(l).replace(n,function(C){if(C==="%%")return"%";if(b>=P)return C;switch(C){case"%s":return String(A[b++]);case"%d":return Number(A[b++]);case"%j":try{return JSON.stringify(A[b++])}catch{return"[Circular]"}default:return C}}),O=A[b];b<P;O=A[++b])D(O)||!ie(O)?L+=" "+O:L+=" "+s(O);return L},t.deprecate=function(l,h){if(typeof I<"u"&&I.noDeprecation===!0)return l;if(typeof I>"u")return function(){return t.deprecate(l,h).apply(this,arguments)};var b=!1;function A(){if(!b){if(I.throwDeprecation)throw new Error(h);I.traceDeprecation?console.trace(h):console.error(h),b=!0}return l.apply(this,arguments)}return A};var r={},i=/^$/;if(I.env.NODE_DEBUG){var o=I.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}t.debuglog=function(l){if(l=l.toUpperCase(),!r[l])if(i.test(l)){var h=I.pid;r[l]=function(){var b=t.format.apply(t,arguments);console.error("%s %d: %s",l,h,b)}}else r[l]=function(){};return r[l]};function s(l,h){var b={seen:[],stylize:u};return arguments.length>=3&&(b.depth=arguments[2]),arguments.length>=4&&(b.colors=arguments[3]),T(h)?b.showHidden=h:h&&t._extend(b,h),_(b.showHidden)&&(b.showHidden=!1),_(b.depth)&&(b.depth=2),_(b.colors)&&(b.colors=!1),_(b.customInspect)&&(b.customInspect=!0),b.colors&&(b.stylize=a),c(b,l,b.depth)}t.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(l,h){var b=s.styles[h];return b?"\x1B["+s.colors[b][0]+"m"+l+"\x1B["+s.colors[b][1]+"m":l}function u(l,h){return l}function d(l){var h={};return l.forEach(function(b,A){h[b]=!0}),h}function c(l,h,b){if(l.customInspect&&h&&de(h.inspect)&&h.inspect!==t.inspect&&!(h.constructor&&h.constructor.prototype===h)){var A=h.inspect(b,l);return N(A)||(A=c(l,A,b)),A}var P=f(l,h);if(P)return P;var L=Object.keys(h),O=d(L);if(l.showHidden&&(L=Object.getOwnPropertyNames(h)),we(h)&&(L.indexOf("message")>=0||L.indexOf("description")>=0))return p(h);if(L.length===0){if(de(h)){var C=h.name?": "+h.name:"";return l.stylize("[Function"+C+"]","special")}if(re(h))return l.stylize(RegExp.prototype.toString.call(h),"regexp");if(_e(h))return l.stylize(Date.prototype.toString.call(h),"date");if(we(h))return p(h)}var R="",z=!1,Te=["{","}"];if(m(h)&&(z=!0,Te=["[","]"]),de(h)){var rt=h.name?": "+h.name:"";R=" [Function"+rt+"]"}if(re(h)&&(R=" "+RegExp.prototype.toString.call(h)),_e(h)&&(R=" "+Date.prototype.toUTCString.call(h)),we(h)&&(R=" "+p(h)),L.length===0&&(!z||h.length==0))return Te[0]+R+Te[1];if(b<0)return re(h)?l.stylize(RegExp.prototype.toString.call(h),"regexp"):l.stylize("[Object]","special");l.seen.push(h);var Ne;return z?Ne=w(l,h,b,O,L):Ne=L.map(function(it){return E(l,h,b,O,it,z)}),l.seen.pop(),g(Ne,R,Te)}function f(l,h){if(_(h))return l.stylize("undefined","undefined");if(N(h)){var b="'"+JSON.stringify(h).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return l.stylize(b,"string")}if(X(h))return l.stylize(""+h,"number");if(T(h))return l.stylize(""+h,"boolean");if(D(h))return l.stylize("null","null")}function p(l){return"["+Error.prototype.toString.call(l)+"]"}function w(l,h,b,A,P){for(var L=[],O=0,C=h.length;O<C;++O)Pe(h,String(O))?L.push(E(l,h,b,A,String(O),!0)):L.push("");return P.forEach(function(R){R.match(/^\d+$/)||L.push(E(l,h,b,A,R,!0))}),L}function E(l,h,b,A,P,L){var O,C,R;if(R=Object.getOwnPropertyDescriptor(h,P)||{value:h[P]},R.get?R.set?C=l.stylize("[Getter/Setter]","special"):C=l.stylize("[Getter]","special"):R.set&&(C=l.stylize("[Setter]","special")),Pe(A,P)||(O="["+P+"]"),C||(l.seen.indexOf(R.value)<0?(D(b)?C=c(l,R.value,null):C=c(l,R.value,b-1),C.indexOf(`
3
3
  `)>-1&&(L?C=C.split(`
4
4
  `).map(function(z){return" "+z}).join(`
5
5
  `).slice(2):C=`
package/lib/es/index.js CHANGED
@@ -1253,7 +1253,7 @@ class To extends Je {
1253
1253
  };
1254
1254
  isBetPackQuestionReceived = ({ userId: e, eventId: r, organizationId: n }, i) => !!this.read(ce.BET_PACK_ITEM_RECEIVED, n, e, r, i);
1255
1255
  saveQuestionOpened = ({ userId: e, eventId: r, organizationId: n }, i) => {
1256
- this.write(ce.QUESTION_OPENED, n, e, r, i);
1256
+ this.write(ce.QUESTION_OPENED, n, e, r, i, "1");
1257
1257
  };
1258
1258
  isQuestionOpened = ({ userId: e, eventId: r, organizationId: n }, i) => !!this.read(ce.QUESTION_OPENED, n, e, r, i);
1259
1259
  saveOnboardingStatus = ({ userId: e, eventId: r, organizationId: n }, i) => {
package/package.json CHANGED
@@ -24,18 +24,18 @@
24
24
  "devDependencies": {
25
25
  "avvio": "=8.2.1",
26
26
  "tslib": "^2.7.0",
27
- "@streamlayer/feature-gamification": "^1.16.7",
28
- "@streamlayer/sdk-web-api": "^1.8.7",
29
- "@streamlayer/sdk-web-analytics": "^1.7.7",
30
- "@streamlayer/sdk-web-core": "^1.11.9",
31
- "@streamlayer/sdk-web-features": "^1.0.54",
32
- "@streamlayer/sdk-web-interfaces": "^1.4.20",
33
- "@streamlayer/sdk-web-logger": "^1.0.54",
34
- "@streamlayer/sdk-web-notifications": "^1.3.16",
35
- "@streamlayer/sdk-web-storage": "^1.0.54",
36
- "@streamlayer/sdk-web-types": "^1.10.11"
27
+ "@streamlayer/feature-gamification": "^1.16.8",
28
+ "@streamlayer/sdk-web-analytics": "^1.7.8",
29
+ "@streamlayer/sdk-web-api": "^1.8.8",
30
+ "@streamlayer/sdk-web-core": "^1.11.10",
31
+ "@streamlayer/sdk-web-features": "^1.0.55",
32
+ "@streamlayer/sdk-web-interfaces": "^1.4.21",
33
+ "@streamlayer/sdk-web-logger": "^1.0.55",
34
+ "@streamlayer/sdk-web-notifications": "^1.3.17",
35
+ "@streamlayer/sdk-web-storage": "^1.0.55",
36
+ "@streamlayer/sdk-web-types": "^1.10.12"
37
37
  },
38
- "version": "1.10.7",
38
+ "version": "1.10.8",
39
39
  "type": "module",
40
40
  "main": "./src/index.js",
41
41
  "typings": "./src/index.d.ts"