@frigade/js 0.9.3 → 0.9.4

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.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- var A=Object.defineProperty,at=Object.defineProperties,rt=Object.getOwnPropertyDescriptor,nt=Object.getOwnPropertyDescriptors,lt=Object.getOwnPropertyNames,V=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var W=(l,s,t)=>s in l?A(l,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):l[s]=t,S=(l,s)=>{for(var t in s||(s={}))B.call(s,t)&&W(l,t,s[t]);if(V)for(var t of V(s))ct.call(s,t)&&W(l,t,s[t]);return l},E=(l,s)=>at(l,nt(s));var dt=(l,s)=>{for(var t in s)A(l,t,{get:s[t],enumerable:!0})},gt=(l,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of lt(s))!B.call(l,i)&&i!==t&&A(l,i,{get:()=>s[i],enumerable:!(e=rt(s,i))||e.enumerable});return l};var ht=l=>gt(A({},"__esModule",{value:!0}),l);var h=(l,s,t)=>new Promise((e,i)=>{var n=o=>{try{f(t.next(o))}catch(r){i(r)}},d=o=>{try{f(t.throw(o))}catch(r){i(r)}},f=o=>o.done?e(o.value):Promise.resolve(o.value).then(n,d);f((t=t.apply(l,s)).next())});var St={};dt(St,{Flow:()=>F,FlowStatus:()=>G,FlowType:()=>$,Frigade:()=>O,TriggerType:()=>x});module.exports=ht(St);var x=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(x||{}),G=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(G||{});var $=(a=>(a.ANNOUNCEMENT="ANNOUNCEMENT",a.CHECKLIST="CHECKLIST",a.FORM="FORM",a.TOUR="TOUR",a.SUPPORT="SUPPORT",a.CUSTOM="CUSTOM",a.BANNER="BANNER",a.EMBEDDED_TIP="EMBEDDED_TIP",a.NPS_SURVEY="NPS_SURVEY",a.SURVEY="SURVEY",a.CARD="CARD",a))($||{});var H=require("uuid");var w={};function I(l){return`${l.__instanceId}-${l.apiKey}`}var T=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:J(),__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():K(this.getAPIUrl(s),S(S({keepalive:!0},t!=null?t:{}),q(this.config)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=I(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,n,d,f,o,r;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=(n=e==null?void 0:e.data)==null?void 0:n.subtitle,this.type=(d=e==null?void 0:e.data)==null?void 0:d.type,this.props=(o=(f=e==null?void 0:e.data)==null?void 0:f.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,a)=>{var u;let c=this.initStepFromStatefulStep(g,a),p=(u=this.steps)==null?void 0:u.get(g.id);p&&Object.keys(c).forEach(b=>{p[b]=c[b]})}),this.getGlobalState().variables[this.id]?this.applyVariablesInternal((r=this.getGlobalState().variables[this.id])!=null?r:{}):this.applyVariablesInternal({})}initStepFromStatefulStep(t,e){return E(S({},t),{flow:this,$state:E(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,n)=>{let d=this.initStepFromStatefulStep(i,n);d.start=o=>h(this,null,function*(){let r=this.steps.get(i.id);if(this.getCurrentStep().id===r.id&&r.$state.started)return;let g=C(this.getGlobalState().flowStates[this.id]);g.data.steps[r.order].$state.started=!0,g.data.steps[r.order].$state.lastActionAt=new Date,g.$state.lastActionAt=new Date,g.$state.currentStepId=r.id,g.$state.currentStepIndex=r.order,this.getGlobalState().flowStates[this.id]=g,this.resyncState(),yield this.sendFlowStateToAPI(N,o,r.id)});let f=(o,r,g=!0)=>h(this,null,function*(){let a=this.steps.get(i.id);if((a.$state.completed||a.$state.skipped)&&g){let u=this.getStepByIndex(a.order+1);for(;u&&!u.$state.visible&&u.order!==this.steps.size-1;)u=this.getStepByIndex(u.order+1);if(u){let b=C(this.getGlobalState().flowStates[this.id]);b.$state.currentStepId=this.getStepByIndex(a.order+1).id,b.$state.currentStepIndex=a.order+1,b.data.steps[a.order+1].$state.started=!0,this.getGlobalState().flowStates[this.id]=b,yield this.sendFlowStateToAPI(N,void 0,u.id),this.resyncState()}return}let c=this.getCurrentStepOrder()+1===this.getNumberOfAvailableSteps(),p=Array.from(this.steps.values()).filter(u=>u.$state.visible&&!u.$state.completed&&!u.$state.skipped).length===1&&c;if(g){let u=C(this.getGlobalState().flowStates[this.id]);if(u.$state.started=!0,o=="complete"?u.data.steps[a.order].$state.completed=!0:u.data.steps[a.order].$state.skipped=!0,u.data.steps[a.order].$state.started=!0,u.data.steps[a.order].$state.lastActionAt=new Date,!c){let b=this.getNextVisibleStepIndexAfterIndex(a.order);b!==-1&&(u.$state.currentStepId=this.getStepByIndex(b).id,u.$state.currentStepIndex=b,u.data.steps[b].$state.started=!0)}p&&(u.$state.completed=!0,u.$state.visible=!1),this.getGlobalState().flowStates[this.id]=u,this.resyncState(),p&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(o=="complete"?Q:Z,r,a.id),p&&(yield this.sendFlowStateToAPI(k,r))});d.complete=(o,r=!0)=>h(this,null,function*(){yield f("complete",o,r)}),d.skip=(o,r=!0)=>h(this,null,function*(){yield f("skip",o,r)}),d.reset=()=>h(this,null,function*(){let o=this.steps.get(i.id);if(!o.$state.completed)return;let r=C(this.getGlobalState().flowStates[this.id]);r.data.steps[o.order].$state.started=!1,r.data.steps[o.order].$state.completed=!1,r.data.steps[o.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=r,this.resyncState(),yield this.sendFlowStateToAPI(j,void 0,o.id)}),d.onStateChange=o=>{let r=g=>{if(g.id!==this.id)return;let a=g.steps.get(i.id),c=this.lastStepUpdate.get(o);(a.$state.completed!==(c==null?void 0:c.$state.completed)||a.$state.started!==(c==null?void 0:c.$state.started)||a.$state.visible!==(c==null?void 0:c.$state.visible)||a.$state.blocked!==(c==null?void 0:c.$state.blocked))&&(o(a,c!=null?c:C(a)),this.lastStepUpdate.set(o,C(a)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(o,r),this.getGlobalState().onFlowStateChangeHandlers.push(r)},d.removeStateChangeHandler=o=>{let r=this.getGlobalState().onStepStateChangeHandlerWrappers.get(o);r&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(g=>g!==r))},e.set(i.id,d)}),this.steps=e,this.resyncState()}start(t){return h(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(Y,t))})}complete(t){return h(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(k,t))})}skip(t){return h(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(z,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(X)})}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,n)=>{i.id===this.id&&(i.isCompleted!==(n==null?void 0:n.isCompleted)||i.isStarted!==(n==null?void 0:n.isStarted)||i.isSkipped!==(n==null?void 0:n.isSkipped)||i.isVisible!==(n==null?void 0:n.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(n==null?void 0:n.steps))&&t(i,n)};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 d,f;let i=o=>{let r=o.match(/\${(.*?)}/g);return r&&r.forEach(g=>{let a=g.replace("${","").replace("}","");if(!t[a]){o=o.replace(g,"");return}o=o.replace(g,t[a])}),o};this.title=i((d=this.title)!=null?d:""),this.subtitle=i((f=this.subtitle)!=null?f:"");let n=o=>{o&&Object.keys(o).forEach(r=>{typeof o[r]=="string"?o[r]=i(o[r]):typeof o[r]=="object"?n(o[r]):Array.isArray(o[r])&&o[r].forEach(g=>{n(g)})})};this.steps&&this.steps.forEach(o=>{try{n(o)}catch(r){}}),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.getGlobalState().collections.ingestCollectionsData(new Map),this.resyncState()}optimisticallyMarkFlowStarted(){let t=C(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.getGlobalState().collections.ingestCollectionsData(new Map),this.resyncState()}sendFlowStateToAPI(t,e,i){return h(this,null,function*(){var f;let n=new Date;this.getGlobalState().lastFlowSyncDate[this.id]=n,this.getGlobalState().pendingRequests[this.id]=((f=this.getGlobalState().pendingRequests[this.id])!=null?f:0)+1;let d=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:n,context:R(this.getGlobalState())})});this.getGlobalState().pendingRequests[this.id]-=1,!(n<this.getGlobalState().lastFlowSyncDate[this.id]||this.getGlobalState().pendingRequests[this.id]>0)&&(yield this.getGlobalState().refreshStateFromAPI(d))})}optimisticallyMarkFlowSkipped(){let t=C(this.getGlobalState().flowStates[this.id]);t.$state.skipped=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.getGlobalState().collections.ingestCollectionsData(new Map),this.resyncState()}register(t){this.getGlobalState().collections.register(this.id,i=>{let n=this.getGlobalState().previousFlows.get(this.id);(n==null?void 0:n._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(d=>{d(this,n),this.getGlobalState().previousFlows.set(this.id,P(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var tt="0.9.3";var j="NOT_STARTED_STEP",k="COMPLETED_FLOW",z="SKIPPED_FLOW",Y="STARTED_FLOW",X="NOT_STARTED_FLOW",Q="COMPLETED_STEP",Z="SKIPPED_STEP",N="STARTED_STEP",et="frigade-guest-key",v="guest_",pt="get-cache-",M="fr-js-",it="Redundant call to Frigade API removed";function P(l){return new F({config:l.config,id:l.id})}function C(l){return JSON.parse(JSON.stringify(l))}function q(l){var s,t;return{headers:{Authorization:`Bearer ${l.apiKey}`,"Content-Type":"application/json","x-frigade-sdk-version":(s=l.__platformVersion)!=null?s:tt,"x-frigade-sdk-platform":(t=l.__platformName)!=null?t:"Javascript"}}}function ft(l){if(m())try{return window.localStorage.getItem(`${M}${l}`)}catch(s){return console.debug("Error getting localStorage:",s),null}return null}function ut(l,s){if(m())try{window.localStorage.setItem(`${M}${l}`,s)}catch(t){console.debug("Error setting localStorage:",t)}}function st(){Object.keys(w).forEach(l=>{l.startsWith(pt)&&delete w[l]})}function ot(){m()&&Object.keys(window.localStorage).forEach(l=>{l.startsWith(M)&&window.localStorage.removeItem(l)})}var L=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 L;function K(l,s){return h(this,null,function*(){var n;if(typeof globalThis.fetch!="function")return y("- Attempted to call fetch() in an environment that doesn't support it.");let t=`${l}${JSON.stringify((n=s.body)!=null?n:{})}`,e,i=m()&&s&&s.body&&s.method==="POST";if(i){let d=globalThis.callQueue.hasIdenticalRecentCall(t);d!=null&&d.response!=null&&(e=(yield d.response).clone())}if(!e)try{let d=fetch(l,s);i&&globalThis.callQueue.push(t,d.then(f=>f.clone()).catch(()=>y())),e=yield d,i&&!globalThis.callQueue.hasCall(t)&&(e=y(it))}catch(d){return y(d)}if(!e)return y("Received an empty response");if(e.status>=400)return y(e.statusText);try{if(e.status===204)return y();let d;try{d=yield e.json()}catch(f){return y()}return d.error?y(d.error):d}catch(d){return y(d)}})}function y(l){return l&&(l===it?console.debug(l):console.warn("Call to Frigade failed:",l)),{json:()=>({}),clone:()=>({})}}function J(){if(m()){let l=ft(et);return l||(l=`${v}${(0,H.v4)()}`,ut(et,l)),l}else return`${v}${(0,H.v4)()}`}function m(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function R(l){let s={registeredCollectionIds:Array.from(l.registeredCollectionIds)};return m()?S({url:l.currentUrl,userAgent:navigator.userAgent},s):s}var _=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){var i,n,d,f,o,r;let t=this.collections,e=s;t.size!==e.size&&(this.hasChanges=!0);for(let[g,a]of t){let c=e.get(g);if(((i=a==null?void 0:a.flows)==null?void 0:i.length)!==((n=c==null?void 0:c.flows)==null?void 0:n.length)){this.hasChanges=!0;break}for(let p=0;p<a.flows.length;p++)if(((d=a==null?void 0:a.flows[p])==null?void 0:d.flowId)!==((f=c==null?void 0:c.flows[p])==null?void 0:f.flowId)||((o=a==null?void 0:a.flows[p])==null?void 0:o.visible)!==((r=c==null?void 0:c.flows[p])==null?void 0:r.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 n=s.flows.map(({flowId:d})=>d).filter(d=>d!==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 O=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).then(()=>{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(n){}})))})}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=I(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(E(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(E(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&&w[I(this.config)])}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(n=>h(this,null,function*(){return E(S({},n),{flow:yield this.getFlow(n.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*(){ot(),st(),t&&(yield this.updateConfig(t),this.mockFlowStates(I(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(n=>n!==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=I(this.config);if(!w[t]){let e=this,i={set:function(n,d,f){if(n[d]){let o=n[d],r=f;JSON.stringify(o)!==JSON.stringify(r)&&(e.triggerDeprecatedEventHandlers(r,o),e.triggerEventHandlers(r,o))}return n[d]=f,!0}};if(w[t]={refreshStateFromAPI:()=>h(this,null,function*(){}),collections:new _(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=n=>h(this,null,function*(){var o,r;if(this.config.__readOnly)return;let d=n||(yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,context:R(this.getGlobalState())})})),f=new Map;(r=(o=d.collections)==null?void 0:o.computedOrder)==null||r.forEach(({allowedComponents:g,collectionId:a,collectionType:c,flowId:p,visible:u})=>{var U;let b=(U=f.get(a))!=null?U:{allowedComponents:g,collectionType:c,flows:[]};b.flows.push({flowId:p,visible:u}),f.set(a,b)}),f.size>0&&(w[t].collections.ingestCollectionsData(f),w[t].collections.collectionsHaveChanged()&&!n&&(this.triggerAllLegacyEventHandlers(),this.triggerAllEventHandlers())),d&&d.eligibleFlows?(d.eligibleFlows.forEach(g=>{w[t].flowStates[g.flowSlug]=g,this.flows.find(a=>a.id==g.flowSlug)?this.flows.forEach(a=>{a.id==g.flowSlug&&a.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[I(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(n=>{let d=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),n(i,d),this.getGlobalState().previousFlows.set(i.id,P(i))})})})}triggerEventHandlers(t,e){var i,n,d,f;if(t){for(let o of this.flows)if(o.id==t.flowSlug){let r=this.getGlobalState().previousFlows.get(o.id);o.resyncState(t);for(let[g,a]of this.eventHandlers.entries())switch(g){case"flow.complete":t.$state.completed&&(e==null?void 0:e.$state.completed)===!1&&a.forEach(c=>c(g,o,r));break;case"flow.restart":!t.$state.started&&(e==null?void 0:e.$state.started)===!0&&a.forEach(c=>c(g,o,r));break;case"flow.skip":t.$state.skipped&&(e==null?void 0:e.$state.skipped)===!1&&a.forEach(c=>c(g,o,r));break;case"flow.start":t.$state.started&&(e==null?void 0:e.$state.started)===!1&&a.forEach(c=>c(g,o,r));break;case"step.complete":for(let c of(i=t.data.steps)!=null?i:[])c.$state.completed&&!(e!=null&&e.data.steps.find(p=>p.id===c.id&&p.$state.completed))&&a.forEach(p=>p(g,o,r,o.steps.get(c.id)));break;case"step.reset":for(let c of(n=t.data.steps)!=null?n:[]){let p=e==null?void 0:e.data.steps.find(u=>u.id===c.id);c.$state.started==!1&&!c.$state.lastActionAt&&(p!=null&&p.$state.started)&&(p!=null&&p.$state.lastActionAt)&&a.forEach(u=>u(g,o,r,o.steps.get(c.id)))}break;case"step.skip":for(let c of(d=t.data.steps)!=null?d:[])c.$state.skipped&&!(e!=null&&e.data.steps.find(p=>p.id===c.id&&p.$state.skipped))&&a.forEach(p=>p(g,o,r,o.steps.get(c.id)));break;case"step.start":for(let c of(f=t.data.steps)!=null?f:[])c.$state.started&&(e!=null&&e.data.steps.find(p=>p.id===c.id&&p.$state.started===!1))&&a.forEach(p=>p(g,o,r,o.steps.get(c.id)));break;case"flow.any":JSON.stringify(t)!==JSON.stringify(e!=null?e:{})&&a.forEach(c=>c(g,o,r));break}this.getGlobalState().previousFlows.set(o.id,P(o))}}}batchRegister(t){return h(this,null,function*(){let e=t.map(d=>h(this,[d],function*([i,n]){let f=yield this.getFlow(i);return[i,r=>{let g=this.getGlobalState().previousFlows.get(i);(g==null?void 0:g.isVisible)!==r&&this.getGlobalState().onFlowStateChangeHandlers.forEach(a=>{a(f,g),this.getGlobalState().previousFlows.set(i,P(f))}),n==null||n(r)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};0&&(module.exports={Flow,FlowStatus,FlowType,Frigade,TriggerType});
2
+ var A=Object.defineProperty,at=Object.defineProperties,rt=Object.getOwnPropertyDescriptor,nt=Object.getOwnPropertyDescriptors,lt=Object.getOwnPropertyNames,V=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var W=(l,s,t)=>s in l?A(l,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):l[s]=t,S=(l,s)=>{for(var t in s||(s={}))B.call(s,t)&&W(l,t,s[t]);if(V)for(var t of V(s))ct.call(s,t)&&W(l,t,s[t]);return l},E=(l,s)=>at(l,nt(s));var dt=(l,s)=>{for(var t in s)A(l,t,{get:s[t],enumerable:!0})},gt=(l,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of lt(s))!B.call(l,i)&&i!==t&&A(l,i,{get:()=>s[i],enumerable:!(e=rt(s,i))||e.enumerable});return l};var pt=l=>gt(A({},"__esModule",{value:!0}),l);var p=(l,s,t)=>new Promise((e,i)=>{var n=o=>{try{f(t.next(o))}catch(r){i(r)}},d=o=>{try{f(t.throw(o))}catch(r){i(r)}},f=o=>o.done?e(o.value):Promise.resolve(o.value).then(n,d);f((t=t.apply(l,s)).next())});var St={};dt(St,{Flow:()=>F,FlowStatus:()=>G,FlowType:()=>$,Frigade:()=>O,TriggerType:()=>x});module.exports=pt(St);var x=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(x||{}),G=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(G||{});var $=(a=>(a.ANNOUNCEMENT="ANNOUNCEMENT",a.CHECKLIST="CHECKLIST",a.FORM="FORM",a.TOUR="TOUR",a.SUPPORT="SUPPORT",a.CUSTOM="CUSTOM",a.BANNER="BANNER",a.EMBEDDED_TIP="EMBEDDED_TIP",a.NPS_SURVEY="NPS_SURVEY",a.SURVEY="SURVEY",a.CARD="CARD",a))($||{});var H=require("uuid");var w={};function I(l){return`${l.__instanceId}-${l.apiKey}`}var T=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:J(),__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 p(this,null,function*(){return this.config.__readOnly?y():K(this.getAPIUrl(s),S(S({keepalive:!0},t!=null?t:{}),q(this.config)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=I(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,n,d,f,o,r;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=(n=e==null?void 0:e.data)==null?void 0:n.subtitle,this.type=(d=e==null?void 0:e.data)==null?void 0:d.type,this.props=(o=(f=e==null?void 0:e.data)==null?void 0:f.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,a)=>{var h;let c=this.initStepFromStatefulStep(g,a),u=(h=this.steps)==null?void 0:h.get(g.id);u&&Object.keys(c).forEach(b=>{u[b]=c[b]})}),this.getGlobalState().variables[this.id]?this.applyVariablesInternal((r=this.getGlobalState().variables[this.id])!=null?r:{}):this.applyVariablesInternal({})}initStepFromStatefulStep(t,e){return E(S({},t),{flow:this,$state:E(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,n)=>{let d=this.initStepFromStatefulStep(i,n);d.start=o=>p(this,null,function*(){let r=this.steps.get(i.id);if(this.getCurrentStep().id===r.id&&r.$state.started)return;let g=C(this.getGlobalState().flowStates[this.id]);g.data.steps[r.order].$state.started=!0,g.data.steps[r.order].$state.lastActionAt=new Date,g.$state.lastActionAt=new Date,g.$state.currentStepId=r.id,g.$state.currentStepIndex=r.order,this.getGlobalState().flowStates[this.id]=g,this.resyncState(),yield this.sendFlowStateToAPI(N,o,r.id)});let f=(o,r,g=!0)=>p(this,null,function*(){let a=this.steps.get(i.id);if((a.$state.completed||a.$state.skipped)&&g){let h=this.getStepByIndex(a.order+1);for(;h&&!h.$state.visible&&h.order!==this.steps.size-1;)h=this.getStepByIndex(h.order+1);if(h){let b=C(this.getGlobalState().flowStates[this.id]);b.$state.currentStepId=this.getStepByIndex(a.order+1).id,b.$state.currentStepIndex=a.order+1,b.data.steps[a.order+1].$state.started=!0,this.getGlobalState().flowStates[this.id]=b,yield this.sendFlowStateToAPI(N,void 0,h.id),this.resyncState()}return}let c=this.getCurrentStepOrder()+1===this.getNumberOfAvailableSteps(),u=Array.from(this.steps.values()).filter(h=>h.$state.visible&&!h.$state.completed&&!h.$state.skipped).length===1&&c;if(g){let h=C(this.getGlobalState().flowStates[this.id]);if(h.$state.started=!0,o=="complete"?h.data.steps[a.order].$state.completed=!0:h.data.steps[a.order].$state.skipped=!0,h.data.steps[a.order].$state.started=!0,h.data.steps[a.order].$state.lastActionAt=new Date,!c){let b=this.getNextVisibleStepIndexAfterIndex(a.order);b!==-1&&(h.$state.currentStepId=this.getStepByIndex(b).id,h.$state.currentStepIndex=b,h.data.steps[b].$state.started=!0)}u&&(h.$state.completed=!0,h.$state.visible=!1),this.getGlobalState().flowStates[this.id]=h,this.resyncState(),u&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(o=="complete"?Q:Z,r,a.id),u&&(yield this.sendFlowStateToAPI(k,r))});d.complete=(o,r=!0)=>p(this,null,function*(){yield f("complete",o,r)}),d.skip=(o,r=!0)=>p(this,null,function*(){yield f("skip",o,r)}),d.reset=()=>p(this,null,function*(){let o=this.steps.get(i.id);if(!o.$state.completed)return;let r=C(this.getGlobalState().flowStates[this.id]);r.data.steps[o.order].$state.started=!1,r.data.steps[o.order].$state.completed=!1,r.data.steps[o.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=r,this.resyncState(),yield this.sendFlowStateToAPI(j,void 0,o.id)}),d.onStateChange=o=>{let r=g=>{if(g.id!==this.id)return;let a=g.steps.get(i.id),c=this.lastStepUpdate.get(o);(a.$state.completed!==(c==null?void 0:c.$state.completed)||a.$state.started!==(c==null?void 0:c.$state.started)||a.$state.visible!==(c==null?void 0:c.$state.visible)||a.$state.blocked!==(c==null?void 0:c.$state.blocked))&&(o(a,c!=null?c:C(a)),this.lastStepUpdate.set(o,C(a)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(o,r),this.getGlobalState().onFlowStateChangeHandlers.push(r)},d.removeStateChangeHandler=o=>{let r=this.getGlobalState().onStepStateChangeHandlerWrappers.get(o);r&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(g=>g!==r))},e.set(i.id,d)}),this.steps=e,this.resyncState()}start(t){return p(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(Y,t))})}complete(t){return p(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(k,t))})}skip(t){return p(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(z,t))})}forward(t){return p(this,null,function*(){let e=this.getStepByIndex(this.getNextVisibleStepIndexAfterIndex(this.getCurrentStepIndex()));e&&(yield e.start(t))})}back(t){return p(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 p(this,null,function*(){yield this.sendFlowStateToAPI(X)})}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,n)=>{i.id===this.id&&(i.isCompleted!==(n==null?void 0:n.isCompleted)||i.isStarted!==(n==null?void 0:n.isStarted)||i.isSkipped!==(n==null?void 0:n.isSkipped)||i.isVisible!==(n==null?void 0:n.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(n==null?void 0:n.steps))&&t(i,n)};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 d,f;let i=o=>{let r=o.match(/\${(.*?)}/g);return r&&r.forEach(g=>{let a=g.replace("${","").replace("}","");if(!t[a]){o=o.replace(g,"");return}o=o.replace(g,t[a])}),o};this.title=i((d=this.title)!=null?d:""),this.subtitle=i((f=this.subtitle)!=null?f:"");let n=o=>{o&&Object.keys(o).forEach(r=>{typeof o[r]=="string"?o[r]=i(o[r]):typeof o[r]=="object"?n(o[r]):Array.isArray(o[r])&&o[r].forEach(g=>{n(g)})})};this.steps&&this.steps.forEach(o=>{try{n(o)}catch(r){}}),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.getGlobalState().collections.ingestCollectionsData(new Map),this.resyncState()}optimisticallyMarkFlowStarted(){let t=C(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.getGlobalState().collections.ingestCollectionsData(new Map),this.resyncState()}sendFlowStateToAPI(t,e,i){return p(this,null,function*(){var f;let n=new Date;this.getGlobalState().lastFlowSyncDate[this.id]=n,this.getGlobalState().pendingRequests[this.id]=((f=this.getGlobalState().pendingRequests[this.id])!=null?f:0)+1;let d=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:n,context:R(this.getGlobalState())})});this.getGlobalState().pendingRequests[this.id]-=1,!(n<this.getGlobalState().lastFlowSyncDate[this.id]||this.getGlobalState().pendingRequests[this.id]>0)&&(yield this.getGlobalState().refreshStateFromAPI(d))})}optimisticallyMarkFlowSkipped(){let t=C(this.getGlobalState().flowStates[this.id]);t.$state.skipped=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.getGlobalState().collections.ingestCollectionsData(new Map),this.resyncState()}register(t){this.getGlobalState().collections.register(this.id,i=>{let n=this.getGlobalState().previousFlows.get(this.id);(n==null?void 0:n._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(d=>{d(this,n),this.getGlobalState().previousFlows.set(this.id,P(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var tt="0.9.4";var j="NOT_STARTED_STEP",k="COMPLETED_FLOW",z="SKIPPED_FLOW",Y="STARTED_FLOW",X="NOT_STARTED_FLOW",Q="COMPLETED_STEP",Z="SKIPPED_STEP",N="STARTED_STEP",et="frigade-guest-key",v="guest_",ht="get-cache-",M="fr-js-",it="Redundant call to Frigade API removed";function P(l){return new F({config:l.config,id:l.id})}function C(l){return JSON.parse(JSON.stringify(l))}function q(l){var s,t;return{headers:{Authorization:`Bearer ${l.apiKey}`,"Content-Type":"application/json","x-frigade-sdk-version":(s=l.__platformVersion)!=null?s:tt,"x-frigade-sdk-platform":(t=l.__platformName)!=null?t:"Javascript"}}}function ft(l){if(m())try{return window.localStorage.getItem(`${M}${l}`)}catch(s){return console.debug("Error getting localStorage:",s),null}return null}function ut(l,s){if(m())try{window.localStorage.setItem(`${M}${l}`,s)}catch(t){console.debug("Error setting localStorage:",t)}}function st(){Object.keys(w).forEach(l=>{l.startsWith(ht)&&delete w[l]})}function ot(){m()&&Object.keys(window.localStorage).forEach(l=>{l.startsWith(M)&&window.localStorage.removeItem(l)})}var L=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 L;function K(l,s){return p(this,null,function*(){var n;if(typeof globalThis.fetch!="function")return y("- Attempted to call fetch() in an environment that doesn't support it.");let t=`${l}${JSON.stringify((n=s.body)!=null?n:{})}`,e,i=m()&&s&&s.body&&s.method==="POST";if(i){let d=globalThis.callQueue.hasIdenticalRecentCall(t);d!=null&&d.response!=null&&(e=(yield d.response).clone())}if(!e)try{let d=fetch(l,s);i&&globalThis.callQueue.push(t,d.then(f=>f.clone()).catch(()=>y())),e=yield d,i&&!globalThis.callQueue.hasCall(t)&&(e=y(it))}catch(d){return y(d)}if(!e)return y("Received an empty response");if(e.status>=400)return y(e.statusText);try{if(e.status===204)return y();let d;try{d=yield e.json()}catch(f){return y()}return d.error?y(d.error):d}catch(d){return y(d)}})}function y(l){return l&&(l===it?console.debug(l):console.warn("Call to Frigade failed:",l)),{json:()=>({}),clone:()=>({})}}function J(){if(m()){let l=ft(et);return l||(l=`${v}${(0,H.v4)()}`,ut(et,l)),l}else return`${v}${(0,H.v4)()}`}function m(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function R(l){let s={registeredCollectionIds:Array.from(l.registeredCollectionIds)};return m()?S({url:l.currentUrl,userAgent:navigator.userAgent},s):s}var _=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){var i,n,d,f,o,r;let t=this.collections,e=s;t.size!==e.size&&(this.hasChanges=!0);for(let[g,a]of t){let c=e.get(g);if(((i=a==null?void 0:a.flows)==null?void 0:i.length)!==((n=c==null?void 0:c.flows)==null?void 0:n.length)){this.hasChanges=!0;break}for(let u=0;u<a.flows.length;u++)if(((d=a==null?void 0:a.flows[u])==null?void 0:d.flowId)!==((f=c==null?void 0:c.flows[u])==null?void 0:f.flowId)||((o=a==null?void 0:a.flows[u])==null?void 0:o.visible)!==((r=c==null?void 0:c.flows[u])==null?void 0:r.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 n=s.flows.map(({flowId:d})=>d).filter(d=>d!==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 O=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).then(()=>{m()&&this.config.syncOnWindowUpdates!==!1&&(document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.navigation&&window.navigation.addEventListener("navigate",i=>p(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(n){}})))})}queueRefreshStateFromAPI(){var t;this.queuedRefresh=!0,!this.refreshTimeout&&(this.refreshTimeout=setTimeout(()=>p(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=I(this.config);w[t]&&(w[t].onFlowStateChangeHandlers=[])}}init(t){return p(this,null,function*(){if(this.updateConfig(S(S({},this.config),t)),!!this.config.userId)return this.initPromise=(()=>p(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 p(this,null,function*(){t!==this.config.userId&&(yield this.updateConfig(E(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 p(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(E(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 p(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 p(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&&w[I(this.config)])}getFlow(t){return p(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 p(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 p(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(n=>p(this,null,function*(){return E(S({},n),{flow:yield this.getFlow(n.flowId)})})));return e.flows=i,e})}registerCollection(t){return p(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 p(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 p(this,null,function*(){ot(),st(),t&&(yield this.updateConfig(t),this.mockFlowStates(I(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 p(this,null,function*(){yield this.refreshStateFromAPI()})}onStateChange(t){return p(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}on(t,e){return p(this,null,function*(){var i;this.eventHandlers.set(t,[...(i=this.eventHandlers.get(t))!=null?i:[],e])})}off(t,e){return p(this,null,function*(){var i;this.eventHandlers.set(t,((i=this.eventHandlers.get(t))!=null?i:[]).filter(n=>n!==e))})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return p(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return p(this,null,function*(){return this.initPromise?this.initPromise:this.init(this.config)})}refreshStateFromAPI(){return p(this,null,function*(){let t=I(this.config);if(!w[t]){let e=this,i={set:function(n,d,f){if(n[d]){let o=n[d],r=f;JSON.stringify(o)!==JSON.stringify(r)&&(e.triggerDeprecatedEventHandlers(r,o),e.triggerEventHandlers(r,o))}return n[d]=f,!0}};if(w[t]={refreshStateFromAPI:()=>p(this,null,function*(){}),collections:new _(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=n=>p(this,null,function*(){var o,r;if(this.config.__readOnly)return;let d=n||(yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,context:R(this.getGlobalState())})})),f=new Map;(r=(o=d.collections)==null?void 0:o.computedOrder)==null||r.forEach(({allowedComponents:g,collectionId:a,collectionType:c,flowId:u,visible:h})=>{var U;let b=(U=f.get(a))!=null?U:{allowedComponents:g,collectionType:c,flows:[]};b.flows.push({flowId:u,visible:h}),f.set(a,b)}),f.size>0&&(w[t].collections.ingestCollectionsData(f),w[t].collections.collectionsHaveChanged()&&!n&&(this.triggerAllLegacyEventHandlers(),this.triggerAllEventHandlers())),d&&d.eligibleFlows?(d.eligibleFlows.forEach(g=>{w[t].flowStates[g.flowSlug]=g,this.flows.find(a=>a.id==g.flowSlug)?this.flows.forEach(a=>{a.id==g.flowSlug&&a.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 p(this,null,function*(){this.config=S(S({},this.config),t),w[I(this.config)]&&(this.getGlobalState().config=this.config)})}triggerDeprecatedEventHandlers(t,e){return p(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(n=>{let d=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),n(i,d),this.getGlobalState().previousFlows.set(i.id,P(i))})})})}triggerEventHandlers(t,e){var i,n,d,f;if(t){for(let o of this.flows)if(o.id==t.flowSlug){let r=this.getGlobalState().previousFlows.get(o.id);o.resyncState(t);for(let[g,a]of this.eventHandlers.entries())switch(g){case"flow.complete":t.$state.completed&&(e==null?void 0:e.$state.completed)===!1&&a.forEach(c=>c(g,o,r));break;case"flow.restart":!t.$state.started&&(e==null?void 0:e.$state.started)===!0&&a.forEach(c=>c(g,o,r));break;case"flow.skip":t.$state.skipped&&(e==null?void 0:e.$state.skipped)===!1&&a.forEach(c=>c(g,o,r));break;case"flow.start":t.$state.started&&(e==null?void 0:e.$state.started)===!1&&a.forEach(c=>c(g,o,r));break;case"step.complete":for(let c of(i=t.data.steps)!=null?i:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===c.id);c.$state.completed&&u&&u.$state.completed!==c.$state.completed&&a.forEach(h=>h(g,o,r,o.steps.get(c.id)))}break;case"step.reset":for(let c of(n=t.data.steps)!=null?n:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===c.id);c.$state.started==!1&&!c.$state.lastActionAt&&u&&(u!=null&&u.$state.started)&&(u!=null&&u.$state.lastActionAt)&&a.forEach(h=>h(g,o,r,o.steps.get(c.id)))}break;case"step.skip":for(let c of(d=t.data.steps)!=null?d:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===c.id);c.$state.skipped&&u&&u.$state.skipped!==c.$state.skipped&&a.forEach(h=>h(g,o,r,o.steps.get(c.id)))}break;case"step.start":for(let c of(f=t.data.steps)!=null?f:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===c.id);c.$state.started&&u&&u.$state.started===!1&&a.forEach(h=>h(g,o,r,o.steps.get(c.id)))}break;case"flow.any":JSON.stringify(t)!==JSON.stringify(e!=null?e:{})&&a.forEach(c=>c(g,o,r));break}this.getGlobalState().previousFlows.set(o.id,P(o))}}}batchRegister(t){return p(this,null,function*(){let e=t.map(d=>p(this,[d],function*([i,n]){let f=yield this.getFlow(i);return[i,r=>{let g=this.getGlobalState().previousFlows.get(i);(g==null?void 0:g.isVisible)!==r&&this.getGlobalState().onFlowStateChangeHandlers.forEach(a=>{a(f,g),this.getGlobalState().previousFlows.set(i,P(f))}),n==null||n(r)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};0&&(module.exports={Flow,FlowStatus,FlowType,Frigade,TriggerType});
3
3
  //# sourceMappingURL=index.cjs.map