@frigade/js 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- var it=Object.defineProperty,st=Object.defineProperties;var ot=Object.getOwnPropertyDescriptors;var D=Object.getOwnPropertySymbols;var rt=Object.prototype.hasOwnProperty,at=Object.prototype.propertyIsEnumerable;var H=(c,s,t)=>s in c?it(c,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[s]=t,S=(c,s)=>{for(var t in s||(s={}))rt.call(s,t)&&H(c,t,s[t]);if(D)for(var t of D(s))at.call(s,t)&&H(c,t,s[t]);return c},I=(c,s)=>st(c,ot(s));var h=(c,s,t)=>new Promise((e,i)=>{var r=o=>{try{p(t.next(o))}catch(a){i(a)}},n=o=>{try{p(t.throw(o))}catch(a){i(a)}},p=o=>o.done?e(o.value):Promise.resolve(o.value).then(r,n);p((t=t.apply(c,s)).next())});import{v4 as j}from"uuid";var w={};function E(c){return`${c.__instanceId}-${c.apiKey}`}var T=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:M(),__instanceId:Math.random().toString(12).substring(4),generateGuestId:!0,__refreshIntervalInMS:100};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));this.config=S(S({},this.config),t)}fetch(s,t){return h(this,null,function*(){return this.config.__readOnly?y():L(this.getAPIUrl(s),S(S({keepalive:!0},t!=null?t:{}),N(this.config)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=E(this.config);if(!w[s])throw new Error("Frigade has not yet been initialized");return w[s]}};var F=class extends T{constructor({config:t,id:e}){super(t);this.props={};this._isVisible=!1;this.lastStepUpdate=new Map;this.id=e,this.init()}get isVisible(){return this._isVisible}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,r,n,p,o,a;let e=C(t!=null?t:this.getStatefulFlow());this.rawData=e,this.title=(i=e==null?void 0:e.data)==null?void 0:i.title,this.subtitle=(r=e==null?void 0:e.data)==null?void 0:r.subtitle,this.type=(n=e==null?void 0:e.data)==null?void 0:n.type,this.props=(o=(p=e==null?void 0:e.data)==null?void 0:p.props)!=null?o:{},this.version=e==null?void 0:e.version,this.isCompleted=e.$state.completed,this.isStarted=e.$state.started,this.isSkipped=e.$state.skipped,this._isVisible=e.$state.visible,e.data.steps.forEach((g,l)=>{var f;let d=this.initStepFromStatefulStep(g,l),u=(f=this.steps)==null?void 0:f.get(g.id);u&&Object.keys(d).forEach(b=>{u[b]=d[b]})}),this.getGlobalState().variables[this.id]?this.applyVariablesInternal((a=this.getGlobalState().variables[this.id])!=null?a:{}):this.applyVariablesInternal({})}initStepFromStatefulStep(t,e){return I(S({},t),{flow:this,$state:I(S({},t.$state),{lastActionAt:t.$state.lastActionAt?new Date(t.$state.lastActionAt):void 0}),order:e})}init(){let t=this.getStatefulFlow(),e=new Map;t.data.steps.forEach((i,r)=>{let n=this.initStepFromStatefulStep(i,r);n.start=o=>h(this,null,function*(){let a=this.steps.get(i.id);if(this.getCurrentStep().id===a.id&&a.$state.started)return;let g=C(this.getGlobalState().flowStates[this.id]);g.data.steps[a.order].$state.started=!0,g.data.steps[a.order].$state.lastActionAt=new Date,g.$state.lastActionAt=new Date,g.$state.currentStepId=a.id,g.$state.currentStepIndex=a.order,this.getGlobalState().flowStates[this.id]=g,this.resyncState(),yield this.sendFlowStateToAPI(R,o,a.id)});let p=(o,a,g=!0)=>h(this,null,function*(){let l=this.steps.get(i.id);if((l.$state.completed||l.$state.skipped)&&g){let f=this.getStepByIndex(l.order+1);for(;f&&!f.$state.visible&&f.order!==this.steps.size-1;)f=this.getStepByIndex(f.order+1);if(f){let b=C(this.getGlobalState().flowStates[this.id]);b.$state.currentStepId=this.getStepByIndex(l.order+1).id,b.$state.currentStepIndex=l.order+1,b.data.steps[l.order+1].$state.started=!0,this.getGlobalState().flowStates[this.id]=b,yield this.sendFlowStateToAPI(R,void 0,f.id),this.resyncState()}return}let d=this.getCurrentStepOrder()+1===this.getNumberOfAvailableSteps(),u=Array.from(this.steps.values()).filter(f=>f.$state.visible&&!f.$state.completed&&!f.$state.skipped).length===1&&d;if(g){let f=C(this.getGlobalState().flowStates[this.id]);if(f.$state.started=!0,o=="complete"?f.data.steps[l.order].$state.completed=!0:f.data.steps[l.order].$state.skipped=!0,f.data.steps[l.order].$state.started=!0,f.data.steps[l.order].$state.lastActionAt=new Date,!d){let b=this.getNextVisibleStepIndexAfterIndex(l.order);b!==-1&&(f.$state.currentStepId=this.getStepByIndex(b).id,f.$state.currentStepIndex=b,f.data.steps[b].$state.started=!0)}u&&(f.$state.completed=!0,f.$state.visible=!1),this.getGlobalState().flowStates[this.id]=f,this.resyncState(),u&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(o=="complete"?q:K,a,l.id),u&&(yield this.sendFlowStateToAPI(x,a))});n.complete=(o,a=!0)=>h(this,null,function*(){yield p("complete",o,a)}),n.skip=(o,a=!0)=>h(this,null,function*(){yield p("skip",o,a)}),n.reset=()=>h(this,null,function*(){let o=this.steps.get(i.id);if(!o.$state.completed)return;let a=C(this.getGlobalState().flowStates[this.id]);a.data.steps[o.order].$state.started=!1,a.data.steps[o.order].$state.completed=!1,a.data.steps[o.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=a,this.resyncState(),yield this.sendFlowStateToAPI(U,void 0,o.id)}),n.onStateChange=o=>{let a=g=>{if(g.id!==this.id)return;let l=g.steps.get(i.id),d=this.lastStepUpdate.get(o);(l.$state.completed!==(d==null?void 0:d.$state.completed)||l.$state.started!==(d==null?void 0:d.$state.started)||l.$state.visible!==(d==null?void 0:d.$state.visible)||l.$state.blocked!==(d==null?void 0:d.$state.blocked))&&(o(l,d!=null?d:C(l)),this.lastStepUpdate.set(o,C(l)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(o,a),this.getGlobalState().onFlowStateChangeHandlers.push(a)},n.removeStateChangeHandler=o=>{let a=this.getGlobalState().onStepStateChangeHandlerWrappers.get(o);a&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(g=>g!==a))},e.set(i.id,n)}),this.steps=e,this.resyncState()}start(t){return h(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(W,t))})}complete(t){return h(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(x,t))})}skip(t){return h(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(V,t))})}forward(t){return h(this,null,function*(){let e=this.getStepByIndex(this.getNextVisibleStepIndexAfterIndex(this.getCurrentStepIndex()));e&&(yield e.start(t))})}back(t){return h(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()-1);for(;e&&!e.$state.visible&&e.order!==0;)e=this.getStepByIndex(e.order-1);e&&(yield e.start(t))})}restart(){return h(this,null,function*(){yield this.sendFlowStateToAPI(B)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){let t=this.steps.get(this.getStatefulFlow().$state.currentStepId);return t||(t=this.getFirstVisibleStep(),t)}getFirstVisibleStep(){return this.getStepByIndex(this.getNextVisibleStepIndexAfterIndex(-1))}getNextVisibleStepIndexAfterIndex(t){let e=Array.from(this.steps.values());for(let i=t+1;i<e.length;i++)if(e[i].$state.visible)return i;return-1}getCurrentStepIndex(){let t=this.getCurrentStep();return Array.from(this.steps.keys()).indexOf(t.id)}getNumberOfCompletedSteps(){return Array.from(this.steps.values()).filter(t=>t.$state.completed).length}getNumberOfAvailableSteps(){return Array.from(this.steps.values()).filter(t=>t.$state.visible).length}getCurrentStepOrder(){let t=this.getCurrentStep();return Array.from(this.steps.values()).filter(e=>e.$state.visible).indexOf(t)}getProgress(){return(this.getNumberOfCompletedSteps()||0)/(this.getNumberOfAvailableSteps()||1)}onStateChange(t){let e=(i,r)=>{i.id===this.id&&(i.isCompleted!==(r==null?void 0:r.isCompleted)||i.isStarted!==(r==null?void 0:r.isStarted)||i.isSkipped!==(r==null?void 0:r.isSkipped)||i.isVisible!==(r==null?void 0:r.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(r==null?void 0:r.steps))&&t(i,r)};this.getGlobalState().onFlowStateChangeHandlerWrappers.set(t,e),this.getGlobalState().onFlowStateChangeHandlers.push(e)}removeStateChangeHandler(t){let e=this.getGlobalState().onFlowStateChangeHandlerWrappers.get(t);e&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(i=>i!==e))}applyVariables(t){this.applyVariablesInternal(t,!0)}applyVariablesInternal(t,e=!1){var n,p;let i=o=>{let a=o.match(/\${(.*?)}/g);return a&&a.forEach(g=>{let l=g.replace("${","").replace("}","");if(!t[l]){o=o.replace(g,"");return}o=o.replace(g,t[l])}),o};this.title=i((n=this.title)!=null?n:""),this.subtitle=i((p=this.subtitle)!=null?p:"");let r=o=>{o&&Object.keys(o).forEach(a=>{typeof o[a]=="string"?o[a]=i(o[a]):typeof o[a]=="object"?r(o[a]):Array.isArray(o[a])&&o[a].forEach(g=>{r(g)})})};this.steps&&this.steps.forEach(o=>{try{r(o)}catch(a){}}),this.getGlobalState().variables[this.id]=S(S({},this.getGlobalState().variables[this.id]),t),e&&this.resyncState()}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=C(this.getGlobalState().flowStates[this.id]);t.$state.completed=!0,t.$state.started=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowStarted(){let t=C(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return h(this,null,function*(){var p;let r=new Date;this.getGlobalState().lastFlowSyncDate[this.id]=r,this.getGlobalState().pendingRequests[this.id]=((p=this.getGlobalState().pendingRequests[this.id])!=null?p:0)+1;let n=yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,flowSlug:this.id,stepId:i,data:e||{},actionType:t,createdAt:r,context:A(this.getGlobalState())})});this.getGlobalState().pendingRequests[this.id]-=1,!(r<this.getGlobalState().lastFlowSyncDate[this.id]||this.getGlobalState().pendingRequests[this.id]>0)&&(yield this.getGlobalState().refreshStateFromAPI(n))})}optimisticallyMarkFlowSkipped(){let t=C(this.getGlobalState().flowStates[this.id]);t.$state.skipped=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}register(t){this.getGlobalState().collections.register(this.id,i=>{let r=this.getGlobalState().previousFlows.get(this.id);(r==null?void 0:r._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(n=>{n(this,r),this.getGlobalState().previousFlows.set(this.id,P(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var J="0.9.0";var U="NOT_STARTED_STEP",x="COMPLETED_FLOW",V="SKIPPED_FLOW",W="STARTED_FLOW",B="NOT_STARTED_FLOW",q="COMPLETED_STEP",K="SKIPPED_STEP",R="STARTED_STEP",z="frigade-guest-key",v="guest_",nt="get-cache-",_="fr-js-",Y="Redundant call to Frigade API removed";function P(c){return new F({config:c.config,id:c.id})}function C(c){return JSON.parse(JSON.stringify(c))}function N(c){var s,t;return{headers:{Authorization:`Bearer ${c.apiKey}`,"Content-Type":"application/json","x-frigade-sdk-version":(s=c.__platformVersion)!=null?s:J,"x-frigade-sdk-platform":(t=c.__platformName)!=null?t:"Javascript"}}}function lt(c){if(m())try{return window.localStorage.getItem(`${_}${c}`)}catch(s){return console.debug("Error getting localStorage:",s),null}return null}function ct(c,s){if(m())try{window.localStorage.setItem(`${_}${c}`,s)}catch(t){console.debug("Error setting localStorage:",t)}}function X(){Object.keys(w).forEach(c=>{c.startsWith(nt)&&delete w[c]})}function Q(){m()&&Object.keys(window.localStorage).forEach(c=>{c.startsWith(_)&&window.localStorage.removeItem(c)})}var G=class{constructor(){this.queue=[];this.ttlInMS=250;this.cacheSize=10}push(s,t){let e=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:e.getTime(),response:t!=null?t:null})}hasIdenticalRecentCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.find(e=>e.call===s)}hasCall(s){return this.queue.find(t=>t.call===s)}cancelAllPendingRequests(){this.queue=[]}};globalThis.callQueue=new G;function L(c,s){return h(this,null,function*(){var r;if(typeof globalThis.fetch!="function")return y("- Attempted to call fetch() in an environment that doesn't support it.");let t=`${c}${JSON.stringify((r=s.body)!=null?r:{})}`,e,i=m()&&s&&s.body&&s.method==="POST";if(i){let n=globalThis.callQueue.hasIdenticalRecentCall(t);n!=null&&n.response!=null&&(e=(yield n.response).clone())}if(!e)try{let n=fetch(c,s);i&&globalThis.callQueue.push(t,n.then(p=>p.clone()).catch(()=>y())),e=yield n,i&&!globalThis.callQueue.hasCall(t)&&(e=y(Y))}catch(n){return y(n)}if(!e)return y("Received an empty response");if(e.status>=400)return y(e.statusText);try{if(e.status===204)return y();let n;try{n=yield e.json()}catch(p){return y()}return n.error?y(n.error):n}catch(n){return y(n)}})}function y(c){return c&&(c===Y?console.debug(c):console.warn("Call to Frigade failed:",c)),{json:()=>({}),clone:()=>({})}}function M(){if(m()){let c=lt(z);return c||(c=`${v}${j()}`,ct(z,c)),c}else return`${v}${j()}`}function m(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function A(c){let s={registeredCollectionIds:Array.from(c.registeredCollectionIds)};return m()?S({url:c.currentUrl,userAgent:navigator.userAgent},s):s}var O=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.collections=new Map;this.flowsInCollections=new Set;this.hasChanges=!1;this.ingestCollectionsData(s)}getCollection(s){return this.collections.get(s)}getCollections(){return this.collections}collectionsHaveChanged(){return this.hasChanges}ingestCollectionsData(s){if(this.hasChanges=!0,this.checkIfCollectionsHaveChanged(s),!!this.hasChanges){this.collections=s;for(let[,t]of this.collections)for(let{flowId:e}of t.flows)this.flowsInCollections.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processCollections()),this.fireCallbacks()}}checkIfCollectionsHaveChanged(s){let t=this.collections,e=s;t.size!==e.size&&(this.hasChanges=!0);for(let[i,r]of t){let n=e.get(i);if(r.flows.length!==n.flows.length){this.hasChanges=!0;break}for(let p=0;p<r.flows.length;p++)if(r.flows[p].flowId!==n.flows[p].flowId||r.flows[p].visible!==n.flows[p].visible){this.hasChanges=!0;break}}}fireCallbacks(){for(let[s,{callback:t}]of this.registry)typeof t=="function"&&t(this.isFlowVisible(s))}isFlowVisible(s){let t=this.registry.get(s),e=this.flowsInCollections.has(s);return t==null||!e?!0:t.visible}lockRegistryState(){this.registryStateLocked=!0}unlockRegistryState(){this.registryStateLocked=!1}resetRegistryState(){for(let[s,t]of this.registry)t.visible=!1,t.visited=!1,this.registry.set(s,t)}processCollections(){for(let[,s]of this.collections)for(let{flowId:t,visible:e}of s.flows){let i=this.registry.get(t);if(i==null)continue;if(e===!1&&i.visible!==!0){this.visit(t,!1);continue}if(i.visited&&this.registryStateLocked)continue;let r=s.flows.map(({flowId:n})=>n).filter(n=>n!==t);this.visit(t)}}register(s,t){if(Array.isArray(s)){this.batchRegister(s);return}this.registry.set(s,{callback:t!=null?t:()=>{},visible:!1,visited:!1}),this.registryStateLocked||this.resetRegistryState(),this.processCollections(),this.fireCallbacks()}batchRegister(s){s.forEach(([t,e])=>{this.registry.set(t,{callback:e!=null?e:()=>{},visible:!1,visited:!1})}),this.registryStateLocked||this.resetRegistryState(),this.processCollections(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processCollections(),this.fireCallbacks()}visit(s,t=!0){var i;let e=(i=this.registry.get(s))!=null?i:{callback:()=>{},visible:t,visited:!0};e.visible=t,e.visited=!0,this.registry.set(s,e)}};var $=class extends T{constructor(t,e){super(S({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.eventHandlers=new Map;this.refreshTimeout=null;this.queuedRefresh=!1;this.visibilityChangeHandler=()=>{document.visibilityState==="visible"&&this.queueRefreshStateFromAPI()};this.init(this.config),m()&&this.config.syncOnWindowUpdates!==!1&&(document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.navigation&&window.navigation.addEventListener("navigate",i=>h(this,null,function*(){try{if(this.getGlobalState().currentUrl===i.destination.url||i.destination.url&&this.getGlobalState().currentUrl&&i.destination.url.split("#")[0]===this.getGlobalState().currentUrl.split("#")[0])return;this.queueRefreshStateFromAPI()}catch(r){}})))}queueRefreshStateFromAPI(){this.queuedRefresh=!0,!this.refreshTimeout&&(this.refreshTimeout=setTimeout(()=>h(this,null,function*(){this.queuedRefresh&&(this.getGlobalState().currentUrl=window.location.href,yield this.refreshStateFromAPI(),this.queuedRefresh=!1),this.refreshTimeout=null}),this.getGlobalState().config.__refreshIntervalInMS))}getConfig(){return this.config}destroy(){if(m()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=E(this.config);w[t]&&(w[t].onFlowStateChangeHandlers=[])}}init(t){return h(this,null,function*(){if(this.updateConfig(S(S({},this.config),t)),!!this.config.userId)return this.initPromise=(()=>h(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(v)||(this.config.userId&&this.config.groupId?yield this.session({userId:this.config.userId,groupId:this.config.groupId,userProperties:this.config.userProperties,groupProperties:this.config.groupProperties}):this.config.userId&&(yield this.session({userId:this.config.userId,userProperties:this.config.userProperties}))),yield this.refreshStateFromAPI()}))(),this.initPromise})}identify(t,e){return h(this,null,function*(){t!==this.config.userId&&(yield this.updateConfig(I(S({},this.config),{userId:t})),yield this.reload()),yield this.initIfNeeded(),(yield this.session({userId:this.config.userId,userProperties:e}))&&(yield this.resync())})}group(t,e){return h(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(I(S({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties:e}),yield this.resync()})}track(t,e){return h(this,null,function*(){if(yield this.initIfNeeded(),!t){console.error("Event name is required to track an event");return}this.config.userId&&this.config.groupId?yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupEvents:[{event:t,properties:e}],userEvents:[{event:t,properties:e}]}):this.config.userId&&(yield this.session({userId:this.config.userId,userEvents:[{event:t,properties:e}]})),yield this.resync()})}session(t){return h(this,null,function*(){let e=this.lastSessionDTO;return e&&JSON.stringify(e)===JSON.stringify(t)?!1:(yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)}),this.lastSessionDTO=t,!0)})}isReady(){return!!(this.config.__instanceId&&this.config.apiKey&&this.initPromise)}getFlow(t){return h(this,null,function*(){if(!(this.getConfig().generateGuestId===!1&&this.getConfig().userId&&this.getConfig().userId.startsWith(v)))return yield this.initIfNeeded(),this.getFlowSync(t)})}getFlowSync(t){return this.flows.find(e=>e.id==t)}getFlows(){return h(this,null,function*(){var t;return yield this.initIfNeeded(),this.config.generateGuestId===!1&&((t=this.getConfig().userId)!=null&&t.startsWith(v))?[]:this.flows})}getCollection(t){return h(this,null,function*(){yield this.initIfNeeded();let e=this.getGlobalState().collections.getCollection(t);if(e==null)return;this.registerCollection(t);let i=yield Promise.all(e.flows.map(r=>h(this,null,function*(){return I(S({},r),{flow:yield this.getFlow(r.flowId)})})));return e.flows=i,e})}registerCollection(t){return h(this,null,function*(){yield this.initIfNeeded(),t&&this.getGlobalState().registeredCollectionIds.add(t)})}getCollectionSync(t){let e=this.getGlobalState().collections.getCollection(t);if(e!=null)return this.getGlobalState().registeredCollectionIds.add(t),e}getCollectionsSync(){return this.getGlobalState().collections.getCollections()}getCollections(){return h(this,null,function*(){if(yield this.initIfNeeded(),!this.config.userId&&this.config.generateGuestId===!1)return;let t=this.getGlobalState().collections.getCollections();if(t!=null)return t})}reload(t){return h(this,null,function*(){Q(),X(),t&&(yield this.updateConfig(t),this.mockFlowStates(E(this.config))),this.initPromise=null,yield this.init(this.config),this.triggerAllLegacyEventHandlers(),this.triggerAllEventHandlers()})}triggerAllLegacyEventHandlers(){this.flows.forEach(t=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(e=>{let i=this.getGlobalState().previousFlows.get(t.id);e(t,i),this.getGlobalState().previousFlows.set(t.id,P(t))})})}triggerAllEventHandlers(){this.flows.forEach(t=>{let e=this.getGlobalState().previousFlows.get(t.id);this.triggerEventHandlers(t.rawData,e==null?void 0:e.rawData)})}resync(){return h(this,null,function*(){yield this.refreshStateFromAPI()})}onStateChange(t){return h(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}on(t,e){return h(this,null,function*(){var i;this.eventHandlers.set(t,[...(i=this.eventHandlers.get(t))!=null?i:[],e])})}off(t,e){return h(this,null,function*(){var i;this.eventHandlers.set(t,((i=this.eventHandlers.get(t))!=null?i:[]).filter(r=>r!==e))})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return h(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return h(this,null,function*(){return this.initPromise?this.initPromise:this.init(this.config)})}refreshStateFromAPI(){return h(this,null,function*(){let t=E(this.config);if(!w[t]){let e=this,i={set:function(r,n,p){if(r[n]){let o=r[n],a=p;JSON.stringify(o)!==JSON.stringify(a)&&(e.triggerDeprecatedEventHandlers(a,o),e.triggerEventHandlers(a,o))}return r[n]=p,!0}};if(w[t]={refreshStateFromAPI:()=>h(this,null,function*(){}),collections:new O(new Map),registeredCollectionIds:new Set,flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config,currentUrl:m()?window.location.href:"",pendingRequests:new Map,lastFlowSyncDate:new Map},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(t);return}w[t].refreshStateFromAPI=r=>h(this,null,function*(){var o,a;if(this.config.__readOnly)return;let n=r||(yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,context:A(this.getGlobalState())})})),p=new Map;(a=(o=n.collections)==null?void 0:o.computedOrder)==null||a.forEach(({allowedComponents:g,collectionId:l,collectionType:d,flowId:u,visible:f})=>{var k;let b=(k=p.get(l))!=null?k:{allowedComponents:g,collectionType:d,flows:[]};b.flows.push({flowId:u,visible:f}),p.set(l,b)}),p.size>0&&(w[t].collections.ingestCollectionsData(p),w[t].collections.collectionsHaveChanged()&&!r&&(this.triggerAllLegacyEventHandlers(),this.triggerAllEventHandlers())),n&&n.eligibleFlows?(n.eligibleFlows.forEach(g=>{w[t].flowStates[g.flowSlug]=g,this.flows.find(l=>l.id==g.flowSlug)?this.flows.forEach(l=>{l.id==g.flowSlug&&l.resyncState(g)}):this.flows.push(new F({config:this.config,id:g.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield w[t].refreshStateFromAPI(void 0)})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{w[t].flowStates[e]=this.config.__flowStateOverrides[e],this.flows.find(i=>i.id==e)?this.flows.forEach(i=>{i.id==e&&i.resyncState(this.config.__flowStateOverrides[e])}):this.flows.push(new F({config:this.config,id:e}))})}updateConfig(t){return h(this,null,function*(){this.config=S(S({},this.config),t),w[E(this.config)]&&(this.getGlobalState().config=this.config)})}triggerDeprecatedEventHandlers(t,e){return h(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(r=>{let n=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),r(i,n),this.getGlobalState().previousFlows.set(i.id,P(i))})})})}triggerEventHandlers(t,e){var i,r,n,p;if(t){for(let o of this.flows)if(o.id==t.flowSlug){let a=this.getGlobalState().previousFlows.get(o.id);o.resyncState(t);for(let[g,l]of this.eventHandlers.entries())switch(g){case"flow.complete":t.$state.completed&&(e==null?void 0:e.$state.completed)===!1&&l.forEach(d=>d(g,o,a));break;case"flow.restart":!t.$state.started&&(e==null?void 0:e.$state.started)===!0&&l.forEach(d=>d(g,o,a));break;case"flow.skip":t.$state.skipped&&(e==null?void 0:e.$state.skipped)===!1&&l.forEach(d=>d(g,o,a));break;case"flow.start":t.$state.started&&(e==null?void 0:e.$state.started)===!1&&l.forEach(d=>d(g,o,a));break;case"step.complete":for(let d of(i=t.data.steps)!=null?i:[])d.$state.completed&&!(e!=null&&e.data.steps.find(u=>u.id===d.id&&u.$state.completed))&&l.forEach(u=>u(g,o,a,o.steps.get(d.id)));break;case"step.reset":for(let d of(r=t.data.steps)!=null?r:[]){let u=e==null?void 0:e.data.steps.find(f=>f.id===d.id);d.$state.started==!1&&!d.$state.lastActionAt&&(u!=null&&u.$state.started)&&(u!=null&&u.$state.lastActionAt)&&l.forEach(f=>f(g,o,a,o.steps.get(d.id)))}break;case"step.skip":for(let d of(n=t.data.steps)!=null?n:[])d.$state.skipped&&!(e!=null&&e.data.steps.find(u=>u.id===d.id&&u.$state.skipped))&&l.forEach(u=>u(g,o,a,o.steps.get(d.id)));break;case"step.start":for(let d of(p=t.data.steps)!=null?p:[])d.$state.started&&(e!=null&&e.data.steps.find(u=>u.id===d.id&&u.$state.started===!1))&&l.forEach(u=>u(g,o,a,o.steps.get(d.id)));break;case"flow.any":JSON.stringify(t)!==JSON.stringify(e!=null?e:{})&&l.forEach(d=>d(g,o,a));break}this.getGlobalState().previousFlows.set(o.id,P(o))}}}batchRegister(t){return h(this,null,function*(){let e=t.map(n=>h(this,[n],function*([i,r]){let p=yield this.getFlow(i);return[i,a=>{let g=this.getGlobalState().previousFlows.get(i);(g==null?void 0:g.isVisible)!==a&&this.getGlobalState().onFlowStateChangeHandlers.forEach(l=>{l(p,g),this.getGlobalState().previousFlows.set(i,P(p))}),r==null||r(a)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};var Z=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(Z||{}),tt=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(tt||{});var et=(l=>(l.ANNOUNCEMENT="ANNOUNCEMENT",l.CHECKLIST="CHECKLIST",l.FORM="FORM",l.TOUR="TOUR",l.SUPPORT="SUPPORT",l.CUSTOM="CUSTOM",l.BANNER="BANNER",l.EMBEDDED_TIP="EMBEDDED_TIP",l.NPS_SURVEY="NPS_SURVEY",l.SURVEY="SURVEY",l.CARD="CARD",l))(et||{});export{F as Flow,tt as FlowStatus,et as FlowType,$ as Frigade,Z as TriggerType};
2
+ var st=Object.defineProperty,ot=Object.defineProperties;var rt=Object.getOwnPropertyDescriptors;var N=Object.getOwnPropertySymbols;var at=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var H=(c,s,t)=>s in c?st(c,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[s]=t,S=(c,s)=>{for(var t in s||(s={}))at.call(s,t)&&H(c,t,s[t]);if(N)for(var t of N(s))nt.call(s,t)&&H(c,t,s[t]);return c},I=(c,s)=>ot(c,rt(s));var h=(c,s,t)=>new Promise((e,i)=>{var r=o=>{try{p(t.next(o))}catch(a){i(a)}},n=o=>{try{p(t.throw(o))}catch(a){i(a)}},p=o=>o.done?e(o.value):Promise.resolve(o.value).then(r,n);p((t=t.apply(c,s)).next())});var L=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(L||{}),M=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(M||{});var U=(l=>(l.ANNOUNCEMENT="ANNOUNCEMENT",l.CHECKLIST="CHECKLIST",l.FORM="FORM",l.TOUR="TOUR",l.SUPPORT="SUPPORT",l.CUSTOM="CUSTOM",l.BANNER="BANNER",l.EMBEDDED_TIP="EMBEDDED_TIP",l.NPS_SURVEY="NPS_SURVEY",l.SURVEY="SURVEY",l.CARD="CARD",l))(U||{});import{v4 as Q}from"uuid";var w={};function E(c){return`${c.__instanceId}-${c.apiKey}`}var T=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:B(),__instanceId:Math.random().toString(12).substring(4),generateGuestId:!0,__refreshIntervalInMS:100};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));this.config=S(S({},this.config),t)}fetch(s,t){return h(this,null,function*(){return this.config.__readOnly?y():W(this.getAPIUrl(s),S(S({keepalive:!0},t!=null?t:{}),V(this.config)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=E(this.config);if(!w[s])throw new Error("Frigade has not yet been initialized");return w[s]}};var F=class extends T{constructor({config:t,id:e}){super(t);this.props={};this._isVisible=!1;this.lastStepUpdate=new Map;this.id=e,this.init()}get isVisible(){return this._isVisible}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,r,n,p,o,a;let e=C(t!=null?t:this.getStatefulFlow());this.rawData=e,this.title=(i=e==null?void 0:e.data)==null?void 0:i.title,this.subtitle=(r=e==null?void 0:e.data)==null?void 0:r.subtitle,this.type=(n=e==null?void 0:e.data)==null?void 0:n.type,this.props=(o=(p=e==null?void 0:e.data)==null?void 0:p.props)!=null?o:{},this.version=e==null?void 0:e.version,this.isCompleted=e.$state.completed,this.isStarted=e.$state.started,this.isSkipped=e.$state.skipped,this._isVisible=e.$state.visible,e.data.steps.forEach((g,l)=>{var f;let d=this.initStepFromStatefulStep(g,l),u=(f=this.steps)==null?void 0:f.get(g.id);u&&Object.keys(d).forEach(b=>{u[b]=d[b]})}),this.getGlobalState().variables[this.id]?this.applyVariablesInternal((a=this.getGlobalState().variables[this.id])!=null?a:{}):this.applyVariablesInternal({})}initStepFromStatefulStep(t,e){return I(S({},t),{flow:this,$state:I(S({},t.$state),{lastActionAt:t.$state.lastActionAt?new Date(t.$state.lastActionAt):void 0}),order:e})}init(){let t=this.getStatefulFlow(),e=new Map;t.data.steps.forEach((i,r)=>{let n=this.initStepFromStatefulStep(i,r);n.start=o=>h(this,null,function*(){let a=this.steps.get(i.id);if(this.getCurrentStep().id===a.id&&a.$state.started)return;let g=C(this.getGlobalState().flowStates[this.id]);g.data.steps[a.order].$state.started=!0,g.data.steps[a.order].$state.lastActionAt=new Date,g.$state.lastActionAt=new Date,g.$state.currentStepId=a.id,g.$state.currentStepIndex=a.order,this.getGlobalState().flowStates[this.id]=g,this.resyncState(),yield this.sendFlowStateToAPI(x,o,a.id)});let p=(o,a,g=!0)=>h(this,null,function*(){let l=this.steps.get(i.id);if((l.$state.completed||l.$state.skipped)&&g){let f=this.getStepByIndex(l.order+1);for(;f&&!f.$state.visible&&f.order!==this.steps.size-1;)f=this.getStepByIndex(f.order+1);if(f){let b=C(this.getGlobalState().flowStates[this.id]);b.$state.currentStepId=this.getStepByIndex(l.order+1).id,b.$state.currentStepIndex=l.order+1,b.data.steps[l.order+1].$state.started=!0,this.getGlobalState().flowStates[this.id]=b,yield this.sendFlowStateToAPI(x,void 0,f.id),this.resyncState()}return}let d=this.getCurrentStepOrder()+1===this.getNumberOfAvailableSteps(),u=Array.from(this.steps.values()).filter(f=>f.$state.visible&&!f.$state.completed&&!f.$state.skipped).length===1&&d;if(g){let f=C(this.getGlobalState().flowStates[this.id]);if(f.$state.started=!0,o=="complete"?f.data.steps[l.order].$state.completed=!0:f.data.steps[l.order].$state.skipped=!0,f.data.steps[l.order].$state.started=!0,f.data.steps[l.order].$state.lastActionAt=new Date,!d){let b=this.getNextVisibleStepIndexAfterIndex(l.order);b!==-1&&(f.$state.currentStepId=this.getStepByIndex(b).id,f.$state.currentStepIndex=b,f.data.steps[b].$state.started=!0)}u&&(f.$state.completed=!0,f.$state.visible=!1),this.getGlobalState().flowStates[this.id]=f,this.resyncState(),u&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(o=="complete"?z:Y,a,l.id),u&&(yield this.sendFlowStateToAPI(O,a))});n.complete=(o,a=!0)=>h(this,null,function*(){yield p("complete",o,a)}),n.skip=(o,a=!0)=>h(this,null,function*(){yield p("skip",o,a)}),n.reset=()=>h(this,null,function*(){let o=this.steps.get(i.id);if(!o.$state.completed)return;let a=C(this.getGlobalState().flowStates[this.id]);a.data.steps[o.order].$state.started=!1,a.data.steps[o.order].$state.completed=!1,a.data.steps[o.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=a,this.resyncState(),yield this.sendFlowStateToAPI(q,void 0,o.id)}),n.onStateChange=o=>{let a=g=>{if(g.id!==this.id)return;let l=g.steps.get(i.id),d=this.lastStepUpdate.get(o);(l.$state.completed!==(d==null?void 0:d.$state.completed)||l.$state.started!==(d==null?void 0:d.$state.started)||l.$state.visible!==(d==null?void 0:d.$state.visible)||l.$state.blocked!==(d==null?void 0:d.$state.blocked))&&(o(l,d!=null?d:C(l)),this.lastStepUpdate.set(o,C(l)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(o,a),this.getGlobalState().onFlowStateChangeHandlers.push(a)},n.removeStateChangeHandler=o=>{let a=this.getGlobalState().onStepStateChangeHandlerWrappers.get(o);a&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(g=>g!==a))},e.set(i.id,n)}),this.steps=e,this.resyncState()}start(t){return h(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(J,t))})}complete(t){return h(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(O,t))})}skip(t){return h(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(K,t))})}forward(t){return h(this,null,function*(){let e=this.getStepByIndex(this.getNextVisibleStepIndexAfterIndex(this.getCurrentStepIndex()));e&&(yield e.start(t))})}back(t){return h(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()-1);for(;e&&!e.$state.visible&&e.order!==0;)e=this.getStepByIndex(e.order-1);e&&(yield e.start(t))})}restart(){return h(this,null,function*(){yield this.sendFlowStateToAPI(j)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){let t=this.steps.get(this.getStatefulFlow().$state.currentStepId);return t||(t=this.getFirstVisibleStep(),t)}getFirstVisibleStep(){return this.getStepByIndex(this.getNextVisibleStepIndexAfterIndex(-1))}getNextVisibleStepIndexAfterIndex(t){let e=Array.from(this.steps.values());for(let i=t+1;i<e.length;i++)if(e[i].$state.visible)return i;return-1}getCurrentStepIndex(){let t=this.getCurrentStep();return Array.from(this.steps.keys()).indexOf(t.id)}getNumberOfCompletedSteps(){return Array.from(this.steps.values()).filter(t=>t.$state.completed).length}getNumberOfAvailableSteps(){return Array.from(this.steps.values()).filter(t=>t.$state.visible).length}getCurrentStepOrder(){let t=this.getCurrentStep();return Array.from(this.steps.values()).filter(e=>e.$state.visible).indexOf(t)}getProgress(){return(this.getNumberOfCompletedSteps()||0)/(this.getNumberOfAvailableSteps()||1)}onStateChange(t){let e=(i,r)=>{i.id===this.id&&(i.isCompleted!==(r==null?void 0:r.isCompleted)||i.isStarted!==(r==null?void 0:r.isStarted)||i.isSkipped!==(r==null?void 0:r.isSkipped)||i.isVisible!==(r==null?void 0:r.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(r==null?void 0:r.steps))&&t(i,r)};this.getGlobalState().onFlowStateChangeHandlerWrappers.set(t,e),this.getGlobalState().onFlowStateChangeHandlers.push(e)}removeStateChangeHandler(t){let e=this.getGlobalState().onFlowStateChangeHandlerWrappers.get(t);e&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(i=>i!==e))}applyVariables(t){this.applyVariablesInternal(t,!0)}applyVariablesInternal(t,e=!1){var n,p;let i=o=>{let a=o.match(/\${(.*?)}/g);return a&&a.forEach(g=>{let l=g.replace("${","").replace("}","");if(!t[l]){o=o.replace(g,"");return}o=o.replace(g,t[l])}),o};this.title=i((n=this.title)!=null?n:""),this.subtitle=i((p=this.subtitle)!=null?p:"");let r=o=>{o&&Object.keys(o).forEach(a=>{typeof o[a]=="string"?o[a]=i(o[a]):typeof o[a]=="object"?r(o[a]):Array.isArray(o[a])&&o[a].forEach(g=>{r(g)})})};this.steps&&this.steps.forEach(o=>{try{r(o)}catch(a){}}),this.getGlobalState().variables[this.id]=S(S({},this.getGlobalState().variables[this.id]),t),e&&this.resyncState()}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=C(this.getGlobalState().flowStates[this.id]);t.$state.completed=!0,t.$state.started=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowStarted(){let t=C(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return h(this,null,function*(){var p;let r=new Date;this.getGlobalState().lastFlowSyncDate[this.id]=r,this.getGlobalState().pendingRequests[this.id]=((p=this.getGlobalState().pendingRequests[this.id])!=null?p:0)+1;let n=yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,flowSlug:this.id,stepId:i,data:e||{},actionType:t,createdAt:r,context:A(this.getGlobalState())})});this.getGlobalState().pendingRequests[this.id]-=1,!(r<this.getGlobalState().lastFlowSyncDate[this.id]||this.getGlobalState().pendingRequests[this.id]>0)&&(yield this.getGlobalState().refreshStateFromAPI(n))})}optimisticallyMarkFlowSkipped(){let t=C(this.getGlobalState().flowStates[this.id]);t.$state.skipped=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}register(t){this.getGlobalState().collections.register(this.id,i=>{let r=this.getGlobalState().previousFlows.get(this.id);(r==null?void 0:r._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(n=>{n(this,r),this.getGlobalState().previousFlows.set(this.id,P(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var X="0.9.1";var q="NOT_STARTED_STEP",O="COMPLETED_FLOW",K="SKIPPED_FLOW",J="STARTED_FLOW",j="NOT_STARTED_FLOW",z="COMPLETED_STEP",Y="SKIPPED_STEP",x="STARTED_STEP",Z="frigade-guest-key",v="guest_",lt="get-cache-",$="fr-js-",tt="Redundant call to Frigade API removed";function P(c){return new F({config:c.config,id:c.id})}function C(c){return JSON.parse(JSON.stringify(c))}function V(c){var s,t;return{headers:{Authorization:`Bearer ${c.apiKey}`,"Content-Type":"application/json","x-frigade-sdk-version":(s=c.__platformVersion)!=null?s:X,"x-frigade-sdk-platform":(t=c.__platformName)!=null?t:"Javascript"}}}function ct(c){if(m())try{return window.localStorage.getItem(`${$}${c}`)}catch(s){return console.debug("Error getting localStorage:",s),null}return null}function dt(c,s){if(m())try{window.localStorage.setItem(`${$}${c}`,s)}catch(t){console.debug("Error setting localStorage:",t)}}function et(){Object.keys(w).forEach(c=>{c.startsWith(lt)&&delete w[c]})}function it(){m()&&Object.keys(window.localStorage).forEach(c=>{c.startsWith($)&&window.localStorage.removeItem(c)})}var G=class{constructor(){this.queue=[];this.ttlInMS=250;this.cacheSize=10}push(s,t){let e=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:e.getTime(),response:t!=null?t:null})}hasIdenticalRecentCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.find(e=>e.call===s)}hasCall(s){return this.queue.find(t=>t.call===s)}cancelAllPendingRequests(){this.queue=[]}};globalThis.callQueue=new G;function W(c,s){return h(this,null,function*(){var r;if(typeof globalThis.fetch!="function")return y("- Attempted to call fetch() in an environment that doesn't support it.");let t=`${c}${JSON.stringify((r=s.body)!=null?r:{})}`,e,i=m()&&s&&s.body&&s.method==="POST";if(i){let n=globalThis.callQueue.hasIdenticalRecentCall(t);n!=null&&n.response!=null&&(e=(yield n.response).clone())}if(!e)try{let n=fetch(c,s);i&&globalThis.callQueue.push(t,n.then(p=>p.clone()).catch(()=>y())),e=yield n,i&&!globalThis.callQueue.hasCall(t)&&(e=y(tt))}catch(n){return y(n)}if(!e)return y("Received an empty response");if(e.status>=400)return y(e.statusText);try{if(e.status===204)return y();let n;try{n=yield e.json()}catch(p){return y()}return n.error?y(n.error):n}catch(n){return y(n)}})}function y(c){return c&&(c===tt?console.debug(c):console.warn("Call to Frigade failed:",c)),{json:()=>({}),clone:()=>({})}}function B(){if(m()){let c=ct(Z);return c||(c=`${v}${Q()}`,dt(Z,c)),c}else return`${v}${Q()}`}function m(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function A(c){let s={registeredCollectionIds:Array.from(c.registeredCollectionIds)};return m()?S({url:c.currentUrl,userAgent:navigator.userAgent},s):s}var R=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.collections=new Map;this.flowsInCollections=new Set;this.hasChanges=!1;this.ingestCollectionsData(s)}getCollection(s){return this.collections.get(s)}getCollections(){return this.collections}collectionsHaveChanged(){return this.hasChanges}ingestCollectionsData(s){if(this.hasChanges=!0,this.checkIfCollectionsHaveChanged(s),!!this.hasChanges){this.collections=s;for(let[,t]of this.collections)for(let{flowId:e}of t.flows)this.flowsInCollections.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processCollections()),this.fireCallbacks()}}checkIfCollectionsHaveChanged(s){let t=this.collections,e=s;t.size!==e.size&&(this.hasChanges=!0);for(let[i,r]of t){let n=e.get(i);if(r.flows.length!==n.flows.length){this.hasChanges=!0;break}for(let p=0;p<r.flows.length;p++)if(r.flows[p].flowId!==n.flows[p].flowId||r.flows[p].visible!==n.flows[p].visible){this.hasChanges=!0;break}}}fireCallbacks(){for(let[s,{callback:t}]of this.registry)typeof t=="function"&&t(this.isFlowVisible(s))}isFlowVisible(s){let t=this.registry.get(s),e=this.flowsInCollections.has(s);return t==null||!e?!0:t.visible}lockRegistryState(){this.registryStateLocked=!0}unlockRegistryState(){this.registryStateLocked=!1}resetRegistryState(){for(let[s,t]of this.registry)t.visible=!1,t.visited=!1,this.registry.set(s,t)}processCollections(){for(let[,s]of this.collections)for(let{flowId:t,visible:e}of s.flows){let i=this.registry.get(t);if(i==null)continue;if(e===!1&&i.visible!==!0){this.visit(t,!1);continue}if(i.visited&&this.registryStateLocked)continue;let r=s.flows.map(({flowId:n})=>n).filter(n=>n!==t);this.visit(t)}}register(s,t){if(Array.isArray(s)){this.batchRegister(s);return}this.registry.set(s,{callback:t!=null?t:()=>{},visible:!1,visited:!1}),this.registryStateLocked||this.resetRegistryState(),this.processCollections(),this.fireCallbacks()}batchRegister(s){s.forEach(([t,e])=>{this.registry.set(t,{callback:e!=null?e:()=>{},visible:!1,visited:!1})}),this.registryStateLocked||this.resetRegistryState(),this.processCollections(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processCollections(),this.fireCallbacks()}visit(s,t=!0){var i;let e=(i=this.registry.get(s))!=null?i:{callback:()=>{},visible:t,visited:!0};e.visible=t,e.visited=!0,this.registry.set(s,e)}};var D=class extends T{constructor(t,e){super(S({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.eventHandlers=new Map;this.refreshTimeout=null;this.queuedRefresh=!1;this.visibilityChangeHandler=()=>{document.visibilityState==="visible"&&this.queueRefreshStateFromAPI()};this.init(this.config),m()&&this.config.syncOnWindowUpdates!==!1&&(document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.navigation&&window.navigation.addEventListener("navigate",i=>h(this,null,function*(){try{if(this.getGlobalState().currentUrl===i.destination.url||i.destination.url&&this.getGlobalState().currentUrl&&i.destination.url.split("#")[0]===this.getGlobalState().currentUrl.split("#")[0])return;this.queueRefreshStateFromAPI()}catch(r){}})))}queueRefreshStateFromAPI(){var t;this.queuedRefresh=!0,!this.refreshTimeout&&(this.refreshTimeout=setTimeout(()=>h(this,null,function*(){this.queuedRefresh&&(this.getGlobalState().currentUrl=window.location.href,yield this.refreshStateFromAPI(),this.queuedRefresh=!1),this.refreshTimeout=null}),(t=this.getGlobalState().config.__refreshIntervalInMS)!=null?t:100))}getConfig(){return this.config}destroy(){if(m()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=E(this.config);w[t]&&(w[t].onFlowStateChangeHandlers=[])}}init(t){return h(this,null,function*(){if(this.updateConfig(S(S({},this.config),t)),!!this.config.userId)return this.initPromise=(()=>h(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(v)||(this.config.userId&&this.config.groupId?yield this.session({userId:this.config.userId,groupId:this.config.groupId,userProperties:this.config.userProperties,groupProperties:this.config.groupProperties}):this.config.userId&&(yield this.session({userId:this.config.userId,userProperties:this.config.userProperties}))),yield this.refreshStateFromAPI()}))(),this.initPromise})}identify(t,e){return h(this,null,function*(){t!==this.config.userId&&(yield this.updateConfig(I(S({},this.config),{userId:t})),yield this.reload()),yield this.initIfNeeded(),(yield this.session({userId:this.config.userId,userProperties:e}))&&(yield this.resync())})}group(t,e){return h(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(I(S({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties:e}),yield this.resync()})}track(t,e){return h(this,null,function*(){if(yield this.initIfNeeded(),!t){console.error("Event name is required to track an event");return}this.config.userId&&this.config.groupId?yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupEvents:[{event:t,properties:e}],userEvents:[{event:t,properties:e}]}):this.config.userId&&(yield this.session({userId:this.config.userId,userEvents:[{event:t,properties:e}]})),yield this.resync()})}session(t){return h(this,null,function*(){let e=this.lastSessionDTO;return e&&JSON.stringify(e)===JSON.stringify(t)?!1:(yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)}),this.lastSessionDTO=t,!0)})}isReady(){return!!(this.config.__instanceId&&this.config.apiKey&&this.initPromise)}getFlow(t){return h(this,null,function*(){if(!(this.getConfig().generateGuestId===!1&&this.getConfig().userId&&this.getConfig().userId.startsWith(v)))return yield this.initIfNeeded(),this.getFlowSync(t)})}getFlowSync(t){return this.flows.find(e=>e.id==t)}getFlows(){return h(this,null,function*(){var t;return yield this.initIfNeeded(),this.config.generateGuestId===!1&&((t=this.getConfig().userId)!=null&&t.startsWith(v))?[]:this.flows})}getCollection(t){return h(this,null,function*(){yield this.initIfNeeded();let e=this.getGlobalState().collections.getCollection(t);if(e==null)return;this.registerCollection(t);let i=yield Promise.all(e.flows.map(r=>h(this,null,function*(){return I(S({},r),{flow:yield this.getFlow(r.flowId)})})));return e.flows=i,e})}registerCollection(t){return h(this,null,function*(){yield this.initIfNeeded(),t&&this.getGlobalState().registeredCollectionIds.add(t)})}getCollectionSync(t){let e=this.getGlobalState().collections.getCollection(t);if(e!=null)return this.getGlobalState().registeredCollectionIds.add(t),e}getCollectionsSync(){return this.getGlobalState().collections.getCollections()}getCollections(){return h(this,null,function*(){if(yield this.initIfNeeded(),!this.config.userId&&this.config.generateGuestId===!1)return;let t=this.getGlobalState().collections.getCollections();if(t!=null)return t})}reload(t){return h(this,null,function*(){it(),et(),t&&(yield this.updateConfig(t),this.mockFlowStates(E(this.config))),this.initPromise=null,yield this.init(this.config),this.triggerAllLegacyEventHandlers(),this.triggerAllEventHandlers()})}triggerAllLegacyEventHandlers(){this.flows.forEach(t=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(e=>{let i=this.getGlobalState().previousFlows.get(t.id);e(t,i),this.getGlobalState().previousFlows.set(t.id,P(t))})})}triggerAllEventHandlers(){this.flows.forEach(t=>{let e=this.getGlobalState().previousFlows.get(t.id);this.triggerEventHandlers(t.rawData,e==null?void 0:e.rawData)})}resync(){return h(this,null,function*(){yield this.refreshStateFromAPI()})}onStateChange(t){return h(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}on(t,e){return h(this,null,function*(){var i;this.eventHandlers.set(t,[...(i=this.eventHandlers.get(t))!=null?i:[],e])})}off(t,e){return h(this,null,function*(){var i;this.eventHandlers.set(t,((i=this.eventHandlers.get(t))!=null?i:[]).filter(r=>r!==e))})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return h(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return h(this,null,function*(){return this.initPromise?this.initPromise:this.init(this.config)})}refreshStateFromAPI(){return h(this,null,function*(){let t=E(this.config);if(!w[t]){let e=this,i={set:function(r,n,p){if(r[n]){let o=r[n],a=p;JSON.stringify(o)!==JSON.stringify(a)&&(e.triggerDeprecatedEventHandlers(a,o),e.triggerEventHandlers(a,o))}return r[n]=p,!0}};if(w[t]={refreshStateFromAPI:()=>h(this,null,function*(){}),collections:new R(new Map),registeredCollectionIds:new Set,flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config,currentUrl:m()?window.location.href:"",pendingRequests:new Map,lastFlowSyncDate:new Map},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(t);return}w[t].refreshStateFromAPI=r=>h(this,null,function*(){var o,a;if(this.config.__readOnly)return;let n=r||(yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,context:A(this.getGlobalState())})})),p=new Map;(a=(o=n.collections)==null?void 0:o.computedOrder)==null||a.forEach(({allowedComponents:g,collectionId:l,collectionType:d,flowId:u,visible:f})=>{var k;let b=(k=p.get(l))!=null?k:{allowedComponents:g,collectionType:d,flows:[]};b.flows.push({flowId:u,visible:f}),p.set(l,b)}),p.size>0&&(w[t].collections.ingestCollectionsData(p),w[t].collections.collectionsHaveChanged()&&!r&&(this.triggerAllLegacyEventHandlers(),this.triggerAllEventHandlers())),n&&n.eligibleFlows?(n.eligibleFlows.forEach(g=>{w[t].flowStates[g.flowSlug]=g,this.flows.find(l=>l.id==g.flowSlug)?this.flows.forEach(l=>{l.id==g.flowSlug&&l.resyncState(g)}):this.flows.push(new F({config:this.config,id:g.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield w[t].refreshStateFromAPI(void 0)})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{w[t].flowStates[e]=this.config.__flowStateOverrides[e],this.flows.find(i=>i.id==e)?this.flows.forEach(i=>{i.id==e&&i.resyncState(this.config.__flowStateOverrides[e])}):this.flows.push(new F({config:this.config,id:e}))})}updateConfig(t){return h(this,null,function*(){this.config=S(S({},this.config),t),w[E(this.config)]&&(this.getGlobalState().config=this.config)})}triggerDeprecatedEventHandlers(t,e){return h(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(r=>{let n=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),r(i,n),this.getGlobalState().previousFlows.set(i.id,P(i))})})})}triggerEventHandlers(t,e){var i,r,n,p;if(t){for(let o of this.flows)if(o.id==t.flowSlug){let a=this.getGlobalState().previousFlows.get(o.id);o.resyncState(t);for(let[g,l]of this.eventHandlers.entries())switch(g){case"flow.complete":t.$state.completed&&(e==null?void 0:e.$state.completed)===!1&&l.forEach(d=>d(g,o,a));break;case"flow.restart":!t.$state.started&&(e==null?void 0:e.$state.started)===!0&&l.forEach(d=>d(g,o,a));break;case"flow.skip":t.$state.skipped&&(e==null?void 0:e.$state.skipped)===!1&&l.forEach(d=>d(g,o,a));break;case"flow.start":t.$state.started&&(e==null?void 0:e.$state.started)===!1&&l.forEach(d=>d(g,o,a));break;case"step.complete":for(let d of(i=t.data.steps)!=null?i:[])d.$state.completed&&!(e!=null&&e.data.steps.find(u=>u.id===d.id&&u.$state.completed))&&l.forEach(u=>u(g,o,a,o.steps.get(d.id)));break;case"step.reset":for(let d of(r=t.data.steps)!=null?r:[]){let u=e==null?void 0:e.data.steps.find(f=>f.id===d.id);d.$state.started==!1&&!d.$state.lastActionAt&&(u!=null&&u.$state.started)&&(u!=null&&u.$state.lastActionAt)&&l.forEach(f=>f(g,o,a,o.steps.get(d.id)))}break;case"step.skip":for(let d of(n=t.data.steps)!=null?n:[])d.$state.skipped&&!(e!=null&&e.data.steps.find(u=>u.id===d.id&&u.$state.skipped))&&l.forEach(u=>u(g,o,a,o.steps.get(d.id)));break;case"step.start":for(let d of(p=t.data.steps)!=null?p:[])d.$state.started&&(e!=null&&e.data.steps.find(u=>u.id===d.id&&u.$state.started===!1))&&l.forEach(u=>u(g,o,a,o.steps.get(d.id)));break;case"flow.any":JSON.stringify(t)!==JSON.stringify(e!=null?e:{})&&l.forEach(d=>d(g,o,a));break}this.getGlobalState().previousFlows.set(o.id,P(o))}}}batchRegister(t){return h(this,null,function*(){let e=t.map(n=>h(this,[n],function*([i,r]){let p=yield this.getFlow(i);return[i,a=>{let g=this.getGlobalState().previousFlows.get(i);(g==null?void 0:g.isVisible)!==a&&this.getGlobalState().onFlowStateChangeHandlers.forEach(l=>{l(p,g),this.getGlobalState().previousFlows.set(i,P(p))}),r==null||r(a)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};export{F as Flow,M as FlowStatus,U as FlowType,D as Frigade,L as TriggerType};
3
3
  //# sourceMappingURL=index.js.map