@frigade/js 0.9.4 → 0.9.6

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 st=Object.defineProperty,ot=Object.defineProperties;var at=Object.getOwnPropertyDescriptors;var N=Object.getOwnPropertySymbols;var rt=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var H=(d,o,t)=>o in d?st(d,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[o]=t,S=(d,o)=>{for(var t in o||(o={}))rt.call(o,t)&&H(d,t,o[t]);if(N)for(var t of N(o))nt.call(o,t)&&H(d,t,o[t]);return d},E=(d,o)=>ot(d,at(o));var p=(d,o,t)=>new Promise((e,i)=>{var n=s=>{try{f(t.next(s))}catch(r){i(r)}},c=s=>{try{f(t.throw(s))}catch(r){i(r)}},f=s=>s.done?e(s.value):Promise.resolve(s.value).then(n,c);f((t=t.apply(d,o)).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=(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))(U||{});import{v4 as Q}from"uuid";var w={};function F(d){return`${d.__instanceId}-${d.apiKey}`}var T=class{constructor(o){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(o).filter(([e,i])=>i!=null));this.config=S(S({},this.config),t)}fetch(o,t){return p(this,null,function*(){return this.config.__readOnly?y():W(this.getAPIUrl(o),S(S({keepalive:!0},t!=null?t:{}),V(this.config)))})}getAPIUrl(o){return`${this.config.apiUrl.replace(/\/$/,"")}/${o.replace(/^\//,"")}`}getGlobalState(){let o=F(this.config);if(!w[o])throw new Error("Frigade has not yet been initialized");return w[o]}};var I=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,c,f,s,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=(c=e==null?void 0:e.data)==null?void 0:c.type,this.props=(s=(f=e==null?void 0:e.data)==null?void 0:f.props)!=null?s:{},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 l=this.initStepFromStatefulStep(g,a),u=(h=this.steps)==null?void 0:h.get(g.id);u&&Object.keys(l).forEach(b=>{u[b]=l[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 c=this.initStepFromStatefulStep(i,n);c.start=s=>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(x,s,r.id)});let f=(s,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(x,void 0,h.id),this.resyncState()}return}let l=this.getCurrentStepOrder()+1===this.getNumberOfAvailableSteps(),u=Array.from(this.steps.values()).filter(h=>h.$state.visible&&!h.$state.completed&&!h.$state.skipped).length===1&&l;if(g){let h=C(this.getGlobalState().flowStates[this.id]);if(h.$state.started=!0,s=="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,!l){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(s=="complete"?z:Y,r,a.id),u&&(yield this.sendFlowStateToAPI(O,r))});c.complete=(s,r=!0)=>p(this,null,function*(){yield f("complete",s,r)}),c.skip=(s,r=!0)=>p(this,null,function*(){yield f("skip",s,r)}),c.reset=()=>p(this,null,function*(){let s=this.steps.get(i.id);if(!s.$state.completed)return;let r=C(this.getGlobalState().flowStates[this.id]);r.data.steps[s.order].$state.started=!1,r.data.steps[s.order].$state.completed=!1,r.data.steps[s.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=r,this.resyncState(),yield this.sendFlowStateToAPI(q,void 0,s.id)}),c.onStateChange=s=>{let r=g=>{if(g.id!==this.id)return;let a=g.steps.get(i.id),l=this.lastStepUpdate.get(s);(a.$state.completed!==(l==null?void 0:l.$state.completed)||a.$state.started!==(l==null?void 0:l.$state.started)||a.$state.visible!==(l==null?void 0:l.$state.visible)||a.$state.blocked!==(l==null?void 0:l.$state.blocked))&&(s(a,l!=null?l:C(a)),this.lastStepUpdate.set(s,C(a)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(s,r),this.getGlobalState().onFlowStateChangeHandlers.push(r)},c.removeStateChangeHandler=s=>{let r=this.getGlobalState().onStepStateChangeHandlerWrappers.get(s);r&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(g=>g!==r))},e.set(i.id,c)}),this.steps=e,this.resyncState()}start(t){return p(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(J,t))})}complete(t){return p(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(O,t))})}skip(t){return p(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(K,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(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,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 c,f;let i=s=>{let r=s.match(/\${(.*?)}/g);return r&&r.forEach(g=>{let a=g.replace("${","").replace("}","");if(!t[a]){s=s.replace(g,"");return}s=s.replace(g,t[a])}),s};this.title=i((c=this.title)!=null?c:""),this.subtitle=i((f=this.subtitle)!=null?f:"");let n=s=>{s&&Object.keys(s).forEach(r=>{typeof s[r]=="string"?s[r]=i(s[r]):typeof s[r]=="object"?n(s[r]):Array.isArray(s[r])&&s[r].forEach(g=>{n(g)})})};this.steps&&this.steps.forEach(s=>{try{n(s)}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 c=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:A(this.getGlobalState())})});this.getGlobalState().pendingRequests[this.id]-=1,!(n<this.getGlobalState().lastFlowSyncDate[this.id]||this.getGlobalState().pendingRequests[this.id]>0)&&(yield this.getGlobalState().refreshStateFromAPI(c))})}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(c=>{c(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 X="0.9.4";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(d){return new I({config:d.config,id:d.id})}function C(d){return JSON.parse(JSON.stringify(d))}function V(d){var o,t;return{headers:{Authorization:`Bearer ${d.apiKey}`,"Content-Type":"application/json","x-frigade-sdk-version":(o=d.__platformVersion)!=null?o:X,"x-frigade-sdk-platform":(t=d.__platformName)!=null?t:"Javascript"}}}function ct(d){if(m())try{return window.localStorage.getItem(`${$}${d}`)}catch(o){return console.debug("Error getting localStorage:",o),null}return null}function dt(d,o){if(m())try{window.localStorage.setItem(`${$}${d}`,o)}catch(t){console.debug("Error setting localStorage:",t)}}function et(){Object.keys(w).forEach(d=>{d.startsWith(lt)&&delete w[d]})}function it(){m()&&Object.keys(window.localStorage).forEach(d=>{d.startsWith($)&&window.localStorage.removeItem(d)})}var G=class{constructor(){this.queue=[];this.ttlInMS=250;this.cacheSize=10}push(o,t){let e=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:o,time:e.getTime(),response:t!=null?t:null})}hasIdenticalRecentCall(o){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.find(e=>e.call===o)}hasCall(o){return this.queue.find(t=>t.call===o)}cancelAllPendingRequests(){this.queue=[]}};globalThis.callQueue=new G;function W(d,o){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=`${d}${JSON.stringify((n=o.body)!=null?n:{})}`,e,i=m()&&o&&o.body&&o.method==="POST";if(i){let c=globalThis.callQueue.hasIdenticalRecentCall(t);c!=null&&c.response!=null&&(e=(yield c.response).clone())}if(!e)try{let c=fetch(d,o);i&&globalThis.callQueue.push(t,c.then(f=>f.clone()).catch(()=>y())),e=yield c,i&&!globalThis.callQueue.hasCall(t)&&(e=y(tt))}catch(c){return y(c)}if(!e)return y("Received an empty response");if(e.status>=400)return y(e.statusText);try{if(e.status===204)return y();let c;try{c=yield e.json()}catch(f){return y()}return c.error?y(c.error):c}catch(c){return y(c)}})}function y(d){return d&&(d===tt?console.debug(d):console.warn("Call to Frigade failed:",d)),{json:()=>({}),clone:()=>({})}}function B(){if(m()){let d=ct(Z);return d||(d=`${v}${Q()}`,dt(Z,d)),d}else return`${v}${Q()}`}function m(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function A(d){let o={registeredCollectionIds:Array.from(d.registeredCollectionIds)};return m()?S({url:d.currentUrl,userAgent:navigator.userAgent},o):o}var R=class{constructor(o){this.registry=new Map;this.registryStateLocked=!1;this.collections=new Map;this.flowsInCollections=new Set;this.hasChanges=!1;this.ingestCollectionsData(o)}getCollection(o){return this.collections.get(o)}getCollections(){return this.collections}collectionsHaveChanged(){return this.hasChanges}ingestCollectionsData(o){if(this.hasChanges=!0,this.checkIfCollectionsHaveChanged(o),!!this.hasChanges){this.collections=o;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(o){var i,n,c,f,s,r;let t=this.collections,e=o;t.size!==e.size&&(this.hasChanges=!0);for(let[g,a]of t){let l=e.get(g);if(((i=a==null?void 0:a.flows)==null?void 0:i.length)!==((n=l==null?void 0:l.flows)==null?void 0:n.length)){this.hasChanges=!0;break}for(let u=0;u<a.flows.length;u++)if(((c=a==null?void 0:a.flows[u])==null?void 0:c.flowId)!==((f=l==null?void 0:l.flows[u])==null?void 0:f.flowId)||((s=a==null?void 0:a.flows[u])==null?void 0:s.visible)!==((r=l==null?void 0:l.flows[u])==null?void 0:r.visible)){this.hasChanges=!0;break}}}fireCallbacks(){for(let[o,{callback:t}]of this.registry)typeof t=="function"&&t(this.isFlowVisible(o))}isFlowVisible(o){let t=this.registry.get(o),e=this.flowsInCollections.has(o);return t==null||!e?!0:t.visible}lockRegistryState(){this.registryStateLocked=!0}unlockRegistryState(){this.registryStateLocked=!1}resetRegistryState(){for(let[o,t]of this.registry)t.visible=!1,t.visited=!1,this.registry.set(o,t)}processCollections(){for(let[,o]of this.collections)for(let{flowId:t,visible:e}of o.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=o.flows.map(({flowId:c})=>c).filter(c=>c!==t);this.visit(t)}}register(o,t){if(Array.isArray(o)){this.batchRegister(o);return}this.registry.set(o,{callback:t!=null?t:()=>{},visible:!1,visited:!1}),this.registryStateLocked||this.resetRegistryState(),this.processCollections(),this.fireCallbacks()}batchRegister(o){o.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(o){this.registry.delete(o),this.resetRegistryState(),this.processCollections(),this.fireCallbacks()}visit(o,t=!0){var i;let e=(i=this.registry.get(o))!=null?i:{callback:()=>{},visible:t,visited:!0};e.visible=t,e.visited=!0,this.registry.set(o,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).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=F(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[F(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*(){it(),et(),t&&(yield this.updateConfig(t),this.mockFlowStates(F(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=F(this.config);if(!w[t]){let e=this,i={set:function(n,c,f){if(n[c]){let s=n[c],r=f;JSON.stringify(s)!==JSON.stringify(r)&&(e.triggerDeprecatedEventHandlers(r,s),e.triggerEventHandlers(r,s))}return n[c]=f,!0}};if(w[t]={refreshStateFromAPI:()=>p(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=n=>p(this,null,function*(){var s,r;if(this.config.__readOnly)return;let c=n||(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())})})),f=new Map;(r=(s=c.collections)==null?void 0:s.computedOrder)==null||r.forEach(({allowedComponents:g,collectionId:a,collectionType:l,flowId:u,visible:h})=>{var k;let b=(k=f.get(a))!=null?k:{allowedComponents:g,collectionType:l,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())),c&&c.eligibleFlows?(c.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 I({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 I({config:this.config,id:e}))})}updateConfig(t){return p(this,null,function*(){this.config=S(S({},this.config),t),w[F(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 c=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),n(i,c),this.getGlobalState().previousFlows.set(i.id,P(i))})})})}triggerEventHandlers(t,e){var i,n,c,f;if(t){for(let s of this.flows)if(s.id==t.flowSlug){let r=this.getGlobalState().previousFlows.get(s.id);s.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(l=>l(g,s,r));break;case"flow.restart":!t.$state.started&&(e==null?void 0:e.$state.started)===!0&&a.forEach(l=>l(g,s,r));break;case"flow.skip":t.$state.skipped&&(e==null?void 0:e.$state.skipped)===!1&&a.forEach(l=>l(g,s,r));break;case"flow.start":t.$state.started&&(e==null?void 0:e.$state.started)===!1&&a.forEach(l=>l(g,s,r));break;case"step.complete":for(let l of(i=t.data.steps)!=null?i:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===l.id);l.$state.completed&&u&&u.$state.completed!==l.$state.completed&&a.forEach(h=>h(g,s,r,s.steps.get(l.id)))}break;case"step.reset":for(let l of(n=t.data.steps)!=null?n:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===l.id);l.$state.started==!1&&!l.$state.lastActionAt&&u&&(u!=null&&u.$state.started)&&(u!=null&&u.$state.lastActionAt)&&a.forEach(h=>h(g,s,r,s.steps.get(l.id)))}break;case"step.skip":for(let l of(c=t.data.steps)!=null?c:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===l.id);l.$state.skipped&&u&&u.$state.skipped!==l.$state.skipped&&a.forEach(h=>h(g,s,r,s.steps.get(l.id)))}break;case"step.start":for(let l of(f=t.data.steps)!=null?f:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===l.id);l.$state.started&&u&&u.$state.started===!1&&a.forEach(h=>h(g,s,r,s.steps.get(l.id)))}break;case"flow.any":JSON.stringify(t)!==JSON.stringify(e!=null?e:{})&&a.forEach(l=>l(g,s,r));break}this.getGlobalState().previousFlows.set(s.id,P(s))}}}batchRegister(t){return p(this,null,function*(){let e=t.map(c=>p(this,[c],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)})})}};export{I as Flow,M as FlowStatus,U as FlowType,D as Frigade,L 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=(d,o,t)=>o in d?st(d,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[o]=t,S=(d,o)=>{for(var t in o||(o={}))at.call(o,t)&&H(d,t,o[t]);if(N)for(var t of N(o))nt.call(o,t)&&H(d,t,o[t]);return d},E=(d,o)=>ot(d,rt(o));var p=(d,o,t)=>new Promise((e,i)=>{var l=s=>{try{f(t.next(s))}catch(r){i(r)}},c=s=>{try{f(t.throw(s))}catch(r){i(r)}},f=s=>s.done?e(s.value):Promise.resolve(s.value).then(l,c);f((t=t.apply(d,o)).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=(n=>(n.ANNOUNCEMENT="ANNOUNCEMENT",n.CHECKLIST="CHECKLIST",n.FORM="FORM",n.TOUR="TOUR",n.SUPPORT="SUPPORT",n.CUSTOM="CUSTOM",n.BANNER="BANNER",n.EMBEDDED_TIP="EMBEDDED_TIP",n.NPS_SURVEY="NPS_SURVEY",n.SURVEY="SURVEY",n.CARD="CARD",n))(U||{});import{v4 as Q}from"uuid";var b={};function F(d){return`${d.__instanceId}-${d.apiKey}`}var T=class{constructor(o){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(o).filter(([e,i])=>i!=null));this.config=S(S({},this.config),t)}fetch(o,t){return p(this,null,function*(){return this.config.__readOnly?y():W(this.getAPIUrl(o),S(S({keepalive:!0},t!=null?t:{}),V(this.config)))})}getAPIUrl(o){return`${this.config.apiUrl.replace(/\/$/,"")}/${o.replace(/^\//,"")}`}getGlobalState(){let o=F(this.config);if(!b[o])throw new Error("Frigade has not yet been initialized");return b[o]}};var I=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,l,c,f,s,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=(l=e==null?void 0:e.data)==null?void 0:l.subtitle,this.type=(c=e==null?void 0:e.data)==null?void 0:c.type,this.props=(s=(f=e==null?void 0:e.data)==null?void 0:f.props)!=null?s:{},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,n)=>{var h;let a=this.initStepFromStatefulStep(g,n),u=(h=this.steps)==null?void 0:h.get(g.id);u&&Object.keys(a).forEach(w=>{u[w]=a[w]})}),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,l)=>{let c=this.initStepFromStatefulStep(i,l);c.start=s=>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(x,s,r.id)});let f=(s,r,g=!0)=>p(this,null,function*(){let n=this.steps.get(i.id);if((n.$state.completed||n.$state.skipped)&&g){let h=this.getStepByIndex(n.order+1);for(;h&&!h.$state.visible&&h.order!==this.steps.size-1;)h=this.getStepByIndex(h.order+1);if(h){let w=C(this.getGlobalState().flowStates[this.id]);w.$state.currentStepId=this.getStepByIndex(n.order+1).id,w.$state.currentStepIndex=n.order+1,w.data.steps[n.order+1].$state.started=!0,this.getGlobalState().flowStates[this.id]=w,yield this.sendFlowStateToAPI(x,void 0,h.id),this.resyncState()}return}let a=this.getCurrentStepOrder()+1===this.getNumberOfAvailableSteps(),u=Array.from(this.steps.values()).filter(h=>h.$state.visible&&!h.$state.completed&&!h.$state.skipped).length===1&&a;if(g){let h=C(this.getGlobalState().flowStates[this.id]);if(h.$state.started=!0,s=="complete"?h.data.steps[n.order].$state.completed=!0:h.data.steps[n.order].$state.skipped=!0,h.data.steps[n.order].$state.started=!0,h.data.steps[n.order].$state.lastActionAt=new Date,!a){let w=this.getNextVisibleStepIndexAfterIndex(n.order);w!==-1&&(h.$state.currentStepId=this.getStepByIndex(w).id,h.$state.currentStepIndex=w,h.data.steps[w].$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(s=="complete"?z:Y,r,n.id,u),u&&(yield this.sendFlowStateToAPI(_,r))});c.complete=(s,r=!0)=>p(this,null,function*(){yield f("complete",s,r)}),c.skip=(s,r=!0)=>p(this,null,function*(){yield f("skip",s,r)}),c.reset=()=>p(this,null,function*(){let s=this.steps.get(i.id);if(!s.$state.completed)return;let r=C(this.getGlobalState().flowStates[this.id]);r.data.steps[s.order].$state.started=!1,r.data.steps[s.order].$state.completed=!1,r.data.steps[s.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=r,this.resyncState(),yield this.sendFlowStateToAPI(q,void 0,s.id)}),c.onStateChange=s=>{let r=g=>{if(g.id!==this.id)return;let n=g.steps.get(i.id),a=this.lastStepUpdate.get(s);(n.$state.completed!==(a==null?void 0:a.$state.completed)||n.$state.started!==(a==null?void 0:a.$state.started)||n.$state.visible!==(a==null?void 0:a.$state.visible)||n.$state.blocked!==(a==null?void 0:a.$state.blocked))&&(s(n,a!=null?a:C(n)),this.lastStepUpdate.set(s,C(n)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(s,r),this.getGlobalState().onFlowStateChangeHandlers.push(r)},c.removeStateChangeHandler=s=>{let r=this.getGlobalState().onStepStateChangeHandlerWrappers.get(s);r&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(g=>g!==r))},e.set(i.id,c)}),this.steps=e,this.resyncState()}start(t){return p(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(J,t))})}complete(t){return p(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(_,t))})}skip(t){return p(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(K,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(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,l)=>{i.id===this.id&&(i.isCompleted!==(l==null?void 0:l.isCompleted)||i.isStarted!==(l==null?void 0:l.isStarted)||i.isSkipped!==(l==null?void 0:l.isSkipped)||i.isVisible!==(l==null?void 0:l.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(l==null?void 0:l.steps))&&t(i,l)};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 c,f;let i=s=>{let r=s.match(/\${(.*?)}/g);return r&&r.forEach(g=>{let n=g.replace("${","").replace("}","");if(!t[n]){s=s.replace(g,"");return}s=s.replace(g,t[n])}),s};this.title=i((c=this.title)!=null?c:""),this.subtitle=i((f=this.subtitle)!=null?f:"");let l=s=>{s&&Object.keys(s).forEach(r=>{typeof s[r]=="string"?s[r]=i(s[r]):typeof s[r]=="object"?l(s[r]):Array.isArray(s[r])&&s[r].forEach(g=>{l(g)})})};this.steps&&this.steps.forEach(s=>{try{l(s)}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,l){return p(this,null,function*(){var s;let c=new Date;this.getGlobalState().lastFlowSyncDate[this.id]=c,this.getGlobalState().pendingRequests[this.id]=((s=this.getGlobalState().pendingRequests[this.id])!=null?s:0)+1;let f=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:c,context:A(this.getGlobalState())})});this.getGlobalState().pendingRequests[this.id]-=1,!(l||c<this.getGlobalState().lastFlowSyncDate[this.id]||this.getGlobalState().pendingRequests[this.id]>0)&&(yield this.getGlobalState().refreshStateFromAPI(f))})}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 l=this.getGlobalState().previousFlows.get(this.id);(l==null?void 0:l._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(c=>{c(this,l),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.6";var q="NOT_STARTED_STEP",_="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(d){return new I({config:d.config,id:d.id})}function C(d){return JSON.parse(JSON.stringify(d))}function V(d){var o,t;return{headers:{Authorization:`Bearer ${d.apiKey}`,"Content-Type":"application/json","x-frigade-sdk-version":(o=d.__platformVersion)!=null?o:X,"x-frigade-sdk-platform":(t=d.__platformName)!=null?t:"Javascript"}}}function ct(d){if(m())try{return window.localStorage.getItem(`${$}${d}`)}catch(o){return console.debug("Error getting localStorage:",o),null}return null}function dt(d,o){if(m())try{window.localStorage.setItem(`${$}${d}`,o)}catch(t){console.debug("Error setting localStorage:",t)}}function et(){Object.keys(b).forEach(d=>{d.startsWith(lt)&&delete b[d]})}function it(){m()&&Object.keys(window.localStorage).forEach(d=>{d.startsWith($)&&window.localStorage.removeItem(d)})}var G=class{constructor(){this.queue=[];this.ttlInMS=250;this.cacheSize=10}push(o,t){let e=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:o,time:e.getTime(),response:t!=null?t:null})}hasIdenticalRecentCall(o){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.find(e=>e.call===o)}hasCall(o){return this.queue.find(t=>t.call===o)}cancelAllPendingRequests(){this.queue=[]}};globalThis.callQueue=new G;function W(d,o){return p(this,null,function*(){var l;if(typeof globalThis.fetch!="function")return y("- Attempted to call fetch() in an environment that doesn't support it.");let t=`${d}${JSON.stringify((l=o.body)!=null?l:{})}`,e,i=m()&&o&&o.body&&o.method==="POST";if(i){let c=globalThis.callQueue.hasIdenticalRecentCall(t);c!=null&&c.response!=null&&(e=(yield c.response).clone())}if(!e)try{let c=fetch(d,o);i&&globalThis.callQueue.push(t,c.then(f=>f.clone()).catch(()=>y())),e=yield c,i&&!globalThis.callQueue.hasCall(t)&&(e=y(tt))}catch(c){return y(c)}if(!e)return y("Received an empty response");if(e.status>=400)return y(e.statusText);try{if(e.status===204)return y();let c;try{c=yield e.json()}catch(f){return y()}return c.error?y(c.error):c}catch(c){return y(c)}})}function y(d){return d&&(d===tt?console.debug(d):console.warn("Call to Frigade failed:",d)),{json:()=>({}),clone:()=>({})}}function B(){if(m()){let d=ct(Z);return d||(d=`${v}${Q()}`,dt(Z,d)),d}else return`${v}${Q()}`}function m(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function A(d){let o={registeredCollectionIds:Array.from(d.registeredCollectionIds)};return m()?S({url:d.currentUrl,userAgent:navigator.userAgent},o):o}var R=class{constructor(o){this.registry=new Map;this.registryStateLocked=!1;this.collections=new Map;this.flowsInCollections=new Set;this.hasChanges=!1;this.ingestCollectionsData(o)}getCollection(o){return this.collections.get(o)}getCollections(){return this.collections}collectionsHaveChanged(){return this.hasChanges}ingestCollectionsData(o){if(this.hasChanges=!0,this.checkIfCollectionsHaveChanged(o),!!this.hasChanges){this.collections=o;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(o){var i,l,c,f,s,r;let t=this.collections,e=o;t.size!==e.size&&(this.hasChanges=!0);for(let[g,n]of t){let a=e.get(g);if(((i=n==null?void 0:n.flows)==null?void 0:i.length)!==((l=a==null?void 0:a.flows)==null?void 0:l.length)){this.hasChanges=!0;break}for(let u=0;u<n.flows.length;u++)if(((c=n==null?void 0:n.flows[u])==null?void 0:c.flowId)!==((f=a==null?void 0:a.flows[u])==null?void 0:f.flowId)||((s=n==null?void 0:n.flows[u])==null?void 0:s.visible)!==((r=a==null?void 0:a.flows[u])==null?void 0:r.visible)){this.hasChanges=!0;break}}}fireCallbacks(){for(let[o,{callback:t}]of this.registry)typeof t=="function"&&t(this.isFlowVisible(o))}isFlowVisible(o){let t=this.registry.get(o),e=this.flowsInCollections.has(o);return t==null||!e?!0:t.visible}lockRegistryState(){this.registryStateLocked=!0}unlockRegistryState(){this.registryStateLocked=!1}resetRegistryState(){for(let[o,t]of this.registry)t.visible=!1,t.visited=!1,this.registry.set(o,t)}processCollections(){for(let[,o]of this.collections)for(let{flowId:t,visible:e}of o.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 l=o.flows.map(({flowId:c})=>c).filter(c=>c!==t);this.visit(t)}}register(o,t){if(Array.isArray(o)){this.batchRegister(o);return}this.registry.set(o,{callback:t!=null?t:()=>{},visible:!1,visited:!1}),this.registryStateLocked||this.resetRegistryState(),this.processCollections(),this.fireCallbacks()}batchRegister(o){o.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(o){this.registry.delete(o),this.resetRegistryState(),this.processCollections(),this.fireCallbacks()}visit(o,t=!0){var i;let e=(i=this.registry.get(o))!=null?i:{callback:()=>{},visible:t,visited:!0};e.visible=t,e.visited=!0,this.registry.set(o,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).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(l){}})):new MutationObserver(()=>{try{if(this.getGlobalState().currentUrl===location.href||location.href&&this.getGlobalState().currentUrl&&location.href.split("#")[0]===this.getGlobalState().currentUrl.split("#")[0])return;this.queueRefreshStateFromAPI()}catch(i){}}).observe(document,{subtree:!0,childList:!0}))})}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=F(this.config);b[t]&&(b[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&&b[F(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(l=>p(this,null,function*(){return E(S({},l),{flow:yield this.getFlow(l.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*(){it(),et(),t&&(yield this.updateConfig(t),this.mockFlowStates(F(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(l=>l!==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=F(this.config);if(!b[t]){let e=this,i={set:function(l,c,f){if(l[c]){let s=l[c],r=f;JSON.stringify(s)!==JSON.stringify(r)&&(e.triggerDeprecatedEventHandlers(r,s),e.triggerEventHandlers(r,s))}return l[c]=f,!0}};if(b[t]={refreshStateFromAPI:()=>p(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}b[t].refreshStateFromAPI=l=>p(this,null,function*(){var s,r;if(this.config.__readOnly)return;let c=l||(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())})})),f=new Map;(r=(s=c.collections)==null?void 0:s.computedOrder)==null||r.forEach(({allowedComponents:g,collectionId:n,collectionType:a,flowId:u,visible:h})=>{var k;let w=(k=f.get(n))!=null?k:{allowedComponents:g,collectionType:a,flows:[]};w.flows.push({flowId:u,visible:h}),f.set(n,w)}),f.size>0&&(b[t].collections.ingestCollectionsData(f),b[t].collections.collectionsHaveChanged()&&!l&&(this.triggerAllLegacyEventHandlers(),this.triggerAllEventHandlers())),c&&c.eligibleFlows?(c.eligibleFlows.forEach(g=>{var n;((n=b[t].pendingRequests[g.flowSlug])!=null?n:0)>0||(b[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 I({config:this.config,id:g.flowSlug})))}),this.hasFailed=!1):this.hasFailed=!0})}yield b[t].refreshStateFromAPI(void 0)})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{b[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 I({config:this.config,id:e}))})}updateConfig(t){return p(this,null,function*(){this.config=S(S({},this.config),t),b[F(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(l=>{let c=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),l(i,c),this.getGlobalState().previousFlows.set(i.id,P(i))})})})}triggerEventHandlers(t,e){var i,l,c,f;if(t){for(let s of this.flows)if(s.id==t.flowSlug){let r=this.getGlobalState().previousFlows.get(s.id);s.resyncState(t);for(let[g,n]of this.eventHandlers.entries())switch(g){case"flow.complete":t.$state.completed&&(e==null?void 0:e.$state.completed)===!1&&n.forEach(a=>a(g,s,r));break;case"flow.restart":!t.$state.started&&(e==null?void 0:e.$state.started)===!0&&n.forEach(a=>a(g,s,r));break;case"flow.skip":t.$state.skipped&&(e==null?void 0:e.$state.skipped)===!1&&n.forEach(a=>a(g,s,r));break;case"flow.start":t.$state.started&&(e==null?void 0:e.$state.started)===!1&&n.forEach(a=>a(g,s,r));break;case"step.complete":for(let a of(i=t.data.steps)!=null?i:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===a.id);a.$state.completed&&u&&u.$state.completed!==a.$state.completed&&n.forEach(h=>h(g,s,r,s.steps.get(a.id)))}break;case"step.reset":for(let a of(l=t.data.steps)!=null?l:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===a.id);a.$state.started==!1&&!a.$state.lastActionAt&&u&&(u!=null&&u.$state.started)&&(u!=null&&u.$state.lastActionAt)&&n.forEach(h=>h(g,s,r,s.steps.get(a.id)))}break;case"step.skip":for(let a of(c=t.data.steps)!=null?c:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===a.id);a.$state.skipped&&u&&u.$state.skipped!==a.$state.skipped&&n.forEach(h=>h(g,s,r,s.steps.get(a.id)))}break;case"step.start":for(let a of(f=t.data.steps)!=null?f:[]){let u=e==null?void 0:e.data.steps.find(h=>h.id===a.id);a.$state.started&&u&&u.$state.started===!1&&n.forEach(h=>h(g,s,r,s.steps.get(a.id)))}break;case"flow.any":JSON.stringify(t)!==JSON.stringify(e!=null?e:{})&&n.forEach(a=>a(g,s,r));break}this.getGlobalState().previousFlows.set(s.id,P(s))}}}batchRegister(t){return p(this,null,function*(){let e=t.map(c=>p(this,[c],function*([i,l]){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(n=>{n(f,g),this.getGlobalState().previousFlows.set(i,P(f))}),l==null||l(r)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};export{I as Flow,M as FlowStatus,U as FlowType,D as Frigade,L as TriggerType};
3
3
  //# sourceMappingURL=index.js.map