@frigade/js 0.5.1 → 0.5.2
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 +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
var R=Object.defineProperty,st=Object.defineProperties,rt=Object.getOwnPropertyDescriptor,at=Object.getOwnPropertyDescriptors,ot=Object.getOwnPropertyNames,L=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var M=(r,s,t)=>s in r?R(r,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[s]=t,h=(r,s)=>{for(var t in s||(s={}))N.call(s,t)&&M(r,t,s[t]);if(L)for(var t of L(s))nt.call(s,t)&&M(r,t,s[t]);return r},b=(r,s)=>st(r,at(s));var lt=(r,s)=>{for(var t in s)R(r,t,{get:s[t],enumerable:!0})},ct=(r,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of ot(s))!N.call(r,i)&&i!==t&&R(r,i,{get:()=>s[i],enumerable:!(e=rt(s,i))||e.enumerable});return r};var gt=r=>ct(R({},"__esModule",{value:!0}),r);var g=(r,s,t)=>new Promise((e,i)=>{var a=l=>{try{n(t.next(l))}catch(c){i(c)}},d=l=>{try{n(t.throw(l))}catch(c){i(c)}},n=l=>l.done?e(l.value):Promise.resolve(l.value).then(a,d);n((t=t.apply(r,s)).next())});var ft={};lt(ft,{Flow:()=>y,FlowStatus:()=>_,FlowType:()=>D,Frigade:()=>T,TriggerType:()=>x});module.exports=gt(ft);var U="0.2.20";var A=require("uuid");var f={};function m(r){return`${r.__instanceId}-${r.apiKey}`}var F=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:V(),__instanceId:Math.random().toString(12).substring(4),generateGuestId:!0};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));!s.userId&&s.generateGuestId===!1&&delete this.config.userId,this.config=h(h({},this.config),t)}fetch(s,t){return g(this,null,function*(){return this.config.__readOnly?u():W(this.getAPIUrl(s),h(h({keepalive:!0},t!=null?t:{}),H(this.config.apiKey)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=m(this.config);if(!f[s])throw new Error("Frigade has not yet been initialized");return f[s]}};var y=class extends F{constructor({config:t,id:e}){super(t);this._isVisible=!1;this.lastStepUpdate=new Map;this.id=e,this.init()}get isVisible(){return this._isVisible===!1?!1:this.getGlobalState().collections.isFlowVisible(this.id)}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,a,d;let e=t!=null?t:this.getStatefulFlow();this.rawData=e,this.title=(i=e==null?void 0:e.data)==null?void 0:i.title,this.subtitle=(a=e==null?void 0:e.data)==null?void 0:a.subtitle,this.isCompleted=e.$state.completed,this.isStarted=e.$state.started,this.isSkipped=e.$state.skipped,this._isVisible=e.$state.visible,e.data.steps.forEach((n,l)=>{var o;let c=this.initStepFromStatefulStep(n,l),p=(o=this.steps)==null?void 0:o.get(n.id);p&&Object.keys(c).forEach(P=>{p[P]=c[P]})}),this.steps&&this.steps.size>0&&this.applyVariables((d=this.getGlobalState().variables[this.id])!=null?d:{})}initStepFromStatefulStep(t,e){return b(h({},t),{flow:this,$state:b(h({},t.$state),{lastActionAt:t.$state.lastActionAt?new Date(t.$state.lastActionAt):void 0}),order:e})}init(){let t=this.getStatefulFlow();this.resyncState();let e=new Map;t.data.steps.forEach((i,a)=>{let d=this.initStepFromStatefulStep(i,a);d.start=n=>g(this,null,function*(){let l=this.steps.get(i.id);if(this.getCurrentStep().id===l.id&&l.$state.started)return;let c=S(this.getGlobalState().flowStates[this.id]);c.data.steps[l.order].$state.started=!0,c.data.steps[l.order].$state.lastActionAt=new Date,c.$state.lastActionAt=new Date,c.$state.currentStepId=l.id,c.$state.currentStepIndex=l.order,this.getGlobalState().flowStates[this.id]=c,this.resyncState(),yield this.sendFlowStateToAPI(X,n,l.id)}),d.complete=(n,l=!0)=>g(this,null,function*(){let c=this.steps.get(i.id);if(!(c.$state.completed&&l)){if(l){let p=c.order+1===this.getNumberOfAvailableSteps(),o=S(this.getGlobalState().flowStates[this.id]);o.$state.started=!0,o.data.steps[c.order].$state.completed=!0,o.data.steps[c.order].$state.started=!0,o.data.steps[c.order].$state.lastActionAt=new Date,p||(o.$state.currentStepId=this.getStepByIndex(c.order+1).id,o.$state.currentStepIndex=c.order+1),p&&(o.$state.completed=!0),this.getGlobalState().flowStates[this.id]=o,this.resyncState(),p&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(z,n,c.id)}}),d.reset=()=>g(this,null,function*(){let n=this.steps.get(i.id);if(!n.$state.completed)return;let l=S(this.getGlobalState().flowStates[this.id]);l.data.steps[n.order].$state.started=!1,l.data.steps[n.order].$state.completed=!1,l.data.steps[n.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=l,this.resyncState(),yield this.sendFlowStateToAPI(B,void 0,n.id)}),d.onStateChange=n=>{let l=c=>{if(c.id!==this.id)return;let p=c.steps.get(i.id),o=this.lastStepUpdate.get(n);(p.$state.completed!==(o==null?void 0:o.$state.completed)||p.$state.started!==(o==null?void 0:o.$state.started)||p.$state.visible!==(o==null?void 0:o.$state.visible)||p.$state.blocked!==(o==null?void 0:o.$state.blocked))&&(n(p,o!=null?o:S(p)),this.lastStepUpdate.set(n,S(p)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(n,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},d.removeStateChangeHandler=n=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(n);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(c=>c!==l))},e.set(i.id,d)}),this.steps=e,this.getGlobalState().variables&&this.getGlobalState().variables[this.id]&&Object.keys(this.getGlobalState().variables[this.id]).length>0&&this.applyVariables(this.getGlobalState().variables[this.id])}start(t){return g(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(J,t))})}complete(t){return g(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(K,t))})}skip(t){return g(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(j,t))})}forward(t){return g(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()+1);e?yield e.start(t):yield this.complete(t)})}back(t){return g(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()-1);e&&(yield e.start(t))})}restart(){return g(this,null,function*(){this.optimisticallyMarkFlowNotStarted(),yield this.sendFlowStateToAPI(q)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){var t;return(t=this.steps.get(this.getStatefulFlow().$state.currentStepId))!=null?t:this.steps.get(Array.from(this.steps.keys())[0])}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}onStateChange(t){let e=(i,a)=>{i.id===this.id&&(i.isCompleted!==(a==null?void 0:a.isCompleted)||i.isStarted!==(a==null?void 0:a.isStarted)||i.isSkipped!==(a==null?void 0:a.isSkipped)||i.isVisible!==(a==null?void 0:a.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(a==null?void 0:a.steps))&&t(i,a)};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){var i,a;let e=d=>{let n=d.match(/\${(.*?)}/g);return n&&n.forEach(l=>{let c=l.replace("${","").replace("}","");t[c]&&(d=d.replace(l,t[c]))}),d};this.title=e((i=this.title)!=null?i:""),this.subtitle=e((a=this.subtitle)!=null?a:""),this.steps.forEach(d=>{Object.keys(d).forEach(n=>{typeof d[n]=="string"&&(d[n]=e(d[n]))})}),this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.completed=!0,t.$state.started=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowStarted(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowNotStarted(){var e;let t=S(this.getGlobalState().flowStates[this.id]);t.$state.completed=!1,t.$state.started=!1,t.$state.visible=!0,t.$state.currentStepIndex=0,t.$state.currentStepId=(e=this.getStepByIndex(0))==null?void 0:e.id,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return g(this,null,function*(){let a=new Date;this.getGlobalState().lastSyncDate=a;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!=null?i:this.getCurrentStep().id,data:e||{},actionType:t,createdAt:a,context:I(this.getGlobalState().currentUrl)})});a<this.getGlobalState().lastSyncDate||(yield this.getGlobalState().refreshStateFromAPI(d))})}optimisticallyMarkFlowSkipped(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.skipped=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}register(t){this.getGlobalState().collections.register(this.id,i=>{let a=this.getGlobalState().previousFlows.get(this.id);(a==null?void 0:a._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(d=>{d(this,a),this.getGlobalState().previousFlows.set(this.id,C(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var B="NOT_STARTED_STEP",K="COMPLETED_FLOW",j="SKIPPED_FLOW",J="STARTED_FLOW",q="NOT_STARTED_FLOW",z="COMPLETED_STEP",X="STARTED_STEP",Y="frigade-guest-key",v="guest_",dt="get-cache-",G="fr-js-";function C(r){return new y({config:r.config,id:r.id})}function S(r){return JSON.parse(JSON.stringify(r))}function H(r){return{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","X-Frigade-SDK-Version":U,"X-Frigade-SDK-Platform":"Javascript"}}}function pt(r){return w()?window.localStorage.getItem(`${G}${r}`):null}function ht(r,s){w()&&window.localStorage.setItem(`${G}${r}`,s)}function Z(){Object.keys(f).forEach(r=>{r.startsWith(dt)&&delete f[r]})}function tt(){w()&&Object.keys(window.localStorage).forEach(r=>{r.startsWith(G)&&window.localStorage.removeItem(r)})}var O=class{constructor(){this.queue=[];this.ttlInMS=100;this.cacheSize=5}push(s){let t=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:t.getTime()})}hasIdenticalCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.some(e=>e.call===s)}},Q=new O;function W(r,s){return g(this,null,function*(){var e;if(typeof globalThis.fetch!="function")return u("- Attempted to call fetch() in an environment that doesn't support it.");if(w()&&s&&s.body&&s.method==="POST"){let i=`${r}${JSON.stringify((e=s.body)!=null?e:{})}`;if(Q.hasIdenticalCall(i))return u();Q.push(i)}let t;try{t=fetch(r,s),t=yield t}catch(i){return u(i)}if(!t)return u("Received an empty response");if(t.status>=400)return u(t.statusText);try{if(t.status===204)return u();let i;try{i=yield t.json()}catch(a){return u()}return i.error?u(i.error):i}catch(i){return u(i)}})}function u(r){return r&&console.log("Call to Frigade failed",r),{json:()=>({})}}function V(){if(w()){let r=pt(Y);return r||(r=`${v}${(0,A.v4)()}`,ht(Y,r)),r}else return`${v}${(0,A.v4)()}`}function w(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function I(r){return w()?{url:r,userAgent:navigator.userAgent}:{}}var E=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.rules=new Map;this.flowsInRules=new Set;this.ingestRulesData(s)}getRule(s){return this.rules.get(s)}getRules(){return this.rules}ingestRulesData(s){this.rules=s;for(let[,t]of this.rules)for(let{flowId:e}of t.flows)this.flowsInRules.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processRules()),this.fireCallbacks()}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.flowsInRules.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)}processRules(){for(let[,s]of this.rules)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;if(s.flows.map(({flowId:n})=>n).filter(n=>n!==t).some(n=>{var p;let{visible:l,visited:c}=(p=this.registry.get(n))!=null?p:{};return l&&c})){this.visit(t,!1);continue}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.processRules(),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.processRules(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processRules(),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 T=class extends F{constructor(t,e){super(h({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>g(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),w()&&this.config.syncOnWindowUpdates!==!1&&(document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.navigation&&window.navigation.addEventListener("navigate",i=>g(this,null,function*(){this.getGlobalState().currentUrl!==i.destination.url&&(this.getGlobalState().currentUrl=i.destination.url,this.refreshStateFromAPI())})))}getConfig(){return this.config}destroy(){if(w()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=m(this.config);f[t]&&(f[t].onFlowStateChangeHandlers=[])}}init(t){return g(this,null,function*(){if(this.updateConfig(h(h({},this.config),t)),!(!this.config.userId&&this.config.generateGuestId===!1))return this.initPromise=(()=>g(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 g(this,null,function*(){yield this.updateConfig(b(h({},this.config),{userId:t})),yield this.initIfNeeded(),yield this.session({userId:this.config.userId,userProperties:e}),yield this.resync()})}group(t,e){return g(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(b(h({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties:e}),yield this.resync()})}track(t,e){return g(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 g(this,null,function*(){yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)})})}isReady(){return!!(this.config.__instanceId&&this.config.apiKey&&this.initPromise)}getFlow(t){return g(this,null,function*(){return yield this.initIfNeeded(),this.flows.find(e=>e.id==t)})}getFlows(){return g(this,null,function*(){return yield this.initIfNeeded(),this.flows})}getCollection(t){return g(this,null,function*(){yield this.initIfNeeded();let e=this.getGlobalState().collections.getRule(t);if(e==null)return;let i=yield Promise.all(e.flows.map(a=>g(this,null,function*(){return b(h({},a),{flow:yield this.getFlow(a.flowId)})})));return e.flows=i,e})}getCollections(){return g(this,null,function*(){yield this.initIfNeeded();let t=this.getGlobalState().collections.getRules();if(t!=null)return t})}reload(t){return g(this,null,function*(){tt(),Z(),t&&(yield this.updateConfig(t),this.mockFlowStates(m(this.config))),this.initPromise=null,yield this.init(this.config),this.flows.forEach(e=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(i=>{let a=this.getGlobalState().previousFlows.get(e.id);i(e,a),this.getGlobalState().previousFlows.set(e.id,C(e))})})})}resync(){return g(this,null,function*(){yield this.refreshStateFromAPI()})}onStateChange(t){return g(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return g(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return g(this,null,function*(){return this.initPromise?this.initPromise:this.init(this.config)})}refreshStateFromAPI(){return g(this,null,function*(){let t=m(this.config);if(!f[t]){let e=this,i={set:function(a,d,n){if(a[d]){let l=a[d],c=n;JSON.stringify(l)!==JSON.stringify(c)&&e.triggerEventHandlers(c,l)}return a[d]=n,!0}};if(f[t]={refreshStateFromAPI:()=>g(this,null,function*(){}),collections:new E(new Map),flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config,currentUrl:w()?window.location.href:""},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(t);return}f[t].refreshStateFromAPI=a=>g(this,null,function*(){var l,c;if(this.config.__readOnly)return;let d=a||(yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,context:I(this.getGlobalState().currentUrl)})})),n=new Map;(c=(l=d.collections)==null?void 0:l.computedOrder)==null||c.forEach(({allowedComponents:p,collectionId:o,collectionType:P,flowId:et,visible:it})=>{var k;let $=(k=n.get(o))!=null?k:{allowedComponents:p,collectionType:P,flows:[]};$.flows.push({flowId:et,visible:it}),n.set(o,$)}),f[t].collections.ingestRulesData(n),d&&d.eligibleFlows?(d.eligibleFlows.forEach(p=>{f[t].flowStates[p.flowSlug]=p,this.flows.find(o=>o.id==p.flowSlug)?this.flows.forEach(o=>{o.id==p.flowSlug&&o.resyncState(p)}):this.flows.push(new y({config:this.config,id:p.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield f[t].refreshStateFromAPI()})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{f[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 y({config:this.config,id:e}))})}updateConfig(t){return g(this,null,function*(){this.config=h(h({},this.config),t),f[m(this.config)]&&(this.getGlobalState().config=this.config)})}triggerEventHandlers(t,e){return g(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(a=>{let d=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),a(i,d),this.getGlobalState().previousFlows.set(i.id,C(i))})})})}batchRegister(t){return g(this,null,function*(){let e=t.map(d=>g(this,[d],function*([i,a]){let n=yield this.getFlow(i);return[i,c=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==c&&this.getGlobalState().onFlowStateChangeHandlers.forEach(o=>{o(n,p),this.getGlobalState().previousFlows.set(i,C(n))}),a==null||a(c)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};var x=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(x||{}),_=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(_||{});var D=(o=>(o.ANNOUNCEMENT="ANNOUNCEMENT",o.CHECKLIST="CHECKLIST",o.FORM="FORM",o.TOUR="TOUR",o.SUPPORT="SUPPORT",o.CUSTOM="CUSTOM",o.BANNER="BANNER",o.EMBEDDED_TIP="EMBEDDED_TIP",o.NPS_SURVEY="NPS_SURVEY",o.SURVEY="SURVEY",o.CARD="CARD",o))(D||{});0&&(module.exports={Flow,FlowStatus,FlowType,Frigade,TriggerType});
|
|
2
|
+
var R=Object.defineProperty,st=Object.defineProperties,rt=Object.getOwnPropertyDescriptor,at=Object.getOwnPropertyDescriptors,ot=Object.getOwnPropertyNames,L=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var M=(r,s,t)=>s in r?R(r,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[s]=t,h=(r,s)=>{for(var t in s||(s={}))N.call(s,t)&&M(r,t,s[t]);if(L)for(var t of L(s))nt.call(s,t)&&M(r,t,s[t]);return r},b=(r,s)=>st(r,at(s));var lt=(r,s)=>{for(var t in s)R(r,t,{get:s[t],enumerable:!0})},ct=(r,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of ot(s))!N.call(r,i)&&i!==t&&R(r,i,{get:()=>s[i],enumerable:!(e=rt(s,i))||e.enumerable});return r};var gt=r=>ct(R({},"__esModule",{value:!0}),r);var g=(r,s,t)=>new Promise((e,i)=>{var a=l=>{try{n(t.next(l))}catch(c){i(c)}},d=l=>{try{n(t.throw(l))}catch(c){i(c)}},n=l=>l.done?e(l.value):Promise.resolve(l.value).then(a,d);n((t=t.apply(r,s)).next())});var ft={};lt(ft,{Flow:()=>y,FlowStatus:()=>_,FlowType:()=>D,Frigade:()=>T,TriggerType:()=>x});module.exports=gt(ft);var U="0.2.20";var A=require("uuid");var f={};function m(r){return`${r.__instanceId}-${r.apiKey}`}var F=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:V(),__instanceId:Math.random().toString(12).substring(4),generateGuestId:!0};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));!s.userId&&s.generateGuestId===!1&&delete this.config.userId,this.config=h(h({},this.config),t)}fetch(s,t){return g(this,null,function*(){return this.config.__readOnly?u():W(this.getAPIUrl(s),h(h({keepalive:!0},t!=null?t:{}),H(this.config.apiKey)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=m(this.config);if(!f[s])throw new Error("Frigade has not yet been initialized");return f[s]}};var y=class extends F{constructor({config:t,id:e}){super(t);this._isVisible=!1;this.lastStepUpdate=new Map;this.id=e,this.init()}get isVisible(){return this._isVisible===!1?!1:this.getGlobalState().collections.isFlowVisible(this.id)}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,a,d;let e=t!=null?t:this.getStatefulFlow();this.rawData=e,this.title=(i=e==null?void 0:e.data)==null?void 0:i.title,this.subtitle=(a=e==null?void 0:e.data)==null?void 0:a.subtitle,this.isCompleted=e.$state.completed,this.isStarted=e.$state.started,this.isSkipped=e.$state.skipped,this._isVisible=e.$state.visible,e.data.steps.forEach((n,l)=>{var o;let c=this.initStepFromStatefulStep(n,l),p=(o=this.steps)==null?void 0:o.get(n.id);p&&Object.keys(c).forEach(P=>{p[P]=c[P]})}),this.steps&&this.steps.size>0&&this.applyVariables((d=this.getGlobalState().variables[this.id])!=null?d:{})}initStepFromStatefulStep(t,e){return b(h({},t),{flow:this,$state:b(h({},t.$state),{lastActionAt:t.$state.lastActionAt?new Date(t.$state.lastActionAt):void 0}),order:e})}init(){let t=this.getStatefulFlow();this.resyncState();let e=new Map;t.data.steps.forEach((i,a)=>{let d=this.initStepFromStatefulStep(i,a);d.start=n=>g(this,null,function*(){let l=this.steps.get(i.id);if(this.getCurrentStep().id===l.id&&l.$state.started)return;let c=S(this.getGlobalState().flowStates[this.id]);c.data.steps[l.order].$state.started=!0,c.data.steps[l.order].$state.lastActionAt=new Date,c.$state.lastActionAt=new Date,c.$state.currentStepId=l.id,c.$state.currentStepIndex=l.order,this.getGlobalState().flowStates[this.id]=c,this.resyncState(),yield this.sendFlowStateToAPI(X,n,l.id)}),d.complete=(n,l=!0)=>g(this,null,function*(){let c=this.steps.get(i.id);if(!(c.$state.completed&&l)){if(l){let p=c.order+1===this.getNumberOfAvailableSteps(),o=S(this.getGlobalState().flowStates[this.id]);o.$state.started=!0,o.data.steps[c.order].$state.completed=!0,o.data.steps[c.order].$state.started=!0,o.data.steps[c.order].$state.lastActionAt=new Date,p||(o.$state.currentStepId=this.getStepByIndex(c.order+1).id,o.$state.currentStepIndex=c.order+1),p&&(o.$state.completed=!0),this.getGlobalState().flowStates[this.id]=o,this.resyncState(),p&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(z,n,c.id)}}),d.reset=()=>g(this,null,function*(){let n=this.steps.get(i.id);if(!n.$state.completed)return;let l=S(this.getGlobalState().flowStates[this.id]);l.data.steps[n.order].$state.started=!1,l.data.steps[n.order].$state.completed=!1,l.data.steps[n.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=l,this.resyncState(),yield this.sendFlowStateToAPI(B,void 0,n.id)}),d.onStateChange=n=>{let l=c=>{if(c.id!==this.id)return;let p=c.steps.get(i.id),o=this.lastStepUpdate.get(n);(p.$state.completed!==(o==null?void 0:o.$state.completed)||p.$state.started!==(o==null?void 0:o.$state.started)||p.$state.visible!==(o==null?void 0:o.$state.visible)||p.$state.blocked!==(o==null?void 0:o.$state.blocked))&&(n(p,o!=null?o:S(p)),this.lastStepUpdate.set(n,S(p)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(n,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},d.removeStateChangeHandler=n=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(n);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(c=>c!==l))},e.set(i.id,d)}),this.steps=e,this.getGlobalState().variables&&this.getGlobalState().variables[this.id]&&Object.keys(this.getGlobalState().variables[this.id]).length>0&&this.applyVariables(this.getGlobalState().variables[this.id])}start(t){return g(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(J,t))})}complete(t){return g(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(K,t))})}skip(t){return g(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(j,t))})}forward(t){return g(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()+1);e?yield e.start(t):yield this.complete(t)})}back(t){return g(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()-1);e&&(yield e.start(t))})}restart(){return g(this,null,function*(){this.optimisticallyMarkFlowNotStarted(),yield this.sendFlowStateToAPI(q)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){var t;return(t=this.steps.get(this.getStatefulFlow().$state.currentStepId))!=null?t:this.steps.get(Array.from(this.steps.keys())[0])}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}onStateChange(t){let e=(i,a)=>{i.id===this.id&&(i.isCompleted!==(a==null?void 0:a.isCompleted)||i.isStarted!==(a==null?void 0:a.isStarted)||i.isSkipped!==(a==null?void 0:a.isSkipped)||i.isVisible!==(a==null?void 0:a.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(a==null?void 0:a.steps))&&t(i,a)};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){var i,a;let e=d=>{let n=d.match(/\${(.*?)}/g);return n&&n.forEach(l=>{let c=l.replace("${","").replace("}","");t[c]&&(d=d.replace(l,t[c]))}),d};this.title=e((i=this.title)!=null?i:""),this.subtitle=e((a=this.subtitle)!=null?a:""),this.steps.forEach(d=>{Object.keys(d).forEach(n=>{typeof d[n]=="string"&&(d[n]=e(d[n]))})}),this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.completed=!0,t.$state.started=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowStarted(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowNotStarted(){var e;let t=S(this.getGlobalState().flowStates[this.id]);t.$state.completed=!1,t.$state.started=!1,t.$state.visible=!0,t.$state.currentStepIndex=0,t.$state.currentStepId=(e=this.getStepByIndex(0))==null?void 0:e.id,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return g(this,null,function*(){let a=new Date;this.getGlobalState().lastSyncDate=a;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!=null?i:this.getCurrentStep().id,data:e||{},actionType:t,createdAt:a,context:I(this.getGlobalState().currentUrl)})});a<this.getGlobalState().lastSyncDate||(yield this.getGlobalState().refreshStateFromAPI(d))})}optimisticallyMarkFlowSkipped(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.skipped=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}register(t){this.getGlobalState().collections.register(this.id,i=>{let a=this.getGlobalState().previousFlows.get(this.id);(a==null?void 0:a._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(d=>{d(this,a),this.getGlobalState().previousFlows.set(this.id,C(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var B="NOT_STARTED_STEP",K="COMPLETED_FLOW",j="SKIPPED_FLOW",J="STARTED_FLOW",q="NOT_STARTED_FLOW",z="COMPLETED_STEP",X="STARTED_STEP",Y="frigade-guest-key",v="guest_",dt="get-cache-",G="fr-js-";function C(r){return new y({config:r.config,id:r.id})}function S(r){return JSON.parse(JSON.stringify(r))}function H(r){return{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","X-Frigade-SDK-Version":U,"X-Frigade-SDK-Platform":"Javascript"}}}function pt(r){return w()?window.localStorage.getItem(`${G}${r}`):null}function ht(r,s){w()&&window.localStorage.setItem(`${G}${r}`,s)}function Z(){Object.keys(f).forEach(r=>{r.startsWith(dt)&&delete f[r]})}function tt(){w()&&Object.keys(window.localStorage).forEach(r=>{r.startsWith(G)&&window.localStorage.removeItem(r)})}var O=class{constructor(){this.queue=[];this.ttlInMS=100;this.cacheSize=5}push(s){let t=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:t.getTime()})}hasIdenticalCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.some(e=>e.call===s)}},Q=new O;function W(r,s){return g(this,null,function*(){var e;if(typeof globalThis.fetch!="function")return u("- Attempted to call fetch() in an environment that doesn't support it.");if(w()&&s&&s.body&&s.method==="POST"){let i=`${r}${JSON.stringify((e=s.body)!=null?e:{})}`;if(Q.hasIdenticalCall(i))return u();Q.push(i)}let t;try{t=fetch(r,s),t=yield t}catch(i){return u(i)}if(!t)return u("Received an empty response");if(t.status>=400)return u(t.statusText);try{if(t.status===204)return u();let i;try{i=yield t.json()}catch(a){return u()}return i.error?u(i.error):i}catch(i){return u(i)}})}function u(r){return r&&console.log("Call to Frigade failed",r),{json:()=>({})}}function V(){if(w()){let r=pt(Y);return r||(r=`${v}${(0,A.v4)()}`,ht(Y,r)),r}else return`${v}${(0,A.v4)()}`}function w(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function I(r){return w()?{url:r,userAgent:navigator.userAgent}:{}}var E=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.rules=new Map;this.flowsInRules=new Set;this.ingestRulesData(s)}getRule(s){return this.rules.get(s)}getRules(){return this.rules}ingestRulesData(s){this.rules=s;for(let[,t]of this.rules)for(let{flowId:e}of t.flows)this.flowsInRules.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processRules()),this.fireCallbacks()}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.flowsInRules.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)}processRules(){for(let[,s]of this.rules)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;if(s.flows.map(({flowId:n})=>n).filter(n=>n!==t).some(n=>{var p;let{visible:l,visited:c}=(p=this.registry.get(n))!=null?p:{};return l&&c})){this.visit(t,!1);continue}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.processRules(),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.processRules(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processRules(),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 T=class extends F{constructor(t,e){super(h({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>g(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),w()&&this.config.syncOnWindowUpdates!==!1&&(document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.navigation&&window.navigation.addEventListener("navigate",i=>g(this,null,function*(){if(this.getGlobalState().currentUrl!==i.destination.url)try{this.getGlobalState().currentUrl=i.destination.url,this.refreshStateFromAPI()}catch(a){}})))}getConfig(){return this.config}destroy(){if(w()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=m(this.config);f[t]&&(f[t].onFlowStateChangeHandlers=[])}}init(t){return g(this,null,function*(){if(this.updateConfig(h(h({},this.config),t)),!(!this.config.userId&&this.config.generateGuestId===!1))return this.initPromise=(()=>g(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 g(this,null,function*(){yield this.updateConfig(b(h({},this.config),{userId:t})),yield this.initIfNeeded(),yield this.session({userId:this.config.userId,userProperties:e}),yield this.resync()})}group(t,e){return g(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(b(h({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties:e}),yield this.resync()})}track(t,e){return g(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 g(this,null,function*(){yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)})})}isReady(){return!!(this.config.__instanceId&&this.config.apiKey&&this.initPromise)}getFlow(t){return g(this,null,function*(){return yield this.initIfNeeded(),this.flows.find(e=>e.id==t)})}getFlows(){return g(this,null,function*(){return yield this.initIfNeeded(),this.flows})}getCollection(t){return g(this,null,function*(){yield this.initIfNeeded();let e=this.getGlobalState().collections.getRule(t);if(e==null)return;let i=yield Promise.all(e.flows.map(a=>g(this,null,function*(){return b(h({},a),{flow:yield this.getFlow(a.flowId)})})));return e.flows=i,e})}getCollections(){return g(this,null,function*(){yield this.initIfNeeded();let t=this.getGlobalState().collections.getRules();if(t!=null)return t})}reload(t){return g(this,null,function*(){tt(),Z(),t&&(yield this.updateConfig(t),this.mockFlowStates(m(this.config))),this.initPromise=null,yield this.init(this.config),this.flows.forEach(e=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(i=>{let a=this.getGlobalState().previousFlows.get(e.id);i(e,a),this.getGlobalState().previousFlows.set(e.id,C(e))})})})}resync(){return g(this,null,function*(){yield this.refreshStateFromAPI()})}onStateChange(t){return g(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return g(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return g(this,null,function*(){return this.initPromise?this.initPromise:this.init(this.config)})}refreshStateFromAPI(){return g(this,null,function*(){let t=m(this.config);if(!f[t]){let e=this,i={set:function(a,d,n){if(a[d]){let l=a[d],c=n;JSON.stringify(l)!==JSON.stringify(c)&&e.triggerEventHandlers(c,l)}return a[d]=n,!0}};if(f[t]={refreshStateFromAPI:()=>g(this,null,function*(){}),collections:new E(new Map),flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config,currentUrl:w()?window.location.href:""},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(t);return}f[t].refreshStateFromAPI=a=>g(this,null,function*(){var l,c;if(this.config.__readOnly)return;let d=a||(yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,context:I(this.getGlobalState().currentUrl)})})),n=new Map;(c=(l=d.collections)==null?void 0:l.computedOrder)==null||c.forEach(({allowedComponents:p,collectionId:o,collectionType:P,flowId:et,visible:it})=>{var k;let $=(k=n.get(o))!=null?k:{allowedComponents:p,collectionType:P,flows:[]};$.flows.push({flowId:et,visible:it}),n.set(o,$)}),f[t].collections.ingestRulesData(n),d&&d.eligibleFlows?(d.eligibleFlows.forEach(p=>{f[t].flowStates[p.flowSlug]=p,this.flows.find(o=>o.id==p.flowSlug)?this.flows.forEach(o=>{o.id==p.flowSlug&&o.resyncState(p)}):this.flows.push(new y({config:this.config,id:p.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield f[t].refreshStateFromAPI()})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{f[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 y({config:this.config,id:e}))})}updateConfig(t){return g(this,null,function*(){this.config=h(h({},this.config),t),f[m(this.config)]&&(this.getGlobalState().config=this.config)})}triggerEventHandlers(t,e){return g(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(a=>{let d=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),a(i,d),this.getGlobalState().previousFlows.set(i.id,C(i))})})})}batchRegister(t){return g(this,null,function*(){let e=t.map(d=>g(this,[d],function*([i,a]){let n=yield this.getFlow(i);return[i,c=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==c&&this.getGlobalState().onFlowStateChangeHandlers.forEach(o=>{o(n,p),this.getGlobalState().previousFlows.set(i,C(n))}),a==null||a(c)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};var x=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(x||{}),_=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(_||{});var D=(o=>(o.ANNOUNCEMENT="ANNOUNCEMENT",o.CHECKLIST="CHECKLIST",o.FORM="FORM",o.TOUR="TOUR",o.SUPPORT="SUPPORT",o.CUSTOM="CUSTOM",o.BANNER="BANNER",o.EMBEDDED_TIP="EMBEDDED_TIP",o.NPS_SURVEY="NPS_SURVEY",o.SURVEY="SURVEY",o.CARD="CARD",o))(D||{});0&&(module.exports={Flow,FlowStatus,FlowType,Frigade,TriggerType});
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/shared/fetchable.ts","../src/core/flow.ts","../src/core/rules.ts","../src/core/frigade.ts","../src/core/types.ts"],"sourcesContent":["export { Frigade } from './core/frigade'\nexport { Flow } from './core/flow'\nexport {\n FlowStatus,\n type FlowStep,\n type FrigadeConfig,\n FlowType,\n type StatefulFlow,\n TriggerType,\n PropertyPayload,\n} from './core/types'\nexport type {\n EnrichedRule,\n Rule,\n RulesList,\n RulesRegistryCallback,\n RulesRegistryBatch,\n} from './core/rules'\n","export const VERSION_NUMBER = '0.2.20'\n","import { VERSION_NUMBER } from '../core/version'\nimport { v4 as uuidv4 } from 'uuid'\nimport { Flow } from '../core/flow'\nimport { frigadeGlobalState } from './state'\nimport { FlowStateContext } from '../core/types'\n\nexport const NOT_STARTED_STEP = 'NOT_STARTED_STEP'\nexport const COMPLETED_FLOW = 'COMPLETED_FLOW'\nexport const SKIPPED_FLOW = 'SKIPPED_FLOW'\nexport const STARTED_FLOW = 'STARTED_FLOW'\nexport const NOT_STARTED_FLOW = 'NOT_STARTED_FLOW'\nexport const COMPLETED_STEP = 'COMPLETED_STEP'\nexport const STARTED_STEP = 'STARTED_STEP'\nconst GUEST_KEY = 'frigade-guest-key'\nexport const GUEST_PREFIX = 'guest_'\nconst GET_CACHE_PREFIX = 'get-cache-'\nconst LOCAL_STORAGE_PREFIX = 'fr-js-'\n\nexport function cloneFlow(flow: Flow): Flow {\n const newFlow = new Flow({\n config: flow.config,\n id: flow.id,\n })\n return newFlow\n}\n\nexport function clone<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj))\n}\n\nexport function getHeaders(apiKey: string) {\n return {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Frigade-SDK-Version': VERSION_NUMBER,\n 'X-Frigade-SDK-Platform': 'Javascript',\n },\n }\n}\n\nfunction getLocalStorage(key: string) {\n if (isWeb()) {\n return window.localStorage.getItem(`${LOCAL_STORAGE_PREFIX}${key}`)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (isWeb()) {\n window.localStorage.setItem(`${LOCAL_STORAGE_PREFIX}${key}`, value)\n }\n}\n\nfunction setGlobalState(key: string, value: any) {\n frigadeGlobalState[key] = value\n}\n\nfunction getGlobalState(key: string): any {\n return frigadeGlobalState[key]\n}\n\nexport function clearCache() {\n Object.keys(frigadeGlobalState).forEach((key) => {\n if (key.startsWith(GET_CACHE_PREFIX)) {\n delete frigadeGlobalState[key]\n }\n })\n}\n\nexport function resetAllLocalStorage() {\n if (isWeb()) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith(LOCAL_STORAGE_PREFIX)) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nclass CallQueue {\n private queue: {\n call: string\n time: number\n }[] = []\n private readonly ttlInMS = 100\n private readonly cacheSize = 5\n\n public push(call: string) {\n const now = new Date()\n if (this.queue.length >= this.cacheSize) {\n this.queue.shift()\n }\n this.queue.push({\n call: call,\n time: now.getTime(),\n })\n }\n\n public hasIdenticalCall(call: string) {\n const now = new Date()\n this.queue = this.queue.filter((item) => now.getTime() - item.time < this.ttlInMS)\n return this.queue.some((item) => item.call === call)\n }\n}\n\nconst callQueue = new CallQueue()\n\nexport async function gracefulFetch(url: string, options: any) {\n if (typeof globalThis.fetch !== 'function') {\n return getEmptyResponse(\n \"- Attempted to call fetch() in an environment that doesn't support it.\"\n )\n }\n\n if (isWeb() && options && options.body && options.method === 'POST') {\n const lastCallDataKey = `${url}${JSON.stringify(options.body ?? {})}`\n if (callQueue.hasIdenticalCall(lastCallDataKey)) {\n return getEmptyResponse()\n }\n callQueue.push(lastCallDataKey)\n }\n\n let response\n try {\n response = fetch(url, options)\n response = await response\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse('Received an empty response')\n }\n\n if (response.status >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n try {\n if (response.status === 204) {\n return getEmptyResponse()\n }\n\n let body\n try {\n body = await response.json()\n } catch (e) {\n return getEmptyResponse()\n }\n\n if (body.error) {\n return getEmptyResponse(body.error)\n }\n return body\n } catch (e) {\n return getEmptyResponse(e)\n }\n}\n\nexport function getEmptyResponse(error?: any) {\n if (error) {\n console.log('Call to Frigade failed', error)\n }\n\n // Create empty response that contains the .json method and returns an empty object\n return {\n json: () => ({}),\n }\n}\n\nexport function generateGuestId() {\n if (isWeb()) {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n setLocalStorage(GUEST_KEY, guestId)\n }\n return guestId\n } else {\n return `${GUEST_PREFIX}${uuidv4()}`\n }\n}\n\nexport function fetcher(apiKey: string, path: string, options?: Record<any, any>) {\n return gracefulFetch(`//api.frigade.com/v1/public${path}`, {\n ...(options ?? {}),\n ...getHeaders(apiKey),\n })\n}\n\nexport function isWeb() {\n return (\n typeof window !== 'undefined' &&\n typeof window.document !== 'undefined' &&\n typeof window.localStorage !== 'undefined'\n )\n}\n\nexport function getContext(currentUrl: string): FlowStateContext {\n if (!isWeb()) {\n return {}\n }\n\n return {\n url: currentUrl,\n userAgent: navigator.userAgent,\n }\n}\n","import { FlowStates, FlowStep, FrigadeConfig, StatefulFlow } from '../core/types'\nimport { Flow } from '../core/flow'\nimport type { Rules } from '../core/rules'\n\nexport interface FrigadeGlobalState {\n refreshStateFromAPI: (overrideFlowStatesRaw?: FlowStates) => Promise<void>\n flowStates: Record<string, StatefulFlow>\n collections: Rules\n onFlowStateChangeHandlerWrappers: Map<\n (flow: Flow, previousFlow: Flow) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onStepStateChangeHandlerWrappers: Map<\n (step: FlowStep, previousStep: FlowStep) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onFlowStateChangeHandlers: ((flow: Flow, previousFlow: Flow) => void)[]\n previousFlows: Map<string, Flow>\n variables: Record<string, Record<string, any>>\n lastSyncDate?: Date\n config: FrigadeConfig\n currentUrl: string\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}`\n}\n","import { generateGuestId, getEmptyResponse, getHeaders, gracefulFetch } from './utils'\nimport { FrigadeConfig } from '../core/types'\nimport { frigadeGlobalState, FrigadeGlobalState, getGlobalStateKey } from './state'\n\nexport class Fetchable {\n public config: FrigadeConfig = {\n apiKey: '',\n apiUrl: 'https://api.frigade.com',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(12).substring(4),\n generateGuestId: true,\n }\n\n constructor(config: FrigadeConfig) {\n const filteredConfig = Object.fromEntries(Object.entries(config).filter(([_, v]) => v != null))\n if (!config.userId && config.generateGuestId === false) {\n delete this.config.userId\n }\n this.config = {\n ...this.config,\n ...filteredConfig,\n }\n }\n\n /**\n * @ignore\n */\n public async fetch(path: string, options?: Record<any, any>) {\n if (this.config.__readOnly) {\n return getEmptyResponse()\n }\n\n return gracefulFetch(this.getAPIUrl(path), {\n keepalive: true,\n ...(options ?? {}),\n ...getHeaders(this.config.apiKey),\n })\n }\n\n private getAPIUrl(path: string) {\n return `${this.config.apiUrl.replace(/\\/$/, '')}/${path.replace(/^\\//, '')}`\n }\n\n /**\n * @ignore\n */\n protected getGlobalState(): FrigadeGlobalState {\n const globalStateKey = getGlobalStateKey(this.config)\n if (!frigadeGlobalState[globalStateKey]) {\n throw new Error('Frigade has not yet been initialized')\n }\n return frigadeGlobalState[globalStateKey]\n }\n}\n","import {\n FlowActionType,\n FlowStateDTO,\n FlowStates,\n FlowStep,\n FrigadeConfig,\n PropertyPayload,\n StatefulFlow,\n StatefulStep,\n} from './types'\nimport {\n clone,\n cloneFlow,\n COMPLETED_FLOW,\n COMPLETED_STEP,\n getContext,\n NOT_STARTED_FLOW,\n NOT_STARTED_STEP,\n SKIPPED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { Fetchable } from '../shared/fetchable'\nimport { RulesRegistryCallback } from './rules'\n\nexport class Flow extends Fetchable {\n /**\n * The Flow's ID.\n */\n public id: string\n /**\n * The Flow's component ID.\n */\n public componentId: string\n /**\n * Ordered map of the Steps in the Flow.\n * See [Flow Step Definition](https://docs.frigade.com/v2/sdk/js/step) for more information.\n */\n public steps: Map<string, FlowStep>\n /**\n * The user-facing title of the Flow, if defined at the top level of the YAML config.\n */\n public title?: string\n /**\n * The user-facing description of the Flow, if defined at the top level of the YAML config.\n */\n public subtitle?: string\n /**\n * The metadata of the Flow.\n * @ignore\n */\n public rawData: StatefulFlow\n /**\n * Whether the Flow is completed or not.\n */\n public isCompleted: boolean\n /**\n * Whether the Flow is started or not.\n */\n public isStarted: boolean\n /**\n * Whether the Flow has been skipped or not.\n */\n public isSkipped: boolean\n /**\n * @ignore\n */\n private _isVisible: boolean = false\n /**\n * Whether the Flow is visible to the user based on the current user/group's state.\n */\n get isVisible() {\n if (this._isVisible === false) {\n return false\n }\n\n return this.getGlobalState().collections.isFlowVisible(this.id)\n }\n set isVisible(visible: boolean) {\n this._isVisible = visible\n }\n\n /**\n * @ignore\n */\n private lastStepUpdate: Map<(step: FlowStep, previousStep: FlowStep) => void, FlowStep> =\n new Map()\n\n constructor({ config, id }: { config: FrigadeConfig; id: string }) {\n super(config)\n this.id = id\n this.init()\n }\n\n /**\n * Reload the Flow data from the server\n */\n reload() {\n this.init()\n }\n\n /**\n * @ignore\n */\n resyncState(overrideStatefulFlow?: StatefulFlow) {\n const statefulFlow = overrideStatefulFlow ?? this.getStatefulFlow()\n\n this.rawData = statefulFlow\n this.title = statefulFlow?.data?.title\n this.subtitle = statefulFlow?.data?.subtitle\n\n this.isCompleted = statefulFlow.$state.completed\n this.isStarted = statefulFlow.$state.started\n this.isSkipped = statefulFlow.$state.skipped\n this._isVisible = statefulFlow.$state.visible\n\n statefulFlow.data.steps.forEach((step, index) => {\n const stepObj = this.initStepFromStatefulStep(step, index)\n\n const existingStep = this.steps?.get(step.id)\n if (existingStep) {\n Object.keys(stepObj).forEach((key) => {\n existingStep[key] = stepObj[key]\n })\n }\n })\n\n if (this.steps && this.steps.size > 0) {\n this.applyVariables(this.getGlobalState().variables[this.id] ?? {})\n }\n }\n\n /**\n * @ignore\n */\n private initStepFromStatefulStep(step: StatefulStep, index: number) {\n return {\n ...step,\n flow: this,\n $state: {\n ...step.$state,\n lastActionAt: step.$state.lastActionAt ? new Date(step.$state.lastActionAt) : undefined,\n },\n order: index,\n } as Partial<FlowStep>\n }\n\n /**\n * @ignore\n */\n private init() {\n const statefulFlow = this.getStatefulFlow()\n\n this.resyncState()\n\n const newSteps = new Map<string, FlowStep>()\n\n statefulFlow.data.steps.forEach((step, index) => {\n const stepObj = this.initStepFromStatefulStep(step, index)\n\n stepObj.start = async (properties?: PropertyPayload) => {\n const thisStep = this.steps.get(step.id)\n\n if (this.getCurrentStep().id === thisStep.id && thisStep.$state.started) {\n return\n }\n\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.data.steps[thisStep.order].$state.started = true\n copy.data.steps[thisStep.order].$state.lastActionAt = new Date()\n copy.$state.lastActionAt = new Date()\n copy.$state.currentStepId = thisStep.id\n copy.$state.currentStepIndex = thisStep.order\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n await this.sendFlowStateToAPI(STARTED_STEP, properties, thisStep.id)\n }\n\n stepObj.complete = async (properties?: PropertyPayload, optimistic: boolean = true) => {\n const thisStep = this.steps.get(step.id)\n\n if (thisStep.$state.completed && optimistic) {\n return\n }\n\n if (optimistic) {\n const isLastStep = thisStep.order + 1 === this.getNumberOfAvailableSteps()\n const copy = clone(this.getGlobalState().flowStates[this.id])\n\n copy.$state.started = true\n copy.data.steps[thisStep.order].$state.completed = true\n copy.data.steps[thisStep.order].$state.started = true\n copy.data.steps[thisStep.order].$state.lastActionAt = new Date()\n\n // If there are more index, advance current step\n if (!isLastStep) {\n copy.$state.currentStepId = this.getStepByIndex(thisStep.order + 1).id\n copy.$state.currentStepIndex = thisStep.order + 1\n }\n\n if (isLastStep) {\n copy.$state.completed = true\n }\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n }\n\n await this.sendFlowStateToAPI(COMPLETED_STEP, properties, thisStep.id)\n }\n\n stepObj.reset = async () => {\n const thisStep = this.steps.get(step.id)\n\n if (!thisStep.$state.completed) {\n return\n }\n\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.data.steps[thisStep.order].$state.started = false\n copy.data.steps[thisStep.order].$state.completed = false\n copy.data.steps[thisStep.order].$state.lastActionAt = undefined\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n await this.sendFlowStateToAPI(NOT_STARTED_STEP, undefined, thisStep.id)\n }\n\n stepObj.onStateChange = (handler: (step: FlowStep, previousStep: FlowStep) => void) => {\n const wrapperHandler = (flow: Flow) => {\n if (flow.id !== this.id) {\n return\n }\n const thisStep = flow.steps.get(step.id)\n const previousStep = this.lastStepUpdate.get(handler)\n\n if (\n thisStep.$state.completed !== previousStep?.$state.completed ||\n thisStep.$state.started !== previousStep?.$state.started ||\n thisStep.$state.visible !== previousStep?.$state.visible ||\n thisStep.$state.blocked !== previousStep?.$state.blocked\n ) {\n handler(thisStep, previousStep ?? clone(thisStep))\n this.lastStepUpdate.set(handler, clone(thisStep))\n }\n }\n this.getGlobalState().onStepStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n stepObj.removeStateChangeHandler = (\n handler: (step: FlowStep, previousStep: FlowStep) => void\n ) => {\n const wrapperHandler = this.getGlobalState().onStepStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n newSteps.set(step.id, stepObj as FlowStep)\n })\n this.steps = newSteps\n // Check if empty object\n if (\n this.getGlobalState().variables &&\n this.getGlobalState().variables[this.id] &&\n Object.keys(this.getGlobalState().variables[this.id]).length > 0\n ) {\n this.applyVariables(this.getGlobalState().variables[this.id])\n }\n }\n\n /**\n * Marks the flow started\n */\n public async start(properties?: PropertyPayload) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowStarted()\n\n await this.sendFlowStateToAPI(STARTED_FLOW, properties)\n }\n\n /**\n * Marks the flow completed\n */\n public async complete(properties?: PropertyPayload) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n await this.sendFlowStateToAPI(COMPLETED_FLOW, properties)\n }\n\n /**\n * Marks the flow skipped\n */\n public async skip(properties?: PropertyPayload) {\n if (this.isSkipped) {\n return\n }\n this.optimisticallyMarkFlowSkipped()\n await this.sendFlowStateToAPI(SKIPPED_FLOW, properties)\n }\n\n /**\n * Navigates the flow to the next step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async forward(properties?: PropertyPayload) {\n const nextStep = this.getStepByIndex(this.getCurrentStepIndex() + 1)\n if (nextStep) {\n await nextStep.start(properties)\n } else {\n await this.complete(properties)\n }\n }\n\n /**\n * Navigates the flow to the previous step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async back(properties?: PropertyPayload) {\n const previousStep = this.getStepByIndex(this.getCurrentStepIndex() - 1)\n if (previousStep) {\n await previousStep.start(properties)\n }\n }\n\n /**\n * Restarts the flow/marks it not started\n */\n public async restart() {\n this.optimisticallyMarkFlowNotStarted()\n await this.sendFlowStateToAPI(NOT_STARTED_FLOW)\n }\n\n /**\n * Get a step by index\n * @param index\n */\n public getStepByIndex(index: number): FlowStep | undefined {\n return this.steps.get(Array.from(this.steps.keys())[index])\n }\n\n /**\n * Gets current step\n */\n public getCurrentStep(): FlowStep {\n return (\n this.steps.get(this.getStatefulFlow().$state.currentStepId) ??\n this.steps.get(Array.from(this.steps.keys())[0])\n )\n }\n\n /**\n * Get the index of the current step. Starts at 0\n */\n public getCurrentStepIndex(): number {\n const currentStep = this.getCurrentStep()\n return Array.from(this.steps.keys()).indexOf(currentStep.id)\n }\n\n /**\n * Get the number of completed steps for the current user in the current flow\n */\n public getNumberOfCompletedSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.$state.completed).length\n }\n\n /**\n * Get the number of available steps for the current user in the current flow. This is the number of steps that are not hidden.\n */\n public getNumberOfAvailableSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.$state.visible).length\n }\n\n /**\n * @ignore\n */\n public onStateChange(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = (flow: Flow, previousFlow: Flow) => {\n if (flow.id === this.id) {\n if (\n flow.isCompleted !== previousFlow?.isCompleted ||\n flow.isStarted !== previousFlow?.isStarted ||\n flow.isSkipped !== previousFlow?.isSkipped ||\n flow.isVisible !== previousFlow?.isVisible ||\n JSON.stringify(flow.steps) !== JSON.stringify(previousFlow?.steps)\n ) {\n handler(flow, previousFlow)\n }\n }\n }\n this.getGlobalState().onFlowStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n /**\n * @ignore\n */\n public removeStateChangeHandler(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = this.getGlobalState().onFlowStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n /**\n * Apply variables to the flow. This will replace any `${variable}` in the title, subtitle, and step fields with the value of the variable.\n * @param variables A record of variables to apply to the flow.\n */\n public applyVariables(variables: Record<string, any>) {\n // Replace ${variable} with the value of the variable\n const replaceVariables = (str: string) => {\n const matches = str.match(/\\${(.*?)}/g)\n if (matches) {\n matches.forEach((match) => {\n const variable = match.replace('${', '').replace('}', '')\n if (!variables[variable]) {\n return\n }\n str = str.replace(match, variables[variable])\n })\n }\n return str\n }\n\n this.title = replaceVariables(this.title ?? '')\n this.subtitle = replaceVariables(this.subtitle ?? '')\n this.steps.forEach((step) => {\n // Iterate over every string field in the step and replace variables\n Object.keys(step).forEach((key) => {\n if (typeof step[key] === 'string') {\n // @ts-ignore\n step[key] = replaceVariables(step[key])\n }\n })\n })\n\n this.getGlobalState().variables[this.id] = variables\n }\n\n /**\n * @ignore\n */\n private getStatefulFlow(): StatefulFlow {\n const userFlowStates = this.getGlobalState().flowStates\n return userFlowStates[this.id]\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowCompleted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = true\n copy.$state.started = true\n copy.$state.visible = false\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.started = true\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowNotStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = false\n copy.$state.started = false\n copy.$state.visible = true\n copy.$state.currentStepIndex = 0\n copy.$state.currentStepId = this.getStepByIndex(0)?.id\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n private async sendFlowStateToAPI(\n action: FlowActionType,\n data?: PropertyPayload,\n stepId?: string\n ) {\n const date = new Date()\n this.getGlobalState().lastSyncDate = date\n const flowStatesRaw: FlowStates = await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n flowSlug: this.id,\n stepId: stepId ?? this.getCurrentStep().id,\n data: data ? data : {},\n actionType: action,\n createdAt: date,\n context: getContext(this.getGlobalState().currentUrl),\n } as FlowStateDTO),\n })\n if (date < this.getGlobalState().lastSyncDate) {\n return\n }\n await this.getGlobalState().refreshStateFromAPI(flowStatesRaw)\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowSkipped() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.skipped = true\n copy.$state.visible = false\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n public register(callback?: RulesRegistryCallback) {\n const globalState = this.getGlobalState()\n\n globalState.collections.register(this.id, (visible) => {\n const prevFlow = this.getGlobalState().previousFlows.get(this.id)\n\n if (prevFlow?._isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(this, prevFlow)\n this.getGlobalState().previousFlows.set(this.id, cloneFlow(this))\n })\n }\n\n callback?.(visible)\n })\n }\n\n public unregister() {\n if (!this.getGlobalState().collections) {\n return\n }\n this.getGlobalState().collections.unregister(this.id)\n }\n}\n","import type { Flow } from './flow'\n\nexport type RulesRegistryCallback = (visible: boolean) => void\n\nexport type RulesRegistryBatch = [string, RulesRegistryCallback][]\n\nexport interface RulesRegistryItem {\n visible: boolean\n visited: boolean\n callback: RulesRegistryCallback\n}\n\nexport interface Rule {\n allowedComponents: string[]\n collectionType: 'DEFAULT' | 'CUSTOM'\n flows: {\n flowId: string\n visible: boolean\n }[]\n}\n\nexport interface EnrichedRule extends Omit<Rule, 'flows'> {\n flows: Array<\n Rule['flows'][number] & {\n flow: Flow\n }\n >\n}\n\nexport type RulesList = Map<string, Rule>\n\nexport class Rules {\n private readonly registry: Map<string, RulesRegistryItem> = new Map()\n private registryStateLocked: boolean = false\n private rules: RulesList = new Map()\n private flowsInRules: Set<string> = new Set()\n\n constructor(rulesData: RulesList) {\n this.ingestRulesData(rulesData)\n }\n\n getRule(ruleId: string) {\n return this.rules.get(ruleId)\n }\n\n getRules() {\n return this.rules\n }\n\n ingestRulesData(rulesData: RulesList) {\n this.rules = rulesData\n\n for (const [, rule] of this.rules) {\n for (const { flowId } of rule.flows) {\n this.flowsInRules.add(flowId)\n }\n }\n\n if (this.registry.size > 0) {\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n }\n\n this.fireCallbacks()\n }\n\n fireCallbacks() {\n for (const [flowId, { callback }] of this.registry) {\n if (typeof callback === 'function') {\n callback(this.isFlowVisible(flowId))\n }\n }\n }\n\n isFlowVisible(flowId: string) {\n const registeredFlow = this.registry.get(flowId)\n const flowInRules = this.flowsInRules.has(flowId)\n\n if (registeredFlow == null || !flowInRules) {\n return true\n }\n\n return registeredFlow.visible\n }\n\n lockRegistryState() {\n this.registryStateLocked = true\n }\n\n unlockRegistryState() {\n this.registryStateLocked = false\n }\n\n resetRegistryState() {\n for (const [flowId, item] of this.registry) {\n item.visible = false\n item.visited = false\n\n this.registry.set(flowId, item)\n }\n }\n\n processRules() {\n for (const [, rule] of this.rules) {\n for (const { flowId, visible: visibleAPIOverride } of rule.flows) {\n const registeredFlow = this.registry.get(flowId)\n\n // If this flow in the rule isn't registered, we have no opinion on it yet\n if (registeredFlow == null) {\n continue\n }\n\n // The API can force a flow to be hidden due to cool-offs, etc.\n if (visibleAPIOverride === false && registeredFlow.visible !== true) {\n this.visit(flowId, false)\n continue\n }\n\n // If this flow was processed in a previous rule and the registry is locked,\n // visibility shouldn't change until next time we run processRules\n if (registeredFlow.visited && this.registryStateLocked) {\n continue\n }\n\n const flowIdsInThisRule = rule.flows\n .map(({ flowId: otherFlowId }) => otherFlowId)\n .filter((otherFlowId) => otherFlowId !== flowId)\n\n // If another flow in this rule has been visited already and is visible...\n const anotherFlowInThisRuleIsVisible = flowIdsInThisRule.some((otherId) => {\n const { visible: otherVisible, visited: otherVisited } = this.registry.get(otherId) ?? {}\n\n return otherVisible && otherVisited\n })\n\n // ...then this flow is hidden\n if (anotherFlowInThisRuleIsVisible) {\n this.visit(flowId, false)\n\n continue\n }\n\n // No other flows are visible, so this flow is visible by default\n this.visit(flowId)\n }\n }\n }\n\n register(flowId: string | RulesRegistryBatch, callback?: RulesRegistryCallback) {\n if (Array.isArray(flowId)) {\n this.batchRegister(flowId)\n return\n }\n\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.fireCallbacks()\n }\n\n batchRegister(flowIds: RulesRegistryBatch) {\n flowIds.forEach(([flowId, callback]) => {\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.lockRegistryState()\n\n this.fireCallbacks()\n }\n\n unregister(flowId: string) {\n this.registry.delete(flowId)\n\n this.resetRegistryState()\n this.processRules()\n\n this.fireCallbacks()\n }\n\n private visit(flowId: string, visible: boolean = true) {\n const item = this.registry.get(flowId) ?? {\n callback: () => {},\n visible,\n visited: true,\n }\n\n item.visible = visible\n item.visited = true\n\n this.registry.set(flowId, item)\n }\n}\n","import {\n FlowStateDTO,\n FlowStates,\n FrigadeConfig,\n PropertyPayload,\n SessionDTO,\n StatefulFlow,\n} from './types'\nimport {\n clearCache,\n cloneFlow,\n getContext,\n GUEST_PREFIX,\n isWeb,\n resetAllLocalStorage,\n} from '../shared/utils'\nimport { Flow } from './flow'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/fetchable'\nimport {\n type EnrichedRule,\n type Rule,\n Rules,\n type RulesList,\n type RulesRegistryBatch,\n} from './rules'\n\nexport class Frigade extends Fetchable {\n /**\n * @ignore\n */\n private flows: Flow[] = []\n /**\n * @ignore\n */\n private initPromise: Promise<void>\n /**\n * @ignore\n */\n private hasFailed = false\n\n /**\n * @ignore\n */\n private visibilityChangeHandler = async () => {\n if (document.visibilityState === 'visible') {\n await this.refreshStateFromAPI()\n }\n }\n\n constructor(apiKey: string, config?: FrigadeConfig) {\n super({\n apiKey,\n ...config,\n })\n this.init(this.config)\n if (isWeb() && this.config.syncOnWindowUpdates !== false) {\n document.addEventListener('visibilitychange', this.visibilityChangeHandler)\n // @ts-ignore\n if (window.navigation) {\n // @ts-ignore\n window.navigation.addEventListener('navigate', async (event) => {\n if (this.getGlobalState().currentUrl === event.destination.url) {\n return\n }\n this.getGlobalState().currentUrl = event.destination.url\n this.refreshStateFromAPI()\n })\n }\n }\n }\n\n /**\n * Gets the current configuration.\n */\n getConfig() {\n return this.config\n }\n\n /**\n * @ignore\n */\n destroy() {\n if (isWeb()) {\n document.removeEventListener('visibilitychange', this.visibilityChangeHandler)\n // Remove all other event listeners\n const globalStateKey = getGlobalStateKey(this.config)\n if (frigadeGlobalState[globalStateKey]) {\n frigadeGlobalState[globalStateKey].onFlowStateChangeHandlers = []\n }\n }\n }\n\n /**\n * @ignore\n */\n private async init(config: FrigadeConfig): Promise<void> {\n this.updateConfig({\n ...this.config,\n ...config,\n })\n\n if (!this.config.userId && this.config.generateGuestId === false) {\n return\n }\n\n this.initPromise = (async () => {\n if (!this.config.__readOnly) {\n if (this.config.userId?.startsWith(GUEST_PREFIX)) {\n // do nothing\n } else if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n userProperties: this.config.userProperties,\n groupProperties: this.config.groupProperties,\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userProperties: this.config.userProperties,\n })\n }\n }\n await this.refreshStateFromAPI()\n })()\n\n return this.initPromise\n }\n\n /**\n * Set the current user.\n * @param userId\n * @param properties\n */\n public async identify(userId: string, properties?: PropertyPayload): Promise<void> {\n await this.updateConfig({ ...this.config, userId })\n await this.initIfNeeded()\n await this.session({\n userId: this.config.userId,\n userProperties: properties,\n })\n await this.resync()\n }\n\n /**\n * Set the group for the current user.\n * @param groupId\n * @param properties\n */\n public async group(groupId?: string, properties?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n this.updateConfig({ ...this.config, groupId })\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupProperties: properties,\n })\n await this.resync()\n }\n\n /**\n * Track an event for the current user (and group if set).\n * @param event\n * @param properties\n */\n public async track(event: string, properties?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n if (!event) {\n console.error('Event name is required to track an event')\n return\n }\n if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupEvents: [\n {\n event,\n properties,\n },\n ],\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n }\n await this.resync()\n }\n\n /**\n * @ignore\n */\n private async session(sessionDTO: SessionDTO) {\n await this.fetch('/v1/public/sessions', {\n method: 'POST',\n body: JSON.stringify(sessionDTO),\n })\n }\n\n /**\n * @ignore\n */\n public isReady(): boolean {\n return Boolean(this.config.__instanceId && this.config.apiKey && this.initPromise)\n }\n\n /**\n * Get a Flow by its ID.\n * @param flowId\n */\n public async getFlow(flowId: string) {\n await this.initIfNeeded()\n\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n await this.initIfNeeded()\n return this.flows\n }\n\n public async getCollection(collectionId: string) {\n await this.initIfNeeded()\n const collection = this.getGlobalState().collections.getRule(collectionId)\n\n if (collection == null) {\n return undefined\n }\n\n const enrichedFlows = await Promise.all(\n collection.flows.map(async (item) => ({\n ...item,\n flow: await this.getFlow(item.flowId),\n }))\n )\n\n collection.flows = enrichedFlows\n\n return collection as EnrichedRule\n }\n\n public async getCollections() {\n await this.initIfNeeded()\n const collections = this.getGlobalState().collections.getRules()\n\n if (collections == null) {\n return undefined\n }\n\n return collections\n }\n\n /**\n * Reload the current state of the flows by calling the Frigade API.\n * This will trigger all event handlers.\n * @param config optional config to use when reloading. If not passed, the current config will be used.\n */\n public async reload(config?: FrigadeConfig) {\n resetAllLocalStorage()\n clearCache()\n if (config) {\n await this.updateConfig(config)\n this.mockFlowStates(getGlobalStateKey(this.config))\n }\n this.initPromise = null\n await this.init(this.config)\n // Trigger all event handlers\n this.flows.forEach((flow) => {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n })\n }\n\n private async resync() {\n await this.refreshStateFromAPI()\n }\n\n /**\n * Event handler that captures all changes that happen to the state of the Flows.\n * @param handler\n */\n public async onStateChange(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers.push(handler)\n }\n\n /**\n * Returns true if the JS SDK failed to connect to the Frigade API.\n */\n hasFailedToLoad() {\n return this.hasFailed\n }\n\n /**\n * Removes the given handler from the list of event handlers.\n * @param handler\n */\n public async removeStateChangeHandler(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== handler)\n }\n\n /**\n * @ignore\n */\n private async initIfNeeded() {\n if (this.initPromise) {\n return this.initPromise\n } else {\n return this.init(this.config)\n }\n }\n\n /**\n * @ignore\n */\n private async refreshStateFromAPI(): Promise<void> {\n const globalStateKey = getGlobalStateKey(this.config)\n\n if (!frigadeGlobalState[globalStateKey]) {\n const that = this\n\n let validator = {\n set: function (target: any, key: any, value: any) {\n if (target[key]) {\n const previousState = target[key] as StatefulFlow\n const newState = value as StatefulFlow\n if (JSON.stringify(previousState) !== JSON.stringify(newState)) {\n that.triggerEventHandlers(newState, previousState)\n }\n }\n\n target[key] = value\n return true\n },\n }\n\n frigadeGlobalState[globalStateKey] = {\n refreshStateFromAPI: async () => {},\n collections: new Rules(new Map()),\n flowStates: new Proxy({}, validator),\n onFlowStateChangeHandlerWrappers: new Map(),\n onStepStateChangeHandlerWrappers: new Map(),\n onFlowStateChangeHandlers: [],\n previousFlows: new Map(),\n variables: {},\n config: this.config,\n currentUrl: isWeb() ? window.location.href : '',\n }\n\n if (this.config.__readOnly && this.config.__flowStateOverrides) {\n this.mockFlowStates(globalStateKey)\n\n return\n }\n\n frigadeGlobalState[globalStateKey].refreshStateFromAPI = async (\n overrideFlowStateRaw?: FlowStates\n ) => {\n if (this.config.__readOnly) {\n return\n }\n\n const flowStateRaw: FlowStates = overrideFlowStateRaw\n ? overrideFlowStateRaw\n : await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n context: getContext(this.getGlobalState().currentUrl),\n } as FlowStateDTO),\n })\n\n const rulesData: RulesList = new Map()\n\n flowStateRaw.collections?.computedOrder?.forEach(\n ({ allowedComponents, collectionId, collectionType, flowId, visible }) => {\n const currentRule: Rule = rulesData.get(collectionId) ?? {\n allowedComponents,\n collectionType,\n flows: [],\n }\n\n currentRule.flows.push({\n flowId,\n visible,\n })\n\n rulesData.set(collectionId, currentRule)\n }\n )\n\n frigadeGlobalState[globalStateKey].collections.ingestRulesData(rulesData)\n\n if (flowStateRaw && flowStateRaw.eligibleFlows) {\n flowStateRaw.eligibleFlows.forEach((statefulFlow) => {\n frigadeGlobalState[globalStateKey].flowStates[statefulFlow.flowSlug] = statefulFlow\n if (!this.flows.find((flow) => flow.id == statefulFlow.flowSlug)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: statefulFlow.flowSlug,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == statefulFlow.flowSlug) {\n flow.resyncState(statefulFlow)\n }\n })\n }\n })\n this.hasFailed = false\n } else {\n this.hasFailed = true\n }\n }\n }\n\n await frigadeGlobalState[globalStateKey].refreshStateFromAPI()\n }\n\n /**\n * @ignore\n */\n private mockFlowStates(globalStateKey: string) {\n Object.keys(this.config.__flowStateOverrides).forEach((flowId) => {\n frigadeGlobalState[globalStateKey].flowStates[flowId] =\n this.config.__flowStateOverrides[flowId]\n\n if (!this.flows.find((flow) => flow.id == flowId)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: flowId,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == flowId) {\n flow.resyncState(this.config.__flowStateOverrides[flowId])\n }\n })\n }\n })\n }\n\n /**\n * @ignore\n */\n private async updateConfig(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n if (frigadeGlobalState[getGlobalStateKey(this.config)]) {\n this.getGlobalState().config = this.config\n }\n }\n\n /**\n * @ignore\n */\n private async triggerEventHandlers(newState: StatefulFlow, previousState?: StatefulFlow) {\n if (newState) {\n this.flows.forEach((flow) => {\n if (flow.id == previousState.flowSlug) {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n flow.resyncState(newState)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n }\n })\n }\n }\n\n /**\n * @ignore\n */\n async batchRegister(flowIds: RulesRegistryBatch) {\n const flowIdsWithWrappedCallbacks = flowIds.map(async ([flowId, callback]) => {\n const currentFlow = await this.getFlow(flowId)\n const wrappedCallback = (visible: boolean) => {\n const prevFlow = this.getGlobalState().previousFlows.get(flowId)\n\n if (prevFlow?.isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(currentFlow, prevFlow)\n this.getGlobalState().previousFlows.set(flowId, cloneFlow(currentFlow))\n })\n }\n\n callback?.(visible)\n }\n\n return [flowId, wrappedCallback] as RulesRegistryBatch[number]\n })\n\n Promise.all(flowIdsWithWrappedCallbacks).then((results) => {\n this.getGlobalState().collections.batchRegister(results)\n })\n }\n}\n","import type { Flow } from './flow'\n\nexport enum TriggerType {\n MANUAL = 'MANUAL',\n AUTOMATIC = 'AUTOMATIC',\n}\n\nexport enum FlowStatus {\n DRAFT = 'DRAFT',\n ACTIVE = 'ACTIVE',\n ARCHIVED = 'ARCHIVED',\n}\n\nexport type StepAction =\n | 'flow.back'\n | 'flow.complete'\n | 'flow.forward'\n | 'flow.restart'\n | 'flow.skip'\n | 'flow.start'\n | 'step.complete'\n | 'step.reset'\n | 'step.start'\n | false\n\nexport type PropertyPayload = Record<string, any>\n\nexport interface FlowStep extends StatefulStep {\n /**\n * Order of the step in the Flow.\n */\n order: number\n\n /**\n * Name of the step when shown in a list view.\n */\n stepName?: string\n\n /**\n * Title of the step.\n */\n title?: string\n\n /**\n * Subtitle of the step.\n */\n subtitle?: string\n\n /**\n * Config for the primary button in this step\n */\n primaryButton?: {\n /**\n * Primary button action. (defaults to step.complete)\n */\n action?: StepAction\n\n /**\n * Primary button URI target (defaults to _self).\n */\n target?: string\n\n /**\n * Primary button title. If omitted, the primary button will not be shown.\n */\n title?: string\n\n /**\n * Primary button URI.\n */\n uri?: string\n }\n\n /**\n * @deprecated Use primaryButton.title instead\n * @description Primary button title. If omitted, the primary button will not be shown.\n */\n primaryButtonTitle?: string\n\n /**\n * @deprecated Use primaryButton.uri instead\n * @description Primary button URI.\n */\n primaryButtonUri?: string\n\n /**\n * @deprecated Use primaryButton.target instead\n * @description Primary button URI target (defaults to _self).\n */\n primaryButtonUriTarget?: string\n\n /**\n * Config for the secondary button in this step\n */\n secondaryButton?: {\n /**\n * Secondary button action. (defaults to step.complete)\n */\n action?: StepAction\n\n /**\n * Secondary button URI target (defaults to _self).\n */\n target?: string\n\n /**\n * Secondary button title. If omitted, the secondary button will not be shown.\n */\n title?: string\n\n /**\n * Secondary button URI.\n */\n uri?: string\n }\n\n /**\n * @deprecated Use secondaryButton.title instead\n * @description Secondary button title. If omitted, the secondary button will not be shown.\n */\n secondaryButtonTitle?: string\n\n /**\n * @deprecated Use secondaryButton.uri instead\n * @description Secondary button URI.\n */\n secondaryButtonUri?: string\n\n /**\n * @deprecated Use secondaryButton.target instead\n * @description Secondary button URI target (defaults to _self)\n */\n secondaryButtonUriTarget?: string\n\n /**\n * Text on button if a back button is present.\n */\n backButtonTitle?: string\n\n /**\n * If true, the step will be marked as completed when the secondary button is clicked.\n */\n skippable?: boolean\n\n /**\n * Video url to be shown for components supporting video.\n */\n videoUri?: string\n\n /**\n * Image url to be shown for components supporting image.\n */\n imageUri?: string | null\n\n /**\n * Automatically mark the step as completed when the primary button is clicked. Default is false.\n */\n autoMarkCompleted?: boolean\n\n /**\n * @ignore\n */\n props?: any\n /**\n * Criteria that needs to be met for the step to complete.\n * Completion criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be completed.\n */\n completionCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to start.\n * Start criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be started.\n */\n startCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to be visible.\n * Visibility criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be visible.\n */\n visibilityCriteria?: string\n\n /**\n * Progress if the step is tied to another Frigade Flow through completionCriteria.\n */\n progress?: number\n\n /**\n * Whether the step is dismissible (for instance, tooltips or other non-essential steps).\n */\n dismissible?: boolean\n\n /**\n * Any other additional props defined in the YAML config.\n */\n [x: string | number | symbol]: unknown\n\n /**\n * Marks the step started.\n */\n start: (properties?: PropertyPayload) => Promise<void>\n\n /**\n * Marks the step completed.\n * @param optimistic If true, the step will be marked as completed without waiting for the API and validation of any targeting rules.\n */\n complete: (properties?: PropertyPayload, optimistic?: boolean) => Promise<void>\n\n /**\n * Resets the step (useful for undoing a finished step).\n */\n reset: () => Promise<void>\n\n /**\n * Event handler called when this step's state changes.\n */\n onStateChange: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Removes the given callback from the list of event handlers.\n */\n removeStateChangeHandler: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Reference to this step's parent Flow\n */\n flow: Flow\n}\n\nexport interface FrigadeConfig {\n /**\n * Frigade API key. You can find your API key in the Frigade Dashboard under \"Developer\".\n */\n apiKey?: string\n /**\n * API url to use for all requests. Defaults to https://api.frigade.com\n */\n apiUrl?: string\n\n /**\n * User ID to use for all requests. If not provided, a Guest ID will be generated.\n */\n userId?: string\n\n /**\n * Group ID (organization) to use for all requests.\n */\n groupId?: string\n\n /**\n * Optional user properties to send to the API.\n */\n userProperties?: PropertyPayload\n\n /**\n * Optional group properties to send to the API.\n */\n groupProperties?: PropertyPayload\n\n /**\n * Whether to generate a Guest ID and session if no userId is not provided on initialization.\n * If set to false, Frigade will not initialize until a userId is provided via `frigade.identify()`.\n *\n * Defaults to true.\n */\n generateGuestId?: boolean\n\n /**\n * Whether to sync state with Frigade on URL or focus change. Defaults to true.\n */\n syncOnWindowUpdates?: boolean\n\n /**\n * @ignore Internal use only.\n * If enabled, Frigade will not send any data to the API. A user's state will be reset on page refresh.\n */\n __readOnly?: boolean\n\n /**\n * @ignore Internal use only.\n * Map of Flow ID to Flow State for all flows in the app that should be mocked.\n */\n __flowStateOverrides?: Record<string, StatefulFlow>\n\n /**\n * @ignore Internal use only.\n */\n __instanceId?: string\n}\n\nexport interface StatefulStep {\n id: string\n $state: {\n completed: boolean\n started: boolean\n visible: boolean\n blocked: boolean\n lastActionAt?: Date\n }\n // allow any other properties\n [key: string]: any\n}\n\nexport interface StatefulFlow {\n flowSlug: string\n flowName: string\n flowType: FlowType\n data: {\n steps: StatefulStep[]\n // allow any other properties\n [key: string]: any\n }\n $state: {\n currentStepId: string\n currentStepIndex: number\n completed: boolean\n started: boolean\n skipped: boolean\n visible: boolean\n lastActionAt?: Date\n }\n}\n\nexport enum CollectionType {\n CUSTOM = 'CUSTOM',\n DEFAULT = 'DEFAULT',\n}\n\nexport interface ComputedCollection {\n collectionId: string\n flowId: string\n visible: boolean\n allowedComponents: []\n collectionType: CollectionType\n}\n\nexport interface CollectionMetadata {\n computedOrder: ComputedCollection[]\n}\n\nexport interface FlowStates {\n eligibleFlows: StatefulFlow[]\n ineligibleFlows: string[]\n collections?: CollectionMetadata\n}\n\nexport enum FlowType {\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}\n\nexport type FlowActionType =\n | 'STARTED_STEP'\n | 'COMPLETED_STEP'\n | 'NOT_STARTED_STEP'\n | 'STARTED_FLOW'\n | 'COMPLETED_FLOW'\n | 'SKIPPED_FLOW'\n | 'NOT_STARTED_FLOW'\n\nexport interface FlowStateDTO {\n userId: string\n groupId?: string\n flowSlug?: string\n stepId?: string\n data?: any\n actionType?: FlowActionType\n createdAt?: Date\n context?: FlowStateContext\n}\n\nexport interface FlowStateContext {\n url?: string\n userAgent?: string\n}\n\nexport interface TrackingEvent {\n event: string\n properties?: PropertyPayload\n}\n\nexport interface SessionDTO {\n userId: string\n groupId?: string\n userProperties?: PropertyPayload\n userEvents?: TrackingEvent[]\n groupProperties?: PropertyPayload\n groupEvents?: TrackingEvent[]\n linkGuestId?: string\n}\n"],"mappings":";k9BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,UAAAE,EAAA,eAAAC,EAAA,aAAAC,EAAA,YAAAC,EAAA,gBAAAC,IAAA,eAAAC,GAAAP,ICAO,IAAMQ,EAAiB,SCC9B,IAAAC,EAA6B,gBCuBtB,IAAIC,EAAyD,CAAC,EAE9D,SAASC,EAAkBC,EAAuC,CACvE,MAAO,GAAGA,EAAe,gBAAgBA,EAAe,QAC1D,CCxBO,IAAMC,EAAN,KAAgB,CASrB,YAAYC,EAAuB,CARnC,KAAO,OAAwB,CAC7B,OAAQ,GACR,OAAQ,0BACR,OAAQC,EAAgB,EACxB,aAAc,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,UAAU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,CAAM,GAE3DqC,GAAA,YAAAA,EAAU,aAAcT,GAE1B,KAAK,eAAe,EAAE,0BAA0B,QAASnB,GAAY,CACnEA,EAAQ2B,EAAaC,CAAQ,EAC7B,KAAK,eAAe,EAAE,cAAc,IAAIrC,EAAQW,EAAUyB,CAAW,CAAC,CACxE,CAAC,EAGHD,GAAA,MAAAA,EAAWP,EACb,CAE+B,CACjC,EAAC,EAED,QAAQ,IAAIK,CAA2B,EAAE,KAAMK,GAAY,CACzD,KAAK,eAAe,EAAE,YAAY,cAAcA,CAAO,CACzD,CAAC,CACH,GACF,EC1gBO,IAAKC,OACVA,EAAA,OAAS,SACTA,EAAA,UAAY,YAFFA,OAAA,IAKAC,OACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SACTA,EAAA,SAAW,WAHDA,OAAA,IAkVL,IAAKC,OACVA,EAAA,aAAe,eACfA,EAAA,UAAY,YACZA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,QAAU,UACVA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,aAAe,eACfA,EAAA,WAAa,aACbA,EAAA,OAAS,SACTA,EAAA,KAAO,OAXGA,OAAA","names":["src_exports","__export","Flow","FlowStatus","FlowType","Frigade","TriggerType","__toCommonJS","VERSION_NUMBER","import_uuid","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","filteredConfig","_","v","__spreadValues","path","options","__async","getEmptyResponse","gracefulFetch","getHeaders","globalStateKey","getGlobalStateKey","frigadeGlobalState","Flow","Fetchable","config","id","visible","overrideStatefulFlow","_a","_b","_c","statefulFlow","step","index","stepObj","existingStep","key","__spreadProps","__spreadValues","newSteps","properties","__async","thisStep","copy","clone","STARTED_STEP","optimistic","isLastStep","COMPLETED_STEP","NOT_STARTED_STEP","handler","wrapperHandler","flow","previousStep","h","STARTED_FLOW","COMPLETED_FLOW","SKIPPED_FLOW","nextStep","NOT_STARTED_FLOW","currentStep","previousFlow","variables","replaceVariables","str","matches","match","variable","action","data","stepId","date","flowStatesRaw","getContext","callback","prevFlow","cloneFlow","NOT_STARTED_STEP","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","GUEST_KEY","GUEST_PREFIX","GET_CACHE_PREFIX","LOCAL_STORAGE_PREFIX","cloneFlow","flow","Flow","clone","obj","getHeaders","apiKey","VERSION_NUMBER","getLocalStorage","key","isWeb","setLocalStorage","value","clearCache","frigadeGlobalState","key","GET_CACHE_PREFIX","resetAllLocalStorage","isWeb","LOCAL_STORAGE_PREFIX","CallQueue","call","now","item","callQueue","gracefulFetch","url","options","__async","_a","getEmptyResponse","lastCallDataKey","response","error","body","e","generateGuestId","guestId","getLocalStorage","GUEST_KEY","GUEST_PREFIX","uuidv4","setLocalStorage","isWeb","getContext","currentUrl","Rules","rulesData","ruleId","rule","flowId","callback","registeredFlow","flowInRules","item","visibleAPIOverride","otherFlowId","otherId","_a","otherVisible","otherVisited","flowIds","visible","Frigade","Fetchable","apiKey","config","__spreadValues","__async","isWeb","event","globalStateKey","getGlobalStateKey","frigadeGlobalState","_a","GUEST_PREFIX","userId","properties","__spreadProps","groupId","sessionDTO","flowId","flow","collectionId","collection","enrichedFlows","item","collections","resetAllLocalStorage","clearCache","handler","lastFlow","cloneFlow","h","that","validator","target","key","value","previousState","newState","Rules","overrideFlowStateRaw","_b","flowStateRaw","getContext","rulesData","allowedComponents","collectionType","visible","currentRule","statefulFlow","Flow","flowIds","flowIdsWithWrappedCallbacks","_0","callback","currentFlow","prevFlow","results","TriggerType","FlowStatus","FlowType"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/shared/fetchable.ts","../src/core/flow.ts","../src/core/rules.ts","../src/core/frigade.ts","../src/core/types.ts"],"sourcesContent":["export { Frigade } from './core/frigade'\nexport { Flow } from './core/flow'\nexport {\n FlowStatus,\n type FlowStep,\n type FrigadeConfig,\n FlowType,\n type StatefulFlow,\n TriggerType,\n PropertyPayload,\n} from './core/types'\nexport type {\n EnrichedRule,\n Rule,\n RulesList,\n RulesRegistryCallback,\n RulesRegistryBatch,\n} from './core/rules'\n","export const VERSION_NUMBER = '0.2.20'\n","import { VERSION_NUMBER } from '../core/version'\nimport { v4 as uuidv4 } from 'uuid'\nimport { Flow } from '../core/flow'\nimport { frigadeGlobalState } from './state'\nimport { FlowStateContext } from '../core/types'\n\nexport const NOT_STARTED_STEP = 'NOT_STARTED_STEP'\nexport const COMPLETED_FLOW = 'COMPLETED_FLOW'\nexport const SKIPPED_FLOW = 'SKIPPED_FLOW'\nexport const STARTED_FLOW = 'STARTED_FLOW'\nexport const NOT_STARTED_FLOW = 'NOT_STARTED_FLOW'\nexport const COMPLETED_STEP = 'COMPLETED_STEP'\nexport const STARTED_STEP = 'STARTED_STEP'\nconst GUEST_KEY = 'frigade-guest-key'\nexport const GUEST_PREFIX = 'guest_'\nconst GET_CACHE_PREFIX = 'get-cache-'\nconst LOCAL_STORAGE_PREFIX = 'fr-js-'\n\nexport function cloneFlow(flow: Flow): Flow {\n const newFlow = new Flow({\n config: flow.config,\n id: flow.id,\n })\n return newFlow\n}\n\nexport function clone<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj))\n}\n\nexport function getHeaders(apiKey: string) {\n return {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Frigade-SDK-Version': VERSION_NUMBER,\n 'X-Frigade-SDK-Platform': 'Javascript',\n },\n }\n}\n\nfunction getLocalStorage(key: string) {\n if (isWeb()) {\n return window.localStorage.getItem(`${LOCAL_STORAGE_PREFIX}${key}`)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (isWeb()) {\n window.localStorage.setItem(`${LOCAL_STORAGE_PREFIX}${key}`, value)\n }\n}\n\nfunction setGlobalState(key: string, value: any) {\n frigadeGlobalState[key] = value\n}\n\nfunction getGlobalState(key: string): any {\n return frigadeGlobalState[key]\n}\n\nexport function clearCache() {\n Object.keys(frigadeGlobalState).forEach((key) => {\n if (key.startsWith(GET_CACHE_PREFIX)) {\n delete frigadeGlobalState[key]\n }\n })\n}\n\nexport function resetAllLocalStorage() {\n if (isWeb()) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith(LOCAL_STORAGE_PREFIX)) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nclass CallQueue {\n private queue: {\n call: string\n time: number\n }[] = []\n private readonly ttlInMS = 100\n private readonly cacheSize = 5\n\n public push(call: string) {\n const now = new Date()\n if (this.queue.length >= this.cacheSize) {\n this.queue.shift()\n }\n this.queue.push({\n call: call,\n time: now.getTime(),\n })\n }\n\n public hasIdenticalCall(call: string) {\n const now = new Date()\n this.queue = this.queue.filter((item) => now.getTime() - item.time < this.ttlInMS)\n return this.queue.some((item) => item.call === call)\n }\n}\n\nconst callQueue = new CallQueue()\n\nexport async function gracefulFetch(url: string, options: any) {\n if (typeof globalThis.fetch !== 'function') {\n return getEmptyResponse(\n \"- Attempted to call fetch() in an environment that doesn't support it.\"\n )\n }\n\n if (isWeb() && options && options.body && options.method === 'POST') {\n const lastCallDataKey = `${url}${JSON.stringify(options.body ?? {})}`\n if (callQueue.hasIdenticalCall(lastCallDataKey)) {\n return getEmptyResponse()\n }\n callQueue.push(lastCallDataKey)\n }\n\n let response\n try {\n response = fetch(url, options)\n response = await response\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse('Received an empty response')\n }\n\n if (response.status >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n try {\n if (response.status === 204) {\n return getEmptyResponse()\n }\n\n let body\n try {\n body = await response.json()\n } catch (e) {\n return getEmptyResponse()\n }\n\n if (body.error) {\n return getEmptyResponse(body.error)\n }\n return body\n } catch (e) {\n return getEmptyResponse(e)\n }\n}\n\nexport function getEmptyResponse(error?: any) {\n if (error) {\n console.log('Call to Frigade failed', error)\n }\n\n // Create empty response that contains the .json method and returns an empty object\n return {\n json: () => ({}),\n }\n}\n\nexport function generateGuestId() {\n if (isWeb()) {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n setLocalStorage(GUEST_KEY, guestId)\n }\n return guestId\n } else {\n return `${GUEST_PREFIX}${uuidv4()}`\n }\n}\n\nexport function fetcher(apiKey: string, path: string, options?: Record<any, any>) {\n return gracefulFetch(`//api.frigade.com/v1/public${path}`, {\n ...(options ?? {}),\n ...getHeaders(apiKey),\n })\n}\n\nexport function isWeb() {\n return (\n typeof window !== 'undefined' &&\n typeof window.document !== 'undefined' &&\n typeof window.localStorage !== 'undefined'\n )\n}\n\nexport function getContext(currentUrl: string): FlowStateContext {\n if (!isWeb()) {\n return {}\n }\n\n return {\n url: currentUrl,\n userAgent: navigator.userAgent,\n }\n}\n","import { FlowStates, FlowStep, FrigadeConfig, StatefulFlow } from '../core/types'\nimport { Flow } from '../core/flow'\nimport type { Rules } from '../core/rules'\n\nexport interface FrigadeGlobalState {\n refreshStateFromAPI: (overrideFlowStatesRaw?: FlowStates) => Promise<void>\n flowStates: Record<string, StatefulFlow>\n collections: Rules\n onFlowStateChangeHandlerWrappers: Map<\n (flow: Flow, previousFlow: Flow) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onStepStateChangeHandlerWrappers: Map<\n (step: FlowStep, previousStep: FlowStep) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onFlowStateChangeHandlers: ((flow: Flow, previousFlow: Flow) => void)[]\n previousFlows: Map<string, Flow>\n variables: Record<string, Record<string, any>>\n lastSyncDate?: Date\n config: FrigadeConfig\n currentUrl: string\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}`\n}\n","import { generateGuestId, getEmptyResponse, getHeaders, gracefulFetch } from './utils'\nimport { FrigadeConfig } from '../core/types'\nimport { frigadeGlobalState, FrigadeGlobalState, getGlobalStateKey } from './state'\n\nexport class Fetchable {\n public config: FrigadeConfig = {\n apiKey: '',\n apiUrl: 'https://api.frigade.com',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(12).substring(4),\n generateGuestId: true,\n }\n\n constructor(config: FrigadeConfig) {\n const filteredConfig = Object.fromEntries(Object.entries(config).filter(([_, v]) => v != null))\n if (!config.userId && config.generateGuestId === false) {\n delete this.config.userId\n }\n this.config = {\n ...this.config,\n ...filteredConfig,\n }\n }\n\n /**\n * @ignore\n */\n public async fetch(path: string, options?: Record<any, any>) {\n if (this.config.__readOnly) {\n return getEmptyResponse()\n }\n\n return gracefulFetch(this.getAPIUrl(path), {\n keepalive: true,\n ...(options ?? {}),\n ...getHeaders(this.config.apiKey),\n })\n }\n\n private getAPIUrl(path: string) {\n return `${this.config.apiUrl.replace(/\\/$/, '')}/${path.replace(/^\\//, '')}`\n }\n\n /**\n * @ignore\n */\n protected getGlobalState(): FrigadeGlobalState {\n const globalStateKey = getGlobalStateKey(this.config)\n if (!frigadeGlobalState[globalStateKey]) {\n throw new Error('Frigade has not yet been initialized')\n }\n return frigadeGlobalState[globalStateKey]\n }\n}\n","import {\n FlowActionType,\n FlowStateDTO,\n FlowStates,\n FlowStep,\n FrigadeConfig,\n PropertyPayload,\n StatefulFlow,\n StatefulStep,\n} from './types'\nimport {\n clone,\n cloneFlow,\n COMPLETED_FLOW,\n COMPLETED_STEP,\n getContext,\n NOT_STARTED_FLOW,\n NOT_STARTED_STEP,\n SKIPPED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { Fetchable } from '../shared/fetchable'\nimport { RulesRegistryCallback } from './rules'\n\nexport class Flow extends Fetchable {\n /**\n * The Flow's ID.\n */\n public id: string\n /**\n * The Flow's component ID.\n */\n public componentId: string\n /**\n * Ordered map of the Steps in the Flow.\n * See [Flow Step Definition](https://docs.frigade.com/v2/sdk/js/step) for more information.\n */\n public steps: Map<string, FlowStep>\n /**\n * The user-facing title of the Flow, if defined at the top level of the YAML config.\n */\n public title?: string\n /**\n * The user-facing description of the Flow, if defined at the top level of the YAML config.\n */\n public subtitle?: string\n /**\n * The metadata of the Flow.\n * @ignore\n */\n public rawData: StatefulFlow\n /**\n * Whether the Flow is completed or not.\n */\n public isCompleted: boolean\n /**\n * Whether the Flow is started or not.\n */\n public isStarted: boolean\n /**\n * Whether the Flow has been skipped or not.\n */\n public isSkipped: boolean\n /**\n * @ignore\n */\n private _isVisible: boolean = false\n /**\n * Whether the Flow is visible to the user based on the current user/group's state.\n */\n get isVisible() {\n if (this._isVisible === false) {\n return false\n }\n\n return this.getGlobalState().collections.isFlowVisible(this.id)\n }\n set isVisible(visible: boolean) {\n this._isVisible = visible\n }\n\n /**\n * @ignore\n */\n private lastStepUpdate: Map<(step: FlowStep, previousStep: FlowStep) => void, FlowStep> =\n new Map()\n\n constructor({ config, id }: { config: FrigadeConfig; id: string }) {\n super(config)\n this.id = id\n this.init()\n }\n\n /**\n * Reload the Flow data from the server\n */\n reload() {\n this.init()\n }\n\n /**\n * @ignore\n */\n resyncState(overrideStatefulFlow?: StatefulFlow) {\n const statefulFlow = overrideStatefulFlow ?? this.getStatefulFlow()\n\n this.rawData = statefulFlow\n this.title = statefulFlow?.data?.title\n this.subtitle = statefulFlow?.data?.subtitle\n\n this.isCompleted = statefulFlow.$state.completed\n this.isStarted = statefulFlow.$state.started\n this.isSkipped = statefulFlow.$state.skipped\n this._isVisible = statefulFlow.$state.visible\n\n statefulFlow.data.steps.forEach((step, index) => {\n const stepObj = this.initStepFromStatefulStep(step, index)\n\n const existingStep = this.steps?.get(step.id)\n if (existingStep) {\n Object.keys(stepObj).forEach((key) => {\n existingStep[key] = stepObj[key]\n })\n }\n })\n\n if (this.steps && this.steps.size > 0) {\n this.applyVariables(this.getGlobalState().variables[this.id] ?? {})\n }\n }\n\n /**\n * @ignore\n */\n private initStepFromStatefulStep(step: StatefulStep, index: number) {\n return {\n ...step,\n flow: this,\n $state: {\n ...step.$state,\n lastActionAt: step.$state.lastActionAt ? new Date(step.$state.lastActionAt) : undefined,\n },\n order: index,\n } as Partial<FlowStep>\n }\n\n /**\n * @ignore\n */\n private init() {\n const statefulFlow = this.getStatefulFlow()\n\n this.resyncState()\n\n const newSteps = new Map<string, FlowStep>()\n\n statefulFlow.data.steps.forEach((step, index) => {\n const stepObj = this.initStepFromStatefulStep(step, index)\n\n stepObj.start = async (properties?: PropertyPayload) => {\n const thisStep = this.steps.get(step.id)\n\n if (this.getCurrentStep().id === thisStep.id && thisStep.$state.started) {\n return\n }\n\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.data.steps[thisStep.order].$state.started = true\n copy.data.steps[thisStep.order].$state.lastActionAt = new Date()\n copy.$state.lastActionAt = new Date()\n copy.$state.currentStepId = thisStep.id\n copy.$state.currentStepIndex = thisStep.order\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n await this.sendFlowStateToAPI(STARTED_STEP, properties, thisStep.id)\n }\n\n stepObj.complete = async (properties?: PropertyPayload, optimistic: boolean = true) => {\n const thisStep = this.steps.get(step.id)\n\n if (thisStep.$state.completed && optimistic) {\n return\n }\n\n if (optimistic) {\n const isLastStep = thisStep.order + 1 === this.getNumberOfAvailableSteps()\n const copy = clone(this.getGlobalState().flowStates[this.id])\n\n copy.$state.started = true\n copy.data.steps[thisStep.order].$state.completed = true\n copy.data.steps[thisStep.order].$state.started = true\n copy.data.steps[thisStep.order].$state.lastActionAt = new Date()\n\n // If there are more index, advance current step\n if (!isLastStep) {\n copy.$state.currentStepId = this.getStepByIndex(thisStep.order + 1).id\n copy.$state.currentStepIndex = thisStep.order + 1\n }\n\n if (isLastStep) {\n copy.$state.completed = true\n }\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n }\n\n await this.sendFlowStateToAPI(COMPLETED_STEP, properties, thisStep.id)\n }\n\n stepObj.reset = async () => {\n const thisStep = this.steps.get(step.id)\n\n if (!thisStep.$state.completed) {\n return\n }\n\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.data.steps[thisStep.order].$state.started = false\n copy.data.steps[thisStep.order].$state.completed = false\n copy.data.steps[thisStep.order].$state.lastActionAt = undefined\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n await this.sendFlowStateToAPI(NOT_STARTED_STEP, undefined, thisStep.id)\n }\n\n stepObj.onStateChange = (handler: (step: FlowStep, previousStep: FlowStep) => void) => {\n const wrapperHandler = (flow: Flow) => {\n if (flow.id !== this.id) {\n return\n }\n const thisStep = flow.steps.get(step.id)\n const previousStep = this.lastStepUpdate.get(handler)\n\n if (\n thisStep.$state.completed !== previousStep?.$state.completed ||\n thisStep.$state.started !== previousStep?.$state.started ||\n thisStep.$state.visible !== previousStep?.$state.visible ||\n thisStep.$state.blocked !== previousStep?.$state.blocked\n ) {\n handler(thisStep, previousStep ?? clone(thisStep))\n this.lastStepUpdate.set(handler, clone(thisStep))\n }\n }\n this.getGlobalState().onStepStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n stepObj.removeStateChangeHandler = (\n handler: (step: FlowStep, previousStep: FlowStep) => void\n ) => {\n const wrapperHandler = this.getGlobalState().onStepStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n newSteps.set(step.id, stepObj as FlowStep)\n })\n this.steps = newSteps\n // Check if empty object\n if (\n this.getGlobalState().variables &&\n this.getGlobalState().variables[this.id] &&\n Object.keys(this.getGlobalState().variables[this.id]).length > 0\n ) {\n this.applyVariables(this.getGlobalState().variables[this.id])\n }\n }\n\n /**\n * Marks the flow started\n */\n public async start(properties?: PropertyPayload) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowStarted()\n\n await this.sendFlowStateToAPI(STARTED_FLOW, properties)\n }\n\n /**\n * Marks the flow completed\n */\n public async complete(properties?: PropertyPayload) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n await this.sendFlowStateToAPI(COMPLETED_FLOW, properties)\n }\n\n /**\n * Marks the flow skipped\n */\n public async skip(properties?: PropertyPayload) {\n if (this.isSkipped) {\n return\n }\n this.optimisticallyMarkFlowSkipped()\n await this.sendFlowStateToAPI(SKIPPED_FLOW, properties)\n }\n\n /**\n * Navigates the flow to the next step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async forward(properties?: PropertyPayload) {\n const nextStep = this.getStepByIndex(this.getCurrentStepIndex() + 1)\n if (nextStep) {\n await nextStep.start(properties)\n } else {\n await this.complete(properties)\n }\n }\n\n /**\n * Navigates the flow to the previous step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async back(properties?: PropertyPayload) {\n const previousStep = this.getStepByIndex(this.getCurrentStepIndex() - 1)\n if (previousStep) {\n await previousStep.start(properties)\n }\n }\n\n /**\n * Restarts the flow/marks it not started\n */\n public async restart() {\n this.optimisticallyMarkFlowNotStarted()\n await this.sendFlowStateToAPI(NOT_STARTED_FLOW)\n }\n\n /**\n * Get a step by index\n * @param index\n */\n public getStepByIndex(index: number): FlowStep | undefined {\n return this.steps.get(Array.from(this.steps.keys())[index])\n }\n\n /**\n * Gets current step\n */\n public getCurrentStep(): FlowStep {\n return (\n this.steps.get(this.getStatefulFlow().$state.currentStepId) ??\n this.steps.get(Array.from(this.steps.keys())[0])\n )\n }\n\n /**\n * Get the index of the current step. Starts at 0\n */\n public getCurrentStepIndex(): number {\n const currentStep = this.getCurrentStep()\n return Array.from(this.steps.keys()).indexOf(currentStep.id)\n }\n\n /**\n * Get the number of completed steps for the current user in the current flow\n */\n public getNumberOfCompletedSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.$state.completed).length\n }\n\n /**\n * Get the number of available steps for the current user in the current flow. This is the number of steps that are not hidden.\n */\n public getNumberOfAvailableSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.$state.visible).length\n }\n\n /**\n * @ignore\n */\n public onStateChange(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = (flow: Flow, previousFlow: Flow) => {\n if (flow.id === this.id) {\n if (\n flow.isCompleted !== previousFlow?.isCompleted ||\n flow.isStarted !== previousFlow?.isStarted ||\n flow.isSkipped !== previousFlow?.isSkipped ||\n flow.isVisible !== previousFlow?.isVisible ||\n JSON.stringify(flow.steps) !== JSON.stringify(previousFlow?.steps)\n ) {\n handler(flow, previousFlow)\n }\n }\n }\n this.getGlobalState().onFlowStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n /**\n * @ignore\n */\n public removeStateChangeHandler(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = this.getGlobalState().onFlowStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n /**\n * Apply variables to the flow. This will replace any `${variable}` in the title, subtitle, and step fields with the value of the variable.\n * @param variables A record of variables to apply to the flow.\n */\n public applyVariables(variables: Record<string, any>) {\n // Replace ${variable} with the value of the variable\n const replaceVariables = (str: string) => {\n const matches = str.match(/\\${(.*?)}/g)\n if (matches) {\n matches.forEach((match) => {\n const variable = match.replace('${', '').replace('}', '')\n if (!variables[variable]) {\n return\n }\n str = str.replace(match, variables[variable])\n })\n }\n return str\n }\n\n this.title = replaceVariables(this.title ?? '')\n this.subtitle = replaceVariables(this.subtitle ?? '')\n this.steps.forEach((step) => {\n // Iterate over every string field in the step and replace variables\n Object.keys(step).forEach((key) => {\n if (typeof step[key] === 'string') {\n // @ts-ignore\n step[key] = replaceVariables(step[key])\n }\n })\n })\n\n this.getGlobalState().variables[this.id] = variables\n }\n\n /**\n * @ignore\n */\n private getStatefulFlow(): StatefulFlow {\n const userFlowStates = this.getGlobalState().flowStates\n return userFlowStates[this.id]\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowCompleted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = true\n copy.$state.started = true\n copy.$state.visible = false\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.started = true\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowNotStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = false\n copy.$state.started = false\n copy.$state.visible = true\n copy.$state.currentStepIndex = 0\n copy.$state.currentStepId = this.getStepByIndex(0)?.id\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n private async sendFlowStateToAPI(\n action: FlowActionType,\n data?: PropertyPayload,\n stepId?: string\n ) {\n const date = new Date()\n this.getGlobalState().lastSyncDate = date\n const flowStatesRaw: FlowStates = await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n flowSlug: this.id,\n stepId: stepId ?? this.getCurrentStep().id,\n data: data ? data : {},\n actionType: action,\n createdAt: date,\n context: getContext(this.getGlobalState().currentUrl),\n } as FlowStateDTO),\n })\n if (date < this.getGlobalState().lastSyncDate) {\n return\n }\n await this.getGlobalState().refreshStateFromAPI(flowStatesRaw)\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowSkipped() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.skipped = true\n copy.$state.visible = false\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n public register(callback?: RulesRegistryCallback) {\n const globalState = this.getGlobalState()\n\n globalState.collections.register(this.id, (visible) => {\n const prevFlow = this.getGlobalState().previousFlows.get(this.id)\n\n if (prevFlow?._isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(this, prevFlow)\n this.getGlobalState().previousFlows.set(this.id, cloneFlow(this))\n })\n }\n\n callback?.(visible)\n })\n }\n\n public unregister() {\n if (!this.getGlobalState().collections) {\n return\n }\n this.getGlobalState().collections.unregister(this.id)\n }\n}\n","import type { Flow } from './flow'\n\nexport type RulesRegistryCallback = (visible: boolean) => void\n\nexport type RulesRegistryBatch = [string, RulesRegistryCallback][]\n\nexport interface RulesRegistryItem {\n visible: boolean\n visited: boolean\n callback: RulesRegistryCallback\n}\n\nexport interface Rule {\n allowedComponents: string[]\n collectionType: 'DEFAULT' | 'CUSTOM'\n flows: {\n flowId: string\n visible: boolean\n }[]\n}\n\nexport interface EnrichedRule extends Omit<Rule, 'flows'> {\n flows: Array<\n Rule['flows'][number] & {\n flow: Flow\n }\n >\n}\n\nexport type RulesList = Map<string, Rule>\n\nexport class Rules {\n private readonly registry: Map<string, RulesRegistryItem> = new Map()\n private registryStateLocked: boolean = false\n private rules: RulesList = new Map()\n private flowsInRules: Set<string> = new Set()\n\n constructor(rulesData: RulesList) {\n this.ingestRulesData(rulesData)\n }\n\n getRule(ruleId: string) {\n return this.rules.get(ruleId)\n }\n\n getRules() {\n return this.rules\n }\n\n ingestRulesData(rulesData: RulesList) {\n this.rules = rulesData\n\n for (const [, rule] of this.rules) {\n for (const { flowId } of rule.flows) {\n this.flowsInRules.add(flowId)\n }\n }\n\n if (this.registry.size > 0) {\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n }\n\n this.fireCallbacks()\n }\n\n fireCallbacks() {\n for (const [flowId, { callback }] of this.registry) {\n if (typeof callback === 'function') {\n callback(this.isFlowVisible(flowId))\n }\n }\n }\n\n isFlowVisible(flowId: string) {\n const registeredFlow = this.registry.get(flowId)\n const flowInRules = this.flowsInRules.has(flowId)\n\n if (registeredFlow == null || !flowInRules) {\n return true\n }\n\n return registeredFlow.visible\n }\n\n lockRegistryState() {\n this.registryStateLocked = true\n }\n\n unlockRegistryState() {\n this.registryStateLocked = false\n }\n\n resetRegistryState() {\n for (const [flowId, item] of this.registry) {\n item.visible = false\n item.visited = false\n\n this.registry.set(flowId, item)\n }\n }\n\n processRules() {\n for (const [, rule] of this.rules) {\n for (const { flowId, visible: visibleAPIOverride } of rule.flows) {\n const registeredFlow = this.registry.get(flowId)\n\n // If this flow in the rule isn't registered, we have no opinion on it yet\n if (registeredFlow == null) {\n continue\n }\n\n // The API can force a flow to be hidden due to cool-offs, etc.\n if (visibleAPIOverride === false && registeredFlow.visible !== true) {\n this.visit(flowId, false)\n continue\n }\n\n // If this flow was processed in a previous rule and the registry is locked,\n // visibility shouldn't change until next time we run processRules\n if (registeredFlow.visited && this.registryStateLocked) {\n continue\n }\n\n const flowIdsInThisRule = rule.flows\n .map(({ flowId: otherFlowId }) => otherFlowId)\n .filter((otherFlowId) => otherFlowId !== flowId)\n\n // If another flow in this rule has been visited already and is visible...\n const anotherFlowInThisRuleIsVisible = flowIdsInThisRule.some((otherId) => {\n const { visible: otherVisible, visited: otherVisited } = this.registry.get(otherId) ?? {}\n\n return otherVisible && otherVisited\n })\n\n // ...then this flow is hidden\n if (anotherFlowInThisRuleIsVisible) {\n this.visit(flowId, false)\n\n continue\n }\n\n // No other flows are visible, so this flow is visible by default\n this.visit(flowId)\n }\n }\n }\n\n register(flowId: string | RulesRegistryBatch, callback?: RulesRegistryCallback) {\n if (Array.isArray(flowId)) {\n this.batchRegister(flowId)\n return\n }\n\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.fireCallbacks()\n }\n\n batchRegister(flowIds: RulesRegistryBatch) {\n flowIds.forEach(([flowId, callback]) => {\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.lockRegistryState()\n\n this.fireCallbacks()\n }\n\n unregister(flowId: string) {\n this.registry.delete(flowId)\n\n this.resetRegistryState()\n this.processRules()\n\n this.fireCallbacks()\n }\n\n private visit(flowId: string, visible: boolean = true) {\n const item = this.registry.get(flowId) ?? {\n callback: () => {},\n visible,\n visited: true,\n }\n\n item.visible = visible\n item.visited = true\n\n this.registry.set(flowId, item)\n }\n}\n","import {\n FlowStateDTO,\n FlowStates,\n FrigadeConfig,\n PropertyPayload,\n SessionDTO,\n StatefulFlow,\n} from './types'\nimport {\n clearCache,\n cloneFlow,\n getContext,\n GUEST_PREFIX,\n isWeb,\n resetAllLocalStorage,\n} from '../shared/utils'\nimport { Flow } from './flow'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/fetchable'\nimport {\n type EnrichedRule,\n type Rule,\n Rules,\n type RulesList,\n type RulesRegistryBatch,\n} from './rules'\n\nexport class Frigade extends Fetchable {\n /**\n * @ignore\n */\n private flows: Flow[] = []\n /**\n * @ignore\n */\n private initPromise: Promise<void>\n /**\n * @ignore\n */\n private hasFailed = false\n\n /**\n * @ignore\n */\n private visibilityChangeHandler = async () => {\n if (document.visibilityState === 'visible') {\n await this.refreshStateFromAPI()\n }\n }\n\n constructor(apiKey: string, config?: FrigadeConfig) {\n super({\n apiKey,\n ...config,\n })\n this.init(this.config)\n if (isWeb() && this.config.syncOnWindowUpdates !== false) {\n document.addEventListener('visibilitychange', this.visibilityChangeHandler)\n // @ts-ignore\n if (window.navigation) {\n // @ts-ignore\n window.navigation.addEventListener('navigate', async (event) => {\n if (this.getGlobalState().currentUrl === event.destination.url) {\n return\n }\n try {\n this.getGlobalState().currentUrl = event.destination.url\n this.refreshStateFromAPI()\n } catch (e) {}\n })\n }\n }\n }\n\n /**\n * Gets the current configuration.\n */\n getConfig() {\n return this.config\n }\n\n /**\n * @ignore\n */\n destroy() {\n if (isWeb()) {\n document.removeEventListener('visibilitychange', this.visibilityChangeHandler)\n // Remove all other event listeners\n const globalStateKey = getGlobalStateKey(this.config)\n if (frigadeGlobalState[globalStateKey]) {\n frigadeGlobalState[globalStateKey].onFlowStateChangeHandlers = []\n }\n }\n }\n\n /**\n * @ignore\n */\n private async init(config: FrigadeConfig): Promise<void> {\n this.updateConfig({\n ...this.config,\n ...config,\n })\n\n if (!this.config.userId && this.config.generateGuestId === false) {\n return\n }\n\n this.initPromise = (async () => {\n if (!this.config.__readOnly) {\n if (this.config.userId?.startsWith(GUEST_PREFIX)) {\n // do nothing\n } else if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n userProperties: this.config.userProperties,\n groupProperties: this.config.groupProperties,\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userProperties: this.config.userProperties,\n })\n }\n }\n await this.refreshStateFromAPI()\n })()\n\n return this.initPromise\n }\n\n /**\n * Set the current user.\n * @param userId\n * @param properties\n */\n public async identify(userId: string, properties?: PropertyPayload): Promise<void> {\n await this.updateConfig({ ...this.config, userId })\n await this.initIfNeeded()\n await this.session({\n userId: this.config.userId,\n userProperties: properties,\n })\n await this.resync()\n }\n\n /**\n * Set the group for the current user.\n * @param groupId\n * @param properties\n */\n public async group(groupId?: string, properties?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n this.updateConfig({ ...this.config, groupId })\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupProperties: properties,\n })\n await this.resync()\n }\n\n /**\n * Track an event for the current user (and group if set).\n * @param event\n * @param properties\n */\n public async track(event: string, properties?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n if (!event) {\n console.error('Event name is required to track an event')\n return\n }\n if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupEvents: [\n {\n event,\n properties,\n },\n ],\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n }\n await this.resync()\n }\n\n /**\n * @ignore\n */\n private async session(sessionDTO: SessionDTO) {\n await this.fetch('/v1/public/sessions', {\n method: 'POST',\n body: JSON.stringify(sessionDTO),\n })\n }\n\n /**\n * @ignore\n */\n public isReady(): boolean {\n return Boolean(this.config.__instanceId && this.config.apiKey && this.initPromise)\n }\n\n /**\n * Get a Flow by its ID.\n * @param flowId\n */\n public async getFlow(flowId: string) {\n await this.initIfNeeded()\n\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n await this.initIfNeeded()\n return this.flows\n }\n\n public async getCollection(collectionId: string) {\n await this.initIfNeeded()\n const collection = this.getGlobalState().collections.getRule(collectionId)\n\n if (collection == null) {\n return undefined\n }\n\n const enrichedFlows = await Promise.all(\n collection.flows.map(async (item) => ({\n ...item,\n flow: await this.getFlow(item.flowId),\n }))\n )\n\n collection.flows = enrichedFlows\n\n return collection as EnrichedRule\n }\n\n public async getCollections() {\n await this.initIfNeeded()\n const collections = this.getGlobalState().collections.getRules()\n\n if (collections == null) {\n return undefined\n }\n\n return collections\n }\n\n /**\n * Reload the current state of the flows by calling the Frigade API.\n * This will trigger all event handlers.\n * @param config optional config to use when reloading. If not passed, the current config will be used.\n */\n public async reload(config?: FrigadeConfig) {\n resetAllLocalStorage()\n clearCache()\n if (config) {\n await this.updateConfig(config)\n this.mockFlowStates(getGlobalStateKey(this.config))\n }\n this.initPromise = null\n await this.init(this.config)\n // Trigger all event handlers\n this.flows.forEach((flow) => {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n })\n }\n\n private async resync() {\n await this.refreshStateFromAPI()\n }\n\n /**\n * Event handler that captures all changes that happen to the state of the Flows.\n * @param handler\n */\n public async onStateChange(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers.push(handler)\n }\n\n /**\n * Returns true if the JS SDK failed to connect to the Frigade API.\n */\n hasFailedToLoad() {\n return this.hasFailed\n }\n\n /**\n * Removes the given handler from the list of event handlers.\n * @param handler\n */\n public async removeStateChangeHandler(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== handler)\n }\n\n /**\n * @ignore\n */\n private async initIfNeeded() {\n if (this.initPromise) {\n return this.initPromise\n } else {\n return this.init(this.config)\n }\n }\n\n /**\n * @ignore\n */\n private async refreshStateFromAPI(): Promise<void> {\n const globalStateKey = getGlobalStateKey(this.config)\n\n if (!frigadeGlobalState[globalStateKey]) {\n const that = this\n\n let validator = {\n set: function (target: any, key: any, value: any) {\n if (target[key]) {\n const previousState = target[key] as StatefulFlow\n const newState = value as StatefulFlow\n if (JSON.stringify(previousState) !== JSON.stringify(newState)) {\n that.triggerEventHandlers(newState, previousState)\n }\n }\n\n target[key] = value\n return true\n },\n }\n\n frigadeGlobalState[globalStateKey] = {\n refreshStateFromAPI: async () => {},\n collections: new Rules(new Map()),\n flowStates: new Proxy({}, validator),\n onFlowStateChangeHandlerWrappers: new Map(),\n onStepStateChangeHandlerWrappers: new Map(),\n onFlowStateChangeHandlers: [],\n previousFlows: new Map(),\n variables: {},\n config: this.config,\n currentUrl: isWeb() ? window.location.href : '',\n }\n\n if (this.config.__readOnly && this.config.__flowStateOverrides) {\n this.mockFlowStates(globalStateKey)\n\n return\n }\n\n frigadeGlobalState[globalStateKey].refreshStateFromAPI = async (\n overrideFlowStateRaw?: FlowStates\n ) => {\n if (this.config.__readOnly) {\n return\n }\n\n const flowStateRaw: FlowStates = overrideFlowStateRaw\n ? overrideFlowStateRaw\n : await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n context: getContext(this.getGlobalState().currentUrl),\n } as FlowStateDTO),\n })\n\n const rulesData: RulesList = new Map()\n\n flowStateRaw.collections?.computedOrder?.forEach(\n ({ allowedComponents, collectionId, collectionType, flowId, visible }) => {\n const currentRule: Rule = rulesData.get(collectionId) ?? {\n allowedComponents,\n collectionType,\n flows: [],\n }\n\n currentRule.flows.push({\n flowId,\n visible,\n })\n\n rulesData.set(collectionId, currentRule)\n }\n )\n\n frigadeGlobalState[globalStateKey].collections.ingestRulesData(rulesData)\n\n if (flowStateRaw && flowStateRaw.eligibleFlows) {\n flowStateRaw.eligibleFlows.forEach((statefulFlow) => {\n frigadeGlobalState[globalStateKey].flowStates[statefulFlow.flowSlug] = statefulFlow\n if (!this.flows.find((flow) => flow.id == statefulFlow.flowSlug)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: statefulFlow.flowSlug,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == statefulFlow.flowSlug) {\n flow.resyncState(statefulFlow)\n }\n })\n }\n })\n this.hasFailed = false\n } else {\n this.hasFailed = true\n }\n }\n }\n\n await frigadeGlobalState[globalStateKey].refreshStateFromAPI()\n }\n\n /**\n * @ignore\n */\n private mockFlowStates(globalStateKey: string) {\n Object.keys(this.config.__flowStateOverrides).forEach((flowId) => {\n frigadeGlobalState[globalStateKey].flowStates[flowId] =\n this.config.__flowStateOverrides[flowId]\n\n if (!this.flows.find((flow) => flow.id == flowId)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: flowId,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == flowId) {\n flow.resyncState(this.config.__flowStateOverrides[flowId])\n }\n })\n }\n })\n }\n\n /**\n * @ignore\n */\n private async updateConfig(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n if (frigadeGlobalState[getGlobalStateKey(this.config)]) {\n this.getGlobalState().config = this.config\n }\n }\n\n /**\n * @ignore\n */\n private async triggerEventHandlers(newState: StatefulFlow, previousState?: StatefulFlow) {\n if (newState) {\n this.flows.forEach((flow) => {\n if (flow.id == previousState.flowSlug) {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n flow.resyncState(newState)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n }\n })\n }\n }\n\n /**\n * @ignore\n */\n async batchRegister(flowIds: RulesRegistryBatch) {\n const flowIdsWithWrappedCallbacks = flowIds.map(async ([flowId, callback]) => {\n const currentFlow = await this.getFlow(flowId)\n const wrappedCallback = (visible: boolean) => {\n const prevFlow = this.getGlobalState().previousFlows.get(flowId)\n\n if (prevFlow?.isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(currentFlow, prevFlow)\n this.getGlobalState().previousFlows.set(flowId, cloneFlow(currentFlow))\n })\n }\n\n callback?.(visible)\n }\n\n return [flowId, wrappedCallback] as RulesRegistryBatch[number]\n })\n\n Promise.all(flowIdsWithWrappedCallbacks).then((results) => {\n this.getGlobalState().collections.batchRegister(results)\n })\n }\n}\n","import type { Flow } from './flow'\n\nexport enum TriggerType {\n MANUAL = 'MANUAL',\n AUTOMATIC = 'AUTOMATIC',\n}\n\nexport enum FlowStatus {\n DRAFT = 'DRAFT',\n ACTIVE = 'ACTIVE',\n ARCHIVED = 'ARCHIVED',\n}\n\nexport type StepAction =\n | 'flow.back'\n | 'flow.complete'\n | 'flow.forward'\n | 'flow.restart'\n | 'flow.skip'\n | 'flow.start'\n | 'step.complete'\n | 'step.reset'\n | 'step.start'\n | false\n\nexport type PropertyPayload = Record<string, any>\n\nexport interface FlowStep extends StatefulStep {\n /**\n * Order of the step in the Flow.\n */\n order: number\n\n /**\n * Name of the step when shown in a list view.\n */\n stepName?: string\n\n /**\n * Title of the step.\n */\n title?: string\n\n /**\n * Subtitle of the step.\n */\n subtitle?: string\n\n /**\n * Config for the primary button in this step\n */\n primaryButton?: {\n /**\n * Primary button action. (defaults to step.complete)\n */\n action?: StepAction\n\n /**\n * Primary button URI target (defaults to _self).\n */\n target?: string\n\n /**\n * Primary button title. If omitted, the primary button will not be shown.\n */\n title?: string\n\n /**\n * Primary button URI.\n */\n uri?: string\n }\n\n /**\n * @deprecated Use primaryButton.title instead\n * @description Primary button title. If omitted, the primary button will not be shown.\n */\n primaryButtonTitle?: string\n\n /**\n * @deprecated Use primaryButton.uri instead\n * @description Primary button URI.\n */\n primaryButtonUri?: string\n\n /**\n * @deprecated Use primaryButton.target instead\n * @description Primary button URI target (defaults to _self).\n */\n primaryButtonUriTarget?: string\n\n /**\n * Config for the secondary button in this step\n */\n secondaryButton?: {\n /**\n * Secondary button action. (defaults to step.complete)\n */\n action?: StepAction\n\n /**\n * Secondary button URI target (defaults to _self).\n */\n target?: string\n\n /**\n * Secondary button title. If omitted, the secondary button will not be shown.\n */\n title?: string\n\n /**\n * Secondary button URI.\n */\n uri?: string\n }\n\n /**\n * @deprecated Use secondaryButton.title instead\n * @description Secondary button title. If omitted, the secondary button will not be shown.\n */\n secondaryButtonTitle?: string\n\n /**\n * @deprecated Use secondaryButton.uri instead\n * @description Secondary button URI.\n */\n secondaryButtonUri?: string\n\n /**\n * @deprecated Use secondaryButton.target instead\n * @description Secondary button URI target (defaults to _self)\n */\n secondaryButtonUriTarget?: string\n\n /**\n * Text on button if a back button is present.\n */\n backButtonTitle?: string\n\n /**\n * If true, the step will be marked as completed when the secondary button is clicked.\n */\n skippable?: boolean\n\n /**\n * Video url to be shown for components supporting video.\n */\n videoUri?: string\n\n /**\n * Image url to be shown for components supporting image.\n */\n imageUri?: string | null\n\n /**\n * Automatically mark the step as completed when the primary button is clicked. Default is false.\n */\n autoMarkCompleted?: boolean\n\n /**\n * @ignore\n */\n props?: any\n /**\n * Criteria that needs to be met for the step to complete.\n * Completion criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be completed.\n */\n completionCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to start.\n * Start criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be started.\n */\n startCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to be visible.\n * Visibility criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be visible.\n */\n visibilityCriteria?: string\n\n /**\n * Progress if the step is tied to another Frigade Flow through completionCriteria.\n */\n progress?: number\n\n /**\n * Whether the step is dismissible (for instance, tooltips or other non-essential steps).\n */\n dismissible?: boolean\n\n /**\n * Any other additional props defined in the YAML config.\n */\n [x: string | number | symbol]: unknown\n\n /**\n * Marks the step started.\n */\n start: (properties?: PropertyPayload) => Promise<void>\n\n /**\n * Marks the step completed.\n * @param optimistic If true, the step will be marked as completed without waiting for the API and validation of any targeting rules.\n */\n complete: (properties?: PropertyPayload, optimistic?: boolean) => Promise<void>\n\n /**\n * Resets the step (useful for undoing a finished step).\n */\n reset: () => Promise<void>\n\n /**\n * Event handler called when this step's state changes.\n */\n onStateChange: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Removes the given callback from the list of event handlers.\n */\n removeStateChangeHandler: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Reference to this step's parent Flow\n */\n flow: Flow\n}\n\nexport interface FrigadeConfig {\n /**\n * Frigade API key. You can find your API key in the Frigade Dashboard under \"Developer\".\n */\n apiKey?: string\n /**\n * API url to use for all requests. Defaults to https://api.frigade.com\n */\n apiUrl?: string\n\n /**\n * User ID to use for all requests. If not provided, a Guest ID will be generated.\n */\n userId?: string\n\n /**\n * Group ID (organization) to use for all requests.\n */\n groupId?: string\n\n /**\n * Optional user properties to send to the API.\n */\n userProperties?: PropertyPayload\n\n /**\n * Optional group properties to send to the API.\n */\n groupProperties?: PropertyPayload\n\n /**\n * Whether to generate a Guest ID and session if no userId is not provided on initialization.\n * If set to false, Frigade will not initialize until a userId is provided via `frigade.identify()`.\n *\n * Defaults to true.\n */\n generateGuestId?: boolean\n\n /**\n * Whether to sync state with Frigade on URL or focus change. Defaults to true.\n */\n syncOnWindowUpdates?: boolean\n\n /**\n * @ignore Internal use only.\n * If enabled, Frigade will not send any data to the API. A user's state will be reset on page refresh.\n */\n __readOnly?: boolean\n\n /**\n * @ignore Internal use only.\n * Map of Flow ID to Flow State for all flows in the app that should be mocked.\n */\n __flowStateOverrides?: Record<string, StatefulFlow>\n\n /**\n * @ignore Internal use only.\n */\n __instanceId?: string\n}\n\nexport interface StatefulStep {\n id: string\n $state: {\n completed: boolean\n started: boolean\n visible: boolean\n blocked: boolean\n lastActionAt?: Date\n }\n // allow any other properties\n [key: string]: any\n}\n\nexport interface StatefulFlow {\n flowSlug: string\n flowName: string\n flowType: FlowType\n data: {\n steps: StatefulStep[]\n // allow any other properties\n [key: string]: any\n }\n $state: {\n currentStepId: string\n currentStepIndex: number\n completed: boolean\n started: boolean\n skipped: boolean\n visible: boolean\n lastActionAt?: Date\n }\n}\n\nexport enum CollectionType {\n CUSTOM = 'CUSTOM',\n DEFAULT = 'DEFAULT',\n}\n\nexport interface ComputedCollection {\n collectionId: string\n flowId: string\n visible: boolean\n allowedComponents: []\n collectionType: CollectionType\n}\n\nexport interface CollectionMetadata {\n computedOrder: ComputedCollection[]\n}\n\nexport interface FlowStates {\n eligibleFlows: StatefulFlow[]\n ineligibleFlows: string[]\n collections?: CollectionMetadata\n}\n\nexport enum FlowType {\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}\n\nexport type FlowActionType =\n | 'STARTED_STEP'\n | 'COMPLETED_STEP'\n | 'NOT_STARTED_STEP'\n | 'STARTED_FLOW'\n | 'COMPLETED_FLOW'\n | 'SKIPPED_FLOW'\n | 'NOT_STARTED_FLOW'\n\nexport interface FlowStateDTO {\n userId: string\n groupId?: string\n flowSlug?: string\n stepId?: string\n data?: any\n actionType?: FlowActionType\n createdAt?: Date\n context?: FlowStateContext\n}\n\nexport interface FlowStateContext {\n url?: string\n userAgent?: string\n}\n\nexport interface TrackingEvent {\n event: string\n properties?: PropertyPayload\n}\n\nexport interface SessionDTO {\n userId: string\n groupId?: string\n userProperties?: PropertyPayload\n userEvents?: TrackingEvent[]\n groupProperties?: PropertyPayload\n groupEvents?: TrackingEvent[]\n linkGuestId?: string\n}\n"],"mappings":";k9BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,UAAAE,EAAA,eAAAC,EAAA,aAAAC,EAAA,YAAAC,EAAA,gBAAAC,IAAA,eAAAC,GAAAP,ICAO,IAAMQ,EAAiB,SCC9B,IAAAC,EAA6B,gBCuBtB,IAAIC,EAAyD,CAAC,EAE9D,SAASC,EAAkBC,EAAuC,CACvE,MAAO,GAAGA,EAAe,gBAAgBA,EAAe,QAC1D,CCxBO,IAAMC,EAAN,KAAgB,CASrB,YAAYC,EAAuB,CARnC,KAAO,OAAwB,CAC7B,OAAQ,GACR,OAAQ,0BACR,OAAQC,EAAgB,EACxB,aAAc,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,UAAU,CAAC,EACpD,gBAAiB,EACnB,EAGE,IAAMC,EAAiB,OAAO,YAAY,OAAO,QAAQF,CAAM,EAAE,OAAO,CAAC,CAACG,EAAGC,CAAC,IAAMA,GAAK,IAAI,CAAC,EAC1F,CAACJ,EAAO,QAAUA,EAAO,kBAAoB,IAC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AK,eAAe,EAAE,cAAc,IAAIrC,EAAQW,EAAUyB,CAAW,CAAC,CACxE,CAAC,EAGHD,GAAA,MAAAA,EAAWP,EACb,CAE+B,CACjC,EAAC,EAED,QAAQ,IAAIK,CAA2B,EAAE,KAAMK,GAAY,CACzD,KAAK,eAAe,EAAE,YAAY,cAAcA,CAAO,CACzD,CAAC,CACH,GACF,EC5gBO,IAAKC,OACVA,EAAA,OAAS,SACTA,EAAA,UAAY,YAFFA,OAAA,IAKAC,OACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SACTA,EAAA,SAAW,WAHDA,OAAA,IAkVL,IAAKC,OACVA,EAAA,aAAe,eACfA,EAAA,UAAY,YACZA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,QAAU,UACVA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,aAAe,eACfA,EAAA,WAAa,aACbA,EAAA,OAAS,SACTA,EAAA,KAAO,OAXGA,OAAA","names":["src_exports","__export","Flow","FlowStatus","FlowType","Frigade","TriggerType","__toCommonJS","VERSION_NUMBER","import_uuid","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","filteredConfig","_","v","__spreadValues","path","options","__async","getEmptyResponse","gracefulFetch","getHeaders","globalStateKey","getGlobalStateKey","frigadeGlobalState","Flow","Fetchable","config","id","visible","overrideStatefulFlow","_a","_b","_c","statefulFlow","step","index","stepObj","existingStep","key","__spreadProps","__spreadValues","newSteps","properties","__async","thisStep","copy","clone","STARTED_STEP","optimistic","isLastStep","COMPLETED_STEP","NOT_STARTED_STEP","handler","wrapperHandler","flow","previousStep","h","STARTED_FLOW","COMPLETED_FLOW","SKIPPED_FLOW","nextStep","NOT_STARTED_FLOW","currentStep","previousFlow","variables","replaceVariables","str","matches","match","variable","action","data","stepId","date","flowStatesRaw","getContext","callback","prevFlow","cloneFlow","NOT_STARTED_STEP","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","GUEST_KEY","GUEST_PREFIX","GET_CACHE_PREFIX","LOCAL_STORAGE_PREFIX","cloneFlow","flow","Flow","clone","obj","getHeaders","apiKey","VERSION_NUMBER","getLocalStorage","key","isWeb","setLocalStorage","value","clearCache","frigadeGlobalState","key","GET_CACHE_PREFIX","resetAllLocalStorage","isWeb","LOCAL_STORAGE_PREFIX","CallQueue","call","now","item","callQueue","gracefulFetch","url","options","__async","_a","getEmptyResponse","lastCallDataKey","response","error","body","e","generateGuestId","guestId","getLocalStorage","GUEST_KEY","GUEST_PREFIX","uuidv4","setLocalStorage","isWeb","getContext","currentUrl","Rules","rulesData","ruleId","rule","flowId","callback","registeredFlow","flowInRules","item","visibleAPIOverride","otherFlowId","otherId","_a","otherVisible","otherVisited","flowIds","visible","Frigade","Fetchable","apiKey","config","__spreadValues","__async","isWeb","event","e","globalStateKey","getGlobalStateKey","frigadeGlobalState","_a","GUEST_PREFIX","userId","properties","__spreadProps","groupId","sessionDTO","flowId","flow","collectionId","collection","enrichedFlows","item","collections","resetAllLocalStorage","clearCache","handler","lastFlow","cloneFlow","h","that","validator","target","key","value","previousState","newState","Rules","overrideFlowStateRaw","_b","flowStateRaw","getContext","rulesData","allowedComponents","collectionType","visible","currentRule","statefulFlow","Flow","flowIds","flowIdsWithWrappedCallbacks","_0","callback","currentFlow","prevFlow","results","TriggerType","FlowStatus","FlowType"]}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
var et=Object.defineProperty,it=Object.defineProperties;var st=Object.getOwnPropertyDescriptors;var x=Object.getOwnPropertySymbols;var rt=Object.prototype.hasOwnProperty,at=Object.prototype.propertyIsEnumerable;var _=(a,s,t)=>s in a?et(a,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[s]=t,h=(a,s)=>{for(var t in s||(s={}))rt.call(s,t)&&_(a,t,s[t]);if(x)for(var t of x(s))at.call(s,t)&&_(a,t,s[t]);return a},b=(a,s)=>it(a,st(s));var g=(a,s,t)=>new Promise((e,i)=>{var r=l=>{try{n(t.next(l))}catch(c){i(c)}},d=l=>{try{n(t.throw(l))}catch(c){i(c)}},n=l=>l.done?e(l.value):Promise.resolve(l.value).then(r,d);n((t=t.apply(a,s)).next())});var D="0.2.20";import{v4 as K}from"uuid";var f={};function m(a){return`${a.__instanceId}-${a.apiKey}`}var F=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:L(),__instanceId:Math.random().toString(12).substring(4),generateGuestId:!0};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));!s.userId&&s.generateGuestId===!1&&delete this.config.userId,this.config=h(h({},this.config),t)}fetch(s,t){return g(this,null,function*(){return this.config.__readOnly?u():k(this.getAPIUrl(s),h(h({keepalive:!0},t!=null?t:{}),$(this.config.apiKey)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=m(this.config);if(!f[s])throw new Error("Frigade has not yet been initialized");return f[s]}};var y=class extends F{constructor({config:t,id:e}){super(t);this._isVisible=!1;this.lastStepUpdate=new Map;this.id=e,this.init()}get isVisible(){return this._isVisible===!1?!1:this.getGlobalState().collections.isFlowVisible(this.id)}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,r,d;let e=t!=null?t:this.getStatefulFlow();this.rawData=e,this.title=(i=e==null?void 0:e.data)==null?void 0:i.title,this.subtitle=(r=e==null?void 0:e.data)==null?void 0:r.subtitle,this.isCompleted=e.$state.completed,this.isStarted=e.$state.started,this.isSkipped=e.$state.skipped,this._isVisible=e.$state.visible,e.data.steps.forEach((n,l)=>{var o;let c=this.initStepFromStatefulStep(n,l),p=(o=this.steps)==null?void 0:o.get(n.id);p&&Object.keys(c).forEach(P=>{p[P]=c[P]})}),this.steps&&this.steps.size>0&&this.applyVariables((d=this.getGlobalState().variables[this.id])!=null?d:{})}initStepFromStatefulStep(t,e){return b(h({},t),{flow:this,$state:b(h({},t.$state),{lastActionAt:t.$state.lastActionAt?new Date(t.$state.lastActionAt):void 0}),order:e})}init(){let t=this.getStatefulFlow();this.resyncState();let e=new Map;t.data.steps.forEach((i,r)=>{let d=this.initStepFromStatefulStep(i,r);d.start=n=>g(this,null,function*(){let l=this.steps.get(i.id);if(this.getCurrentStep().id===l.id&&l.$state.started)return;let c=S(this.getGlobalState().flowStates[this.id]);c.data.steps[l.order].$state.started=!0,c.data.steps[l.order].$state.lastActionAt=new Date,c.$state.lastActionAt=new Date,c.$state.currentStepId=l.id,c.$state.currentStepIndex=l.order,this.getGlobalState().flowStates[this.id]=c,this.resyncState(),yield this.sendFlowStateToAPI(B,n,l.id)}),d.complete=(n,l=!0)=>g(this,null,function*(){let c=this.steps.get(i.id);if(!(c.$state.completed&&l)){if(l){let p=c.order+1===this.getNumberOfAvailableSteps(),o=S(this.getGlobalState().flowStates[this.id]);o.$state.started=!0,o.data.steps[c.order].$state.completed=!0,o.data.steps[c.order].$state.started=!0,o.data.steps[c.order].$state.lastActionAt=new Date,p||(o.$state.currentStepId=this.getStepByIndex(c.order+1).id,o.$state.currentStepIndex=c.order+1),p&&(o.$state.completed=!0),this.getGlobalState().flowStates[this.id]=o,this.resyncState(),p&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(V,n,c.id)}}),d.reset=()=>g(this,null,function*(){let n=this.steps.get(i.id);if(!n.$state.completed)return;let l=S(this.getGlobalState().flowStates[this.id]);l.data.steps[n.order].$state.started=!1,l.data.steps[n.order].$state.completed=!1,l.data.steps[n.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=l,this.resyncState(),yield this.sendFlowStateToAPI(M,void 0,n.id)}),d.onStateChange=n=>{let l=c=>{if(c.id!==this.id)return;let p=c.steps.get(i.id),o=this.lastStepUpdate.get(n);(p.$state.completed!==(o==null?void 0:o.$state.completed)||p.$state.started!==(o==null?void 0:o.$state.started)||p.$state.visible!==(o==null?void 0:o.$state.visible)||p.$state.blocked!==(o==null?void 0:o.$state.blocked))&&(n(p,o!=null?o:S(p)),this.lastStepUpdate.set(n,S(p)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(n,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},d.removeStateChangeHandler=n=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(n);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(c=>c!==l))},e.set(i.id,d)}),this.steps=e,this.getGlobalState().variables&&this.getGlobalState().variables[this.id]&&Object.keys(this.getGlobalState().variables[this.id]).length>0&&this.applyVariables(this.getGlobalState().variables[this.id])}start(t){return g(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(H,t))})}complete(t){return g(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(N,t))})}skip(t){return g(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(U,t))})}forward(t){return g(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()+1);e?yield e.start(t):yield this.complete(t)})}back(t){return g(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()-1);e&&(yield e.start(t))})}restart(){return g(this,null,function*(){this.optimisticallyMarkFlowNotStarted(),yield this.sendFlowStateToAPI(W)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){var t;return(t=this.steps.get(this.getStatefulFlow().$state.currentStepId))!=null?t:this.steps.get(Array.from(this.steps.keys())[0])}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}onStateChange(t){let e=(i,r)=>{i.id===this.id&&(i.isCompleted!==(r==null?void 0:r.isCompleted)||i.isStarted!==(r==null?void 0:r.isStarted)||i.isSkipped!==(r==null?void 0:r.isSkipped)||i.isVisible!==(r==null?void 0:r.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(r==null?void 0:r.steps))&&t(i,r)};this.getGlobalState().onFlowStateChangeHandlerWrappers.set(t,e),this.getGlobalState().onFlowStateChangeHandlers.push(e)}removeStateChangeHandler(t){let e=this.getGlobalState().onFlowStateChangeHandlerWrappers.get(t);e&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(i=>i!==e))}applyVariables(t){var i,r;let e=d=>{let n=d.match(/\${(.*?)}/g);return n&&n.forEach(l=>{let c=l.replace("${","").replace("}","");t[c]&&(d=d.replace(l,t[c]))}),d};this.title=e((i=this.title)!=null?i:""),this.subtitle=e((r=this.subtitle)!=null?r:""),this.steps.forEach(d=>{Object.keys(d).forEach(n=>{typeof d[n]=="string"&&(d[n]=e(d[n]))})}),this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.completed=!0,t.$state.started=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowStarted(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowNotStarted(){var e;let t=S(this.getGlobalState().flowStates[this.id]);t.$state.completed=!1,t.$state.started=!1,t.$state.visible=!0,t.$state.currentStepIndex=0,t.$state.currentStepId=(e=this.getStepByIndex(0))==null?void 0:e.id,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return g(this,null,function*(){let r=new Date;this.getGlobalState().lastSyncDate=r;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!=null?i:this.getCurrentStep().id,data:e||{},actionType:t,createdAt:r,context:R(this.getGlobalState().currentUrl)})});r<this.getGlobalState().lastSyncDate||(yield this.getGlobalState().refreshStateFromAPI(d))})}optimisticallyMarkFlowSkipped(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.skipped=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}register(t){this.getGlobalState().collections.register(this.id,i=>{let r=this.getGlobalState().previousFlows.get(this.id);(r==null?void 0:r._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(d=>{d(this,r),this.getGlobalState().previousFlows.set(this.id,C(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var M="NOT_STARTED_STEP",N="COMPLETED_FLOW",U="SKIPPED_FLOW",H="STARTED_FLOW",W="NOT_STARTED_FLOW",V="COMPLETED_STEP",B="STARTED_STEP",j="frigade-guest-key",I="guest_",ot="get-cache-",T="fr-js-";function C(a){return new y({config:a.config,id:a.id})}function S(a){return JSON.parse(JSON.stringify(a))}function $(a){return{headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json","X-Frigade-SDK-Version":D,"X-Frigade-SDK-Platform":"Javascript"}}}function nt(a){return w()?window.localStorage.getItem(`${T}${a}`):null}function lt(a,s){w()&&window.localStorage.setItem(`${T}${a}`,s)}function q(){Object.keys(f).forEach(a=>{a.startsWith(ot)&&delete f[a]})}function z(){w()&&Object.keys(window.localStorage).forEach(a=>{a.startsWith(T)&&window.localStorage.removeItem(a)})}var E=class{constructor(){this.queue=[];this.ttlInMS=100;this.cacheSize=5}push(s){let t=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:t.getTime()})}hasIdenticalCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.some(e=>e.call===s)}},J=new E;function k(a,s){return g(this,null,function*(){var e;if(typeof globalThis.fetch!="function")return u("- Attempted to call fetch() in an environment that doesn't support it.");if(w()&&s&&s.body&&s.method==="POST"){let i=`${a}${JSON.stringify((e=s.body)!=null?e:{})}`;if(J.hasIdenticalCall(i))return u();J.push(i)}let t;try{t=fetch(a,s),t=yield t}catch(i){return u(i)}if(!t)return u("Received an empty response");if(t.status>=400)return u(t.statusText);try{if(t.status===204)return u();let i;try{i=yield t.json()}catch(r){return u()}return i.error?u(i.error):i}catch(i){return u(i)}})}function u(a){return a&&console.log("Call to Frigade failed",a),{json:()=>({})}}function L(){if(w()){let a=nt(j);return a||(a=`${I}${K()}`,lt(j,a)),a}else return`${I}${K()}`}function w(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function R(a){return w()?{url:a,userAgent:navigator.userAgent}:{}}var v=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.rules=new Map;this.flowsInRules=new Set;this.ingestRulesData(s)}getRule(s){return this.rules.get(s)}getRules(){return this.rules}ingestRulesData(s){this.rules=s;for(let[,t]of this.rules)for(let{flowId:e}of t.flows)this.flowsInRules.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processRules()),this.fireCallbacks()}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.flowsInRules.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)}processRules(){for(let[,s]of this.rules)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;if(s.flows.map(({flowId:n})=>n).filter(n=>n!==t).some(n=>{var p;let{visible:l,visited:c}=(p=this.registry.get(n))!=null?p:{};return l&&c})){this.visit(t,!1);continue}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.processRules(),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.processRules(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processRules(),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 A=class extends F{constructor(t,e){super(h({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>g(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),w()&&this.config.syncOnWindowUpdates!==!1&&(document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.navigation&&window.navigation.addEventListener("navigate",i=>g(this,null,function*(){this.getGlobalState().currentUrl!==i.destination.url&&(this.getGlobalState().currentUrl=i.destination.url,this.refreshStateFromAPI())})))}getConfig(){return this.config}destroy(){if(w()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=m(this.config);f[t]&&(f[t].onFlowStateChangeHandlers=[])}}init(t){return g(this,null,function*(){if(this.updateConfig(h(h({},this.config),t)),!(!this.config.userId&&this.config.generateGuestId===!1))return this.initPromise=(()=>g(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(I)||(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 g(this,null,function*(){yield this.updateConfig(b(h({},this.config),{userId:t})),yield this.initIfNeeded(),yield this.session({userId:this.config.userId,userProperties:e}),yield this.resync()})}group(t,e){return g(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(b(h({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties:e}),yield this.resync()})}track(t,e){return g(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 g(this,null,function*(){yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)})})}isReady(){return!!(this.config.__instanceId&&this.config.apiKey&&this.initPromise)}getFlow(t){return g(this,null,function*(){return yield this.initIfNeeded(),this.flows.find(e=>e.id==t)})}getFlows(){return g(this,null,function*(){return yield this.initIfNeeded(),this.flows})}getCollection(t){return g(this,null,function*(){yield this.initIfNeeded();let e=this.getGlobalState().collections.getRule(t);if(e==null)return;let i=yield Promise.all(e.flows.map(r=>g(this,null,function*(){return b(h({},r),{flow:yield this.getFlow(r.flowId)})})));return e.flows=i,e})}getCollections(){return g(this,null,function*(){yield this.initIfNeeded();let t=this.getGlobalState().collections.getRules();if(t!=null)return t})}reload(t){return g(this,null,function*(){z(),q(),t&&(yield this.updateConfig(t),this.mockFlowStates(m(this.config))),this.initPromise=null,yield this.init(this.config),this.flows.forEach(e=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(i=>{let r=this.getGlobalState().previousFlows.get(e.id);i(e,r),this.getGlobalState().previousFlows.set(e.id,C(e))})})})}resync(){return g(this,null,function*(){yield this.refreshStateFromAPI()})}onStateChange(t){return g(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return g(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return g(this,null,function*(){return this.initPromise?this.initPromise:this.init(this.config)})}refreshStateFromAPI(){return g(this,null,function*(){let t=m(this.config);if(!f[t]){let e=this,i={set:function(r,d,n){if(r[d]){let l=r[d],c=n;JSON.stringify(l)!==JSON.stringify(c)&&e.triggerEventHandlers(c,l)}return r[d]=n,!0}};if(f[t]={refreshStateFromAPI:()=>g(this,null,function*(){}),collections:new v(new Map),flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config,currentUrl:w()?window.location.href:""},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(t);return}f[t].refreshStateFromAPI=r=>g(this,null,function*(){var l,c;if(this.config.__readOnly)return;let d=r||(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().currentUrl)})})),n=new Map;(c=(l=d.collections)==null?void 0:l.computedOrder)==null||c.forEach(({allowedComponents:p,collectionId:o,collectionType:P,flowId:Z,visible:tt})=>{var G;let O=(G=n.get(o))!=null?G:{allowedComponents:p,collectionType:P,flows:[]};O.flows.push({flowId:Z,visible:tt}),n.set(o,O)}),f[t].collections.ingestRulesData(n),d&&d.eligibleFlows?(d.eligibleFlows.forEach(p=>{f[t].flowStates[p.flowSlug]=p,this.flows.find(o=>o.id==p.flowSlug)?this.flows.forEach(o=>{o.id==p.flowSlug&&o.resyncState(p)}):this.flows.push(new y({config:this.config,id:p.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield f[t].refreshStateFromAPI()})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{f[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 y({config:this.config,id:e}))})}updateConfig(t){return g(this,null,function*(){this.config=h(h({},this.config),t),f[m(this.config)]&&(this.getGlobalState().config=this.config)})}triggerEventHandlers(t,e){return g(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(r=>{let d=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),r(i,d),this.getGlobalState().previousFlows.set(i.id,C(i))})})})}batchRegister(t){return g(this,null,function*(){let e=t.map(d=>g(this,[d],function*([i,r]){let n=yield this.getFlow(i);return[i,c=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==c&&this.getGlobalState().onFlowStateChangeHandlers.forEach(o=>{o(n,p),this.getGlobalState().previousFlows.set(i,C(n))}),r==null||r(c)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};var X=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(X||{}),Y=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(Y||{});var Q=(o=>(o.ANNOUNCEMENT="ANNOUNCEMENT",o.CHECKLIST="CHECKLIST",o.FORM="FORM",o.TOUR="TOUR",o.SUPPORT="SUPPORT",o.CUSTOM="CUSTOM",o.BANNER="BANNER",o.EMBEDDED_TIP="EMBEDDED_TIP",o.NPS_SURVEY="NPS_SURVEY",o.SURVEY="SURVEY",o.CARD="CARD",o))(Q||{});export{y as Flow,Y as FlowStatus,Q as FlowType,A as Frigade,X as TriggerType};
|
|
2
|
+
var et=Object.defineProperty,it=Object.defineProperties;var st=Object.getOwnPropertyDescriptors;var x=Object.getOwnPropertySymbols;var rt=Object.prototype.hasOwnProperty,at=Object.prototype.propertyIsEnumerable;var _=(a,s,t)=>s in a?et(a,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[s]=t,h=(a,s)=>{for(var t in s||(s={}))rt.call(s,t)&&_(a,t,s[t]);if(x)for(var t of x(s))at.call(s,t)&&_(a,t,s[t]);return a},b=(a,s)=>it(a,st(s));var g=(a,s,t)=>new Promise((e,i)=>{var r=l=>{try{n(t.next(l))}catch(c){i(c)}},d=l=>{try{n(t.throw(l))}catch(c){i(c)}},n=l=>l.done?e(l.value):Promise.resolve(l.value).then(r,d);n((t=t.apply(a,s)).next())});var D="0.2.20";import{v4 as K}from"uuid";var f={};function m(a){return`${a.__instanceId}-${a.apiKey}`}var F=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:L(),__instanceId:Math.random().toString(12).substring(4),generateGuestId:!0};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));!s.userId&&s.generateGuestId===!1&&delete this.config.userId,this.config=h(h({},this.config),t)}fetch(s,t){return g(this,null,function*(){return this.config.__readOnly?u():k(this.getAPIUrl(s),h(h({keepalive:!0},t!=null?t:{}),$(this.config.apiKey)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=m(this.config);if(!f[s])throw new Error("Frigade has not yet been initialized");return f[s]}};var y=class extends F{constructor({config:t,id:e}){super(t);this._isVisible=!1;this.lastStepUpdate=new Map;this.id=e,this.init()}get isVisible(){return this._isVisible===!1?!1:this.getGlobalState().collections.isFlowVisible(this.id)}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,r,d;let e=t!=null?t:this.getStatefulFlow();this.rawData=e,this.title=(i=e==null?void 0:e.data)==null?void 0:i.title,this.subtitle=(r=e==null?void 0:e.data)==null?void 0:r.subtitle,this.isCompleted=e.$state.completed,this.isStarted=e.$state.started,this.isSkipped=e.$state.skipped,this._isVisible=e.$state.visible,e.data.steps.forEach((n,l)=>{var o;let c=this.initStepFromStatefulStep(n,l),p=(o=this.steps)==null?void 0:o.get(n.id);p&&Object.keys(c).forEach(P=>{p[P]=c[P]})}),this.steps&&this.steps.size>0&&this.applyVariables((d=this.getGlobalState().variables[this.id])!=null?d:{})}initStepFromStatefulStep(t,e){return b(h({},t),{flow:this,$state:b(h({},t.$state),{lastActionAt:t.$state.lastActionAt?new Date(t.$state.lastActionAt):void 0}),order:e})}init(){let t=this.getStatefulFlow();this.resyncState();let e=new Map;t.data.steps.forEach((i,r)=>{let d=this.initStepFromStatefulStep(i,r);d.start=n=>g(this,null,function*(){let l=this.steps.get(i.id);if(this.getCurrentStep().id===l.id&&l.$state.started)return;let c=S(this.getGlobalState().flowStates[this.id]);c.data.steps[l.order].$state.started=!0,c.data.steps[l.order].$state.lastActionAt=new Date,c.$state.lastActionAt=new Date,c.$state.currentStepId=l.id,c.$state.currentStepIndex=l.order,this.getGlobalState().flowStates[this.id]=c,this.resyncState(),yield this.sendFlowStateToAPI(B,n,l.id)}),d.complete=(n,l=!0)=>g(this,null,function*(){let c=this.steps.get(i.id);if(!(c.$state.completed&&l)){if(l){let p=c.order+1===this.getNumberOfAvailableSteps(),o=S(this.getGlobalState().flowStates[this.id]);o.$state.started=!0,o.data.steps[c.order].$state.completed=!0,o.data.steps[c.order].$state.started=!0,o.data.steps[c.order].$state.lastActionAt=new Date,p||(o.$state.currentStepId=this.getStepByIndex(c.order+1).id,o.$state.currentStepIndex=c.order+1),p&&(o.$state.completed=!0),this.getGlobalState().flowStates[this.id]=o,this.resyncState(),p&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(V,n,c.id)}}),d.reset=()=>g(this,null,function*(){let n=this.steps.get(i.id);if(!n.$state.completed)return;let l=S(this.getGlobalState().flowStates[this.id]);l.data.steps[n.order].$state.started=!1,l.data.steps[n.order].$state.completed=!1,l.data.steps[n.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=l,this.resyncState(),yield this.sendFlowStateToAPI(M,void 0,n.id)}),d.onStateChange=n=>{let l=c=>{if(c.id!==this.id)return;let p=c.steps.get(i.id),o=this.lastStepUpdate.get(n);(p.$state.completed!==(o==null?void 0:o.$state.completed)||p.$state.started!==(o==null?void 0:o.$state.started)||p.$state.visible!==(o==null?void 0:o.$state.visible)||p.$state.blocked!==(o==null?void 0:o.$state.blocked))&&(n(p,o!=null?o:S(p)),this.lastStepUpdate.set(n,S(p)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(n,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},d.removeStateChangeHandler=n=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(n);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(c=>c!==l))},e.set(i.id,d)}),this.steps=e,this.getGlobalState().variables&&this.getGlobalState().variables[this.id]&&Object.keys(this.getGlobalState().variables[this.id]).length>0&&this.applyVariables(this.getGlobalState().variables[this.id])}start(t){return g(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(H,t))})}complete(t){return g(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(N,t))})}skip(t){return g(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(U,t))})}forward(t){return g(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()+1);e?yield e.start(t):yield this.complete(t)})}back(t){return g(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()-1);e&&(yield e.start(t))})}restart(){return g(this,null,function*(){this.optimisticallyMarkFlowNotStarted(),yield this.sendFlowStateToAPI(W)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){var t;return(t=this.steps.get(this.getStatefulFlow().$state.currentStepId))!=null?t:this.steps.get(Array.from(this.steps.keys())[0])}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}onStateChange(t){let e=(i,r)=>{i.id===this.id&&(i.isCompleted!==(r==null?void 0:r.isCompleted)||i.isStarted!==(r==null?void 0:r.isStarted)||i.isSkipped!==(r==null?void 0:r.isSkipped)||i.isVisible!==(r==null?void 0:r.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(r==null?void 0:r.steps))&&t(i,r)};this.getGlobalState().onFlowStateChangeHandlerWrappers.set(t,e),this.getGlobalState().onFlowStateChangeHandlers.push(e)}removeStateChangeHandler(t){let e=this.getGlobalState().onFlowStateChangeHandlerWrappers.get(t);e&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(i=>i!==e))}applyVariables(t){var i,r;let e=d=>{let n=d.match(/\${(.*?)}/g);return n&&n.forEach(l=>{let c=l.replace("${","").replace("}","");t[c]&&(d=d.replace(l,t[c]))}),d};this.title=e((i=this.title)!=null?i:""),this.subtitle=e((r=this.subtitle)!=null?r:""),this.steps.forEach(d=>{Object.keys(d).forEach(n=>{typeof d[n]=="string"&&(d[n]=e(d[n]))})}),this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.completed=!0,t.$state.started=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowStarted(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowNotStarted(){var e;let t=S(this.getGlobalState().flowStates[this.id]);t.$state.completed=!1,t.$state.started=!1,t.$state.visible=!0,t.$state.currentStepIndex=0,t.$state.currentStepId=(e=this.getStepByIndex(0))==null?void 0:e.id,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return g(this,null,function*(){let r=new Date;this.getGlobalState().lastSyncDate=r;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!=null?i:this.getCurrentStep().id,data:e||{},actionType:t,createdAt:r,context:R(this.getGlobalState().currentUrl)})});r<this.getGlobalState().lastSyncDate||(yield this.getGlobalState().refreshStateFromAPI(d))})}optimisticallyMarkFlowSkipped(){let t=S(this.getGlobalState().flowStates[this.id]);t.$state.skipped=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}register(t){this.getGlobalState().collections.register(this.id,i=>{let r=this.getGlobalState().previousFlows.get(this.id);(r==null?void 0:r._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(d=>{d(this,r),this.getGlobalState().previousFlows.set(this.id,C(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var M="NOT_STARTED_STEP",N="COMPLETED_FLOW",U="SKIPPED_FLOW",H="STARTED_FLOW",W="NOT_STARTED_FLOW",V="COMPLETED_STEP",B="STARTED_STEP",j="frigade-guest-key",I="guest_",ot="get-cache-",T="fr-js-";function C(a){return new y({config:a.config,id:a.id})}function S(a){return JSON.parse(JSON.stringify(a))}function $(a){return{headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json","X-Frigade-SDK-Version":D,"X-Frigade-SDK-Platform":"Javascript"}}}function nt(a){return w()?window.localStorage.getItem(`${T}${a}`):null}function lt(a,s){w()&&window.localStorage.setItem(`${T}${a}`,s)}function q(){Object.keys(f).forEach(a=>{a.startsWith(ot)&&delete f[a]})}function z(){w()&&Object.keys(window.localStorage).forEach(a=>{a.startsWith(T)&&window.localStorage.removeItem(a)})}var E=class{constructor(){this.queue=[];this.ttlInMS=100;this.cacheSize=5}push(s){let t=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:t.getTime()})}hasIdenticalCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.some(e=>e.call===s)}},J=new E;function k(a,s){return g(this,null,function*(){var e;if(typeof globalThis.fetch!="function")return u("- Attempted to call fetch() in an environment that doesn't support it.");if(w()&&s&&s.body&&s.method==="POST"){let i=`${a}${JSON.stringify((e=s.body)!=null?e:{})}`;if(J.hasIdenticalCall(i))return u();J.push(i)}let t;try{t=fetch(a,s),t=yield t}catch(i){return u(i)}if(!t)return u("Received an empty response");if(t.status>=400)return u(t.statusText);try{if(t.status===204)return u();let i;try{i=yield t.json()}catch(r){return u()}return i.error?u(i.error):i}catch(i){return u(i)}})}function u(a){return a&&console.log("Call to Frigade failed",a),{json:()=>({})}}function L(){if(w()){let a=nt(j);return a||(a=`${I}${K()}`,lt(j,a)),a}else return`${I}${K()}`}function w(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function R(a){return w()?{url:a,userAgent:navigator.userAgent}:{}}var v=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.rules=new Map;this.flowsInRules=new Set;this.ingestRulesData(s)}getRule(s){return this.rules.get(s)}getRules(){return this.rules}ingestRulesData(s){this.rules=s;for(let[,t]of this.rules)for(let{flowId:e}of t.flows)this.flowsInRules.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processRules()),this.fireCallbacks()}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.flowsInRules.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)}processRules(){for(let[,s]of this.rules)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;if(s.flows.map(({flowId:n})=>n).filter(n=>n!==t).some(n=>{var p;let{visible:l,visited:c}=(p=this.registry.get(n))!=null?p:{};return l&&c})){this.visit(t,!1);continue}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.processRules(),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.processRules(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processRules(),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 A=class extends F{constructor(t,e){super(h({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>g(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),w()&&this.config.syncOnWindowUpdates!==!1&&(document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.navigation&&window.navigation.addEventListener("navigate",i=>g(this,null,function*(){if(this.getGlobalState().currentUrl!==i.destination.url)try{this.getGlobalState().currentUrl=i.destination.url,this.refreshStateFromAPI()}catch(r){}})))}getConfig(){return this.config}destroy(){if(w()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=m(this.config);f[t]&&(f[t].onFlowStateChangeHandlers=[])}}init(t){return g(this,null,function*(){if(this.updateConfig(h(h({},this.config),t)),!(!this.config.userId&&this.config.generateGuestId===!1))return this.initPromise=(()=>g(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(I)||(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 g(this,null,function*(){yield this.updateConfig(b(h({},this.config),{userId:t})),yield this.initIfNeeded(),yield this.session({userId:this.config.userId,userProperties:e}),yield this.resync()})}group(t,e){return g(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(b(h({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties:e}),yield this.resync()})}track(t,e){return g(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 g(this,null,function*(){yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)})})}isReady(){return!!(this.config.__instanceId&&this.config.apiKey&&this.initPromise)}getFlow(t){return g(this,null,function*(){return yield this.initIfNeeded(),this.flows.find(e=>e.id==t)})}getFlows(){return g(this,null,function*(){return yield this.initIfNeeded(),this.flows})}getCollection(t){return g(this,null,function*(){yield this.initIfNeeded();let e=this.getGlobalState().collections.getRule(t);if(e==null)return;let i=yield Promise.all(e.flows.map(r=>g(this,null,function*(){return b(h({},r),{flow:yield this.getFlow(r.flowId)})})));return e.flows=i,e})}getCollections(){return g(this,null,function*(){yield this.initIfNeeded();let t=this.getGlobalState().collections.getRules();if(t!=null)return t})}reload(t){return g(this,null,function*(){z(),q(),t&&(yield this.updateConfig(t),this.mockFlowStates(m(this.config))),this.initPromise=null,yield this.init(this.config),this.flows.forEach(e=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(i=>{let r=this.getGlobalState().previousFlows.get(e.id);i(e,r),this.getGlobalState().previousFlows.set(e.id,C(e))})})})}resync(){return g(this,null,function*(){yield this.refreshStateFromAPI()})}onStateChange(t){return g(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return g(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return g(this,null,function*(){return this.initPromise?this.initPromise:this.init(this.config)})}refreshStateFromAPI(){return g(this,null,function*(){let t=m(this.config);if(!f[t]){let e=this,i={set:function(r,d,n){if(r[d]){let l=r[d],c=n;JSON.stringify(l)!==JSON.stringify(c)&&e.triggerEventHandlers(c,l)}return r[d]=n,!0}};if(f[t]={refreshStateFromAPI:()=>g(this,null,function*(){}),collections:new v(new Map),flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config,currentUrl:w()?window.location.href:""},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(t);return}f[t].refreshStateFromAPI=r=>g(this,null,function*(){var l,c;if(this.config.__readOnly)return;let d=r||(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().currentUrl)})})),n=new Map;(c=(l=d.collections)==null?void 0:l.computedOrder)==null||c.forEach(({allowedComponents:p,collectionId:o,collectionType:P,flowId:Z,visible:tt})=>{var G;let O=(G=n.get(o))!=null?G:{allowedComponents:p,collectionType:P,flows:[]};O.flows.push({flowId:Z,visible:tt}),n.set(o,O)}),f[t].collections.ingestRulesData(n),d&&d.eligibleFlows?(d.eligibleFlows.forEach(p=>{f[t].flowStates[p.flowSlug]=p,this.flows.find(o=>o.id==p.flowSlug)?this.flows.forEach(o=>{o.id==p.flowSlug&&o.resyncState(p)}):this.flows.push(new y({config:this.config,id:p.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield f[t].refreshStateFromAPI()})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{f[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 y({config:this.config,id:e}))})}updateConfig(t){return g(this,null,function*(){this.config=h(h({},this.config),t),f[m(this.config)]&&(this.getGlobalState().config=this.config)})}triggerEventHandlers(t,e){return g(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(r=>{let d=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),r(i,d),this.getGlobalState().previousFlows.set(i.id,C(i))})})})}batchRegister(t){return g(this,null,function*(){let e=t.map(d=>g(this,[d],function*([i,r]){let n=yield this.getFlow(i);return[i,c=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==c&&this.getGlobalState().onFlowStateChangeHandlers.forEach(o=>{o(n,p),this.getGlobalState().previousFlows.set(i,C(n))}),r==null||r(c)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};var X=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(X||{}),Y=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(Y||{});var Q=(o=>(o.ANNOUNCEMENT="ANNOUNCEMENT",o.CHECKLIST="CHECKLIST",o.FORM="FORM",o.TOUR="TOUR",o.SUPPORT="SUPPORT",o.CUSTOM="CUSTOM",o.BANNER="BANNER",o.EMBEDDED_TIP="EMBEDDED_TIP",o.NPS_SURVEY="NPS_SURVEY",o.SURVEY="SURVEY",o.CARD="CARD",o))(Q||{});export{y as Flow,Y as FlowStatus,Q as FlowType,A as Frigade,X as TriggerType};
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/shared/fetchable.ts","../src/core/flow.ts","../src/core/rules.ts","../src/core/frigade.ts","../src/core/types.ts"],"sourcesContent":["export const VERSION_NUMBER = '0.2.20'\n","import { VERSION_NUMBER } from '../core/version'\nimport { v4 as uuidv4 } from 'uuid'\nimport { Flow } from '../core/flow'\nimport { frigadeGlobalState } from './state'\nimport { FlowStateContext } from '../core/types'\n\nexport const NOT_STARTED_STEP = 'NOT_STARTED_STEP'\nexport const COMPLETED_FLOW = 'COMPLETED_FLOW'\nexport const SKIPPED_FLOW = 'SKIPPED_FLOW'\nexport const STARTED_FLOW = 'STARTED_FLOW'\nexport const NOT_STARTED_FLOW = 'NOT_STARTED_FLOW'\nexport const COMPLETED_STEP = 'COMPLETED_STEP'\nexport const STARTED_STEP = 'STARTED_STEP'\nconst GUEST_KEY = 'frigade-guest-key'\nexport const GUEST_PREFIX = 'guest_'\nconst GET_CACHE_PREFIX = 'get-cache-'\nconst LOCAL_STORAGE_PREFIX = 'fr-js-'\n\nexport function cloneFlow(flow: Flow): Flow {\n const newFlow = new Flow({\n config: flow.config,\n id: flow.id,\n })\n return newFlow\n}\n\nexport function clone<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj))\n}\n\nexport function getHeaders(apiKey: string) {\n return {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Frigade-SDK-Version': VERSION_NUMBER,\n 'X-Frigade-SDK-Platform': 'Javascript',\n },\n }\n}\n\nfunction getLocalStorage(key: string) {\n if (isWeb()) {\n return window.localStorage.getItem(`${LOCAL_STORAGE_PREFIX}${key}`)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (isWeb()) {\n window.localStorage.setItem(`${LOCAL_STORAGE_PREFIX}${key}`, value)\n }\n}\n\nfunction setGlobalState(key: string, value: any) {\n frigadeGlobalState[key] = value\n}\n\nfunction getGlobalState(key: string): any {\n return frigadeGlobalState[key]\n}\n\nexport function clearCache() {\n Object.keys(frigadeGlobalState).forEach((key) => {\n if (key.startsWith(GET_CACHE_PREFIX)) {\n delete frigadeGlobalState[key]\n }\n })\n}\n\nexport function resetAllLocalStorage() {\n if (isWeb()) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith(LOCAL_STORAGE_PREFIX)) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nclass CallQueue {\n private queue: {\n call: string\n time: number\n }[] = []\n private readonly ttlInMS = 100\n private readonly cacheSize = 5\n\n public push(call: string) {\n const now = new Date()\n if (this.queue.length >= this.cacheSize) {\n this.queue.shift()\n }\n this.queue.push({\n call: call,\n time: now.getTime(),\n })\n }\n\n public hasIdenticalCall(call: string) {\n const now = new Date()\n this.queue = this.queue.filter((item) => now.getTime() - item.time < this.ttlInMS)\n return this.queue.some((item) => item.call === call)\n }\n}\n\nconst callQueue = new CallQueue()\n\nexport async function gracefulFetch(url: string, options: any) {\n if (typeof globalThis.fetch !== 'function') {\n return getEmptyResponse(\n \"- Attempted to call fetch() in an environment that doesn't support it.\"\n )\n }\n\n if (isWeb() && options && options.body && options.method === 'POST') {\n const lastCallDataKey = `${url}${JSON.stringify(options.body ?? {})}`\n if (callQueue.hasIdenticalCall(lastCallDataKey)) {\n return getEmptyResponse()\n }\n callQueue.push(lastCallDataKey)\n }\n\n let response\n try {\n response = fetch(url, options)\n response = await response\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse('Received an empty response')\n }\n\n if (response.status >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n try {\n if (response.status === 204) {\n return getEmptyResponse()\n }\n\n let body\n try {\n body = await response.json()\n } catch (e) {\n return getEmptyResponse()\n }\n\n if (body.error) {\n return getEmptyResponse(body.error)\n }\n return body\n } catch (e) {\n return getEmptyResponse(e)\n }\n}\n\nexport function getEmptyResponse(error?: any) {\n if (error) {\n console.log('Call to Frigade failed', error)\n }\n\n // Create empty response that contains the .json method and returns an empty object\n return {\n json: () => ({}),\n }\n}\n\nexport function generateGuestId() {\n if (isWeb()) {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n setLocalStorage(GUEST_KEY, guestId)\n }\n return guestId\n } else {\n return `${GUEST_PREFIX}${uuidv4()}`\n }\n}\n\nexport function fetcher(apiKey: string, path: string, options?: Record<any, any>) {\n return gracefulFetch(`//api.frigade.com/v1/public${path}`, {\n ...(options ?? {}),\n ...getHeaders(apiKey),\n })\n}\n\nexport function isWeb() {\n return (\n typeof window !== 'undefined' &&\n typeof window.document !== 'undefined' &&\n typeof window.localStorage !== 'undefined'\n )\n}\n\nexport function getContext(currentUrl: string): FlowStateContext {\n if (!isWeb()) {\n return {}\n }\n\n return {\n url: currentUrl,\n userAgent: navigator.userAgent,\n }\n}\n","import { FlowStates, FlowStep, FrigadeConfig, StatefulFlow } from '../core/types'\nimport { Flow } from '../core/flow'\nimport type { Rules } from '../core/rules'\n\nexport interface FrigadeGlobalState {\n refreshStateFromAPI: (overrideFlowStatesRaw?: FlowStates) => Promise<void>\n flowStates: Record<string, StatefulFlow>\n collections: Rules\n onFlowStateChangeHandlerWrappers: Map<\n (flow: Flow, previousFlow: Flow) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onStepStateChangeHandlerWrappers: Map<\n (step: FlowStep, previousStep: FlowStep) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onFlowStateChangeHandlers: ((flow: Flow, previousFlow: Flow) => void)[]\n previousFlows: Map<string, Flow>\n variables: Record<string, Record<string, any>>\n lastSyncDate?: Date\n config: FrigadeConfig\n currentUrl: string\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}`\n}\n","import { generateGuestId, getEmptyResponse, getHeaders, gracefulFetch } from './utils'\nimport { FrigadeConfig } from '../core/types'\nimport { frigadeGlobalState, FrigadeGlobalState, getGlobalStateKey } from './state'\n\nexport class Fetchable {\n public config: FrigadeConfig = {\n apiKey: '',\n apiUrl: 'https://api.frigade.com',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(12).substring(4),\n generateGuestId: true,\n }\n\n constructor(config: FrigadeConfig) {\n const filteredConfig = Object.fromEntries(Object.entries(config).filter(([_, v]) => v != null))\n if (!config.userId && config.generateGuestId === false) {\n delete this.config.userId\n }\n this.config = {\n ...this.config,\n ...filteredConfig,\n }\n }\n\n /**\n * @ignore\n */\n public async fetch(path: string, options?: Record<any, any>) {\n if (this.config.__readOnly) {\n return getEmptyResponse()\n }\n\n return gracefulFetch(this.getAPIUrl(path), {\n keepalive: true,\n ...(options ?? {}),\n ...getHeaders(this.config.apiKey),\n })\n }\n\n private getAPIUrl(path: string) {\n return `${this.config.apiUrl.replace(/\\/$/, '')}/${path.replace(/^\\//, '')}`\n }\n\n /**\n * @ignore\n */\n protected getGlobalState(): FrigadeGlobalState {\n const globalStateKey = getGlobalStateKey(this.config)\n if (!frigadeGlobalState[globalStateKey]) {\n throw new Error('Frigade has not yet been initialized')\n }\n return frigadeGlobalState[globalStateKey]\n }\n}\n","import {\n FlowActionType,\n FlowStateDTO,\n FlowStates,\n FlowStep,\n FrigadeConfig,\n PropertyPayload,\n StatefulFlow,\n StatefulStep,\n} from './types'\nimport {\n clone,\n cloneFlow,\n COMPLETED_FLOW,\n COMPLETED_STEP,\n getContext,\n NOT_STARTED_FLOW,\n NOT_STARTED_STEP,\n SKIPPED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { Fetchable } from '../shared/fetchable'\nimport { RulesRegistryCallback } from './rules'\n\nexport class Flow extends Fetchable {\n /**\n * The Flow's ID.\n */\n public id: string\n /**\n * The Flow's component ID.\n */\n public componentId: string\n /**\n * Ordered map of the Steps in the Flow.\n * See [Flow Step Definition](https://docs.frigade.com/v2/sdk/js/step) for more information.\n */\n public steps: Map<string, FlowStep>\n /**\n * The user-facing title of the Flow, if defined at the top level of the YAML config.\n */\n public title?: string\n /**\n * The user-facing description of the Flow, if defined at the top level of the YAML config.\n */\n public subtitle?: string\n /**\n * The metadata of the Flow.\n * @ignore\n */\n public rawData: StatefulFlow\n /**\n * Whether the Flow is completed or not.\n */\n public isCompleted: boolean\n /**\n * Whether the Flow is started or not.\n */\n public isStarted: boolean\n /**\n * Whether the Flow has been skipped or not.\n */\n public isSkipped: boolean\n /**\n * @ignore\n */\n private _isVisible: boolean = false\n /**\n * Whether the Flow is visible to the user based on the current user/group's state.\n */\n get isVisible() {\n if (this._isVisible === false) {\n return false\n }\n\n return this.getGlobalState().collections.isFlowVisible(this.id)\n }\n set isVisible(visible: boolean) {\n this._isVisible = visible\n }\n\n /**\n * @ignore\n */\n private lastStepUpdate: Map<(step: FlowStep, previousStep: FlowStep) => void, FlowStep> =\n new Map()\n\n constructor({ config, id }: { config: FrigadeConfig; id: string }) {\n super(config)\n this.id = id\n this.init()\n }\n\n /**\n * Reload the Flow data from the server\n */\n reload() {\n this.init()\n }\n\n /**\n * @ignore\n */\n resyncState(overrideStatefulFlow?: StatefulFlow) {\n const statefulFlow = overrideStatefulFlow ?? this.getStatefulFlow()\n\n this.rawData = statefulFlow\n this.title = statefulFlow?.data?.title\n this.subtitle = statefulFlow?.data?.subtitle\n\n this.isCompleted = statefulFlow.$state.completed\n this.isStarted = statefulFlow.$state.started\n this.isSkipped = statefulFlow.$state.skipped\n this._isVisible = statefulFlow.$state.visible\n\n statefulFlow.data.steps.forEach((step, index) => {\n const stepObj = this.initStepFromStatefulStep(step, index)\n\n const existingStep = this.steps?.get(step.id)\n if (existingStep) {\n Object.keys(stepObj).forEach((key) => {\n existingStep[key] = stepObj[key]\n })\n }\n })\n\n if (this.steps && this.steps.size > 0) {\n this.applyVariables(this.getGlobalState().variables[this.id] ?? {})\n }\n }\n\n /**\n * @ignore\n */\n private initStepFromStatefulStep(step: StatefulStep, index: number) {\n return {\n ...step,\n flow: this,\n $state: {\n ...step.$state,\n lastActionAt: step.$state.lastActionAt ? new Date(step.$state.lastActionAt) : undefined,\n },\n order: index,\n } as Partial<FlowStep>\n }\n\n /**\n * @ignore\n */\n private init() {\n const statefulFlow = this.getStatefulFlow()\n\n this.resyncState()\n\n const newSteps = new Map<string, FlowStep>()\n\n statefulFlow.data.steps.forEach((step, index) => {\n const stepObj = this.initStepFromStatefulStep(step, index)\n\n stepObj.start = async (properties?: PropertyPayload) => {\n const thisStep = this.steps.get(step.id)\n\n if (this.getCurrentStep().id === thisStep.id && thisStep.$state.started) {\n return\n }\n\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.data.steps[thisStep.order].$state.started = true\n copy.data.steps[thisStep.order].$state.lastActionAt = new Date()\n copy.$state.lastActionAt = new Date()\n copy.$state.currentStepId = thisStep.id\n copy.$state.currentStepIndex = thisStep.order\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n await this.sendFlowStateToAPI(STARTED_STEP, properties, thisStep.id)\n }\n\n stepObj.complete = async (properties?: PropertyPayload, optimistic: boolean = true) => {\n const thisStep = this.steps.get(step.id)\n\n if (thisStep.$state.completed && optimistic) {\n return\n }\n\n if (optimistic) {\n const isLastStep = thisStep.order + 1 === this.getNumberOfAvailableSteps()\n const copy = clone(this.getGlobalState().flowStates[this.id])\n\n copy.$state.started = true\n copy.data.steps[thisStep.order].$state.completed = true\n copy.data.steps[thisStep.order].$state.started = true\n copy.data.steps[thisStep.order].$state.lastActionAt = new Date()\n\n // If there are more index, advance current step\n if (!isLastStep) {\n copy.$state.currentStepId = this.getStepByIndex(thisStep.order + 1).id\n copy.$state.currentStepIndex = thisStep.order + 1\n }\n\n if (isLastStep) {\n copy.$state.completed = true\n }\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n }\n\n await this.sendFlowStateToAPI(COMPLETED_STEP, properties, thisStep.id)\n }\n\n stepObj.reset = async () => {\n const thisStep = this.steps.get(step.id)\n\n if (!thisStep.$state.completed) {\n return\n }\n\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.data.steps[thisStep.order].$state.started = false\n copy.data.steps[thisStep.order].$state.completed = false\n copy.data.steps[thisStep.order].$state.lastActionAt = undefined\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n await this.sendFlowStateToAPI(NOT_STARTED_STEP, undefined, thisStep.id)\n }\n\n stepObj.onStateChange = (handler: (step: FlowStep, previousStep: FlowStep) => void) => {\n const wrapperHandler = (flow: Flow) => {\n if (flow.id !== this.id) {\n return\n }\n const thisStep = flow.steps.get(step.id)\n const previousStep = this.lastStepUpdate.get(handler)\n\n if (\n thisStep.$state.completed !== previousStep?.$state.completed ||\n thisStep.$state.started !== previousStep?.$state.started ||\n thisStep.$state.visible !== previousStep?.$state.visible ||\n thisStep.$state.blocked !== previousStep?.$state.blocked\n ) {\n handler(thisStep, previousStep ?? clone(thisStep))\n this.lastStepUpdate.set(handler, clone(thisStep))\n }\n }\n this.getGlobalState().onStepStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n stepObj.removeStateChangeHandler = (\n handler: (step: FlowStep, previousStep: FlowStep) => void\n ) => {\n const wrapperHandler = this.getGlobalState().onStepStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n newSteps.set(step.id, stepObj as FlowStep)\n })\n this.steps = newSteps\n // Check if empty object\n if (\n this.getGlobalState().variables &&\n this.getGlobalState().variables[this.id] &&\n Object.keys(this.getGlobalState().variables[this.id]).length > 0\n ) {\n this.applyVariables(this.getGlobalState().variables[this.id])\n }\n }\n\n /**\n * Marks the flow started\n */\n public async start(properties?: PropertyPayload) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowStarted()\n\n await this.sendFlowStateToAPI(STARTED_FLOW, properties)\n }\n\n /**\n * Marks the flow completed\n */\n public async complete(properties?: PropertyPayload) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n await this.sendFlowStateToAPI(COMPLETED_FLOW, properties)\n }\n\n /**\n * Marks the flow skipped\n */\n public async skip(properties?: PropertyPayload) {\n if (this.isSkipped) {\n return\n }\n this.optimisticallyMarkFlowSkipped()\n await this.sendFlowStateToAPI(SKIPPED_FLOW, properties)\n }\n\n /**\n * Navigates the flow to the next step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async forward(properties?: PropertyPayload) {\n const nextStep = this.getStepByIndex(this.getCurrentStepIndex() + 1)\n if (nextStep) {\n await nextStep.start(properties)\n } else {\n await this.complete(properties)\n }\n }\n\n /**\n * Navigates the flow to the previous step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async back(properties?: PropertyPayload) {\n const previousStep = this.getStepByIndex(this.getCurrentStepIndex() - 1)\n if (previousStep) {\n await previousStep.start(properties)\n }\n }\n\n /**\n * Restarts the flow/marks it not started\n */\n public async restart() {\n this.optimisticallyMarkFlowNotStarted()\n await this.sendFlowStateToAPI(NOT_STARTED_FLOW)\n }\n\n /**\n * Get a step by index\n * @param index\n */\n public getStepByIndex(index: number): FlowStep | undefined {\n return this.steps.get(Array.from(this.steps.keys())[index])\n }\n\n /**\n * Gets current step\n */\n public getCurrentStep(): FlowStep {\n return (\n this.steps.get(this.getStatefulFlow().$state.currentStepId) ??\n this.steps.get(Array.from(this.steps.keys())[0])\n )\n }\n\n /**\n * Get the index of the current step. Starts at 0\n */\n public getCurrentStepIndex(): number {\n const currentStep = this.getCurrentStep()\n return Array.from(this.steps.keys()).indexOf(currentStep.id)\n }\n\n /**\n * Get the number of completed steps for the current user in the current flow\n */\n public getNumberOfCompletedSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.$state.completed).length\n }\n\n /**\n * Get the number of available steps for the current user in the current flow. This is the number of steps that are not hidden.\n */\n public getNumberOfAvailableSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.$state.visible).length\n }\n\n /**\n * @ignore\n */\n public onStateChange(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = (flow: Flow, previousFlow: Flow) => {\n if (flow.id === this.id) {\n if (\n flow.isCompleted !== previousFlow?.isCompleted ||\n flow.isStarted !== previousFlow?.isStarted ||\n flow.isSkipped !== previousFlow?.isSkipped ||\n flow.isVisible !== previousFlow?.isVisible ||\n JSON.stringify(flow.steps) !== JSON.stringify(previousFlow?.steps)\n ) {\n handler(flow, previousFlow)\n }\n }\n }\n this.getGlobalState().onFlowStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n /**\n * @ignore\n */\n public removeStateChangeHandler(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = this.getGlobalState().onFlowStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n /**\n * Apply variables to the flow. This will replace any `${variable}` in the title, subtitle, and step fields with the value of the variable.\n * @param variables A record of variables to apply to the flow.\n */\n public applyVariables(variables: Record<string, any>) {\n // Replace ${variable} with the value of the variable\n const replaceVariables = (str: string) => {\n const matches = str.match(/\\${(.*?)}/g)\n if (matches) {\n matches.forEach((match) => {\n const variable = match.replace('${', '').replace('}', '')\n if (!variables[variable]) {\n return\n }\n str = str.replace(match, variables[variable])\n })\n }\n return str\n }\n\n this.title = replaceVariables(this.title ?? '')\n this.subtitle = replaceVariables(this.subtitle ?? '')\n this.steps.forEach((step) => {\n // Iterate over every string field in the step and replace variables\n Object.keys(step).forEach((key) => {\n if (typeof step[key] === 'string') {\n // @ts-ignore\n step[key] = replaceVariables(step[key])\n }\n })\n })\n\n this.getGlobalState().variables[this.id] = variables\n }\n\n /**\n * @ignore\n */\n private getStatefulFlow(): StatefulFlow {\n const userFlowStates = this.getGlobalState().flowStates\n return userFlowStates[this.id]\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowCompleted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = true\n copy.$state.started = true\n copy.$state.visible = false\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.started = true\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowNotStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = false\n copy.$state.started = false\n copy.$state.visible = true\n copy.$state.currentStepIndex = 0\n copy.$state.currentStepId = this.getStepByIndex(0)?.id\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n private async sendFlowStateToAPI(\n action: FlowActionType,\n data?: PropertyPayload,\n stepId?: string\n ) {\n const date = new Date()\n this.getGlobalState().lastSyncDate = date\n const flowStatesRaw: FlowStates = await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n flowSlug: this.id,\n stepId: stepId ?? this.getCurrentStep().id,\n data: data ? data : {},\n actionType: action,\n createdAt: date,\n context: getContext(this.getGlobalState().currentUrl),\n } as FlowStateDTO),\n })\n if (date < this.getGlobalState().lastSyncDate) {\n return\n }\n await this.getGlobalState().refreshStateFromAPI(flowStatesRaw)\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowSkipped() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.skipped = true\n copy.$state.visible = false\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n public register(callback?: RulesRegistryCallback) {\n const globalState = this.getGlobalState()\n\n globalState.collections.register(this.id, (visible) => {\n const prevFlow = this.getGlobalState().previousFlows.get(this.id)\n\n if (prevFlow?._isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(this, prevFlow)\n this.getGlobalState().previousFlows.set(this.id, cloneFlow(this))\n })\n }\n\n callback?.(visible)\n })\n }\n\n public unregister() {\n if (!this.getGlobalState().collections) {\n return\n }\n this.getGlobalState().collections.unregister(this.id)\n }\n}\n","import type { Flow } from './flow'\n\nexport type RulesRegistryCallback = (visible: boolean) => void\n\nexport type RulesRegistryBatch = [string, RulesRegistryCallback][]\n\nexport interface RulesRegistryItem {\n visible: boolean\n visited: boolean\n callback: RulesRegistryCallback\n}\n\nexport interface Rule {\n allowedComponents: string[]\n collectionType: 'DEFAULT' | 'CUSTOM'\n flows: {\n flowId: string\n visible: boolean\n }[]\n}\n\nexport interface EnrichedRule extends Omit<Rule, 'flows'> {\n flows: Array<\n Rule['flows'][number] & {\n flow: Flow\n }\n >\n}\n\nexport type RulesList = Map<string, Rule>\n\nexport class Rules {\n private readonly registry: Map<string, RulesRegistryItem> = new Map()\n private registryStateLocked: boolean = false\n private rules: RulesList = new Map()\n private flowsInRules: Set<string> = new Set()\n\n constructor(rulesData: RulesList) {\n this.ingestRulesData(rulesData)\n }\n\n getRule(ruleId: string) {\n return this.rules.get(ruleId)\n }\n\n getRules() {\n return this.rules\n }\n\n ingestRulesData(rulesData: RulesList) {\n this.rules = rulesData\n\n for (const [, rule] of this.rules) {\n for (const { flowId } of rule.flows) {\n this.flowsInRules.add(flowId)\n }\n }\n\n if (this.registry.size > 0) {\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n }\n\n this.fireCallbacks()\n }\n\n fireCallbacks() {\n for (const [flowId, { callback }] of this.registry) {\n if (typeof callback === 'function') {\n callback(this.isFlowVisible(flowId))\n }\n }\n }\n\n isFlowVisible(flowId: string) {\n const registeredFlow = this.registry.get(flowId)\n const flowInRules = this.flowsInRules.has(flowId)\n\n if (registeredFlow == null || !flowInRules) {\n return true\n }\n\n return registeredFlow.visible\n }\n\n lockRegistryState() {\n this.registryStateLocked = true\n }\n\n unlockRegistryState() {\n this.registryStateLocked = false\n }\n\n resetRegistryState() {\n for (const [flowId, item] of this.registry) {\n item.visible = false\n item.visited = false\n\n this.registry.set(flowId, item)\n }\n }\n\n processRules() {\n for (const [, rule] of this.rules) {\n for (const { flowId, visible: visibleAPIOverride } of rule.flows) {\n const registeredFlow = this.registry.get(flowId)\n\n // If this flow in the rule isn't registered, we have no opinion on it yet\n if (registeredFlow == null) {\n continue\n }\n\n // The API can force a flow to be hidden due to cool-offs, etc.\n if (visibleAPIOverride === false && registeredFlow.visible !== true) {\n this.visit(flowId, false)\n continue\n }\n\n // If this flow was processed in a previous rule and the registry is locked,\n // visibility shouldn't change until next time we run processRules\n if (registeredFlow.visited && this.registryStateLocked) {\n continue\n }\n\n const flowIdsInThisRule = rule.flows\n .map(({ flowId: otherFlowId }) => otherFlowId)\n .filter((otherFlowId) => otherFlowId !== flowId)\n\n // If another flow in this rule has been visited already and is visible...\n const anotherFlowInThisRuleIsVisible = flowIdsInThisRule.some((otherId) => {\n const { visible: otherVisible, visited: otherVisited } = this.registry.get(otherId) ?? {}\n\n return otherVisible && otherVisited\n })\n\n // ...then this flow is hidden\n if (anotherFlowInThisRuleIsVisible) {\n this.visit(flowId, false)\n\n continue\n }\n\n // No other flows are visible, so this flow is visible by default\n this.visit(flowId)\n }\n }\n }\n\n register(flowId: string | RulesRegistryBatch, callback?: RulesRegistryCallback) {\n if (Array.isArray(flowId)) {\n this.batchRegister(flowId)\n return\n }\n\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.fireCallbacks()\n }\n\n batchRegister(flowIds: RulesRegistryBatch) {\n flowIds.forEach(([flowId, callback]) => {\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.lockRegistryState()\n\n this.fireCallbacks()\n }\n\n unregister(flowId: string) {\n this.registry.delete(flowId)\n\n this.resetRegistryState()\n this.processRules()\n\n this.fireCallbacks()\n }\n\n private visit(flowId: string, visible: boolean = true) {\n const item = this.registry.get(flowId) ?? {\n callback: () => {},\n visible,\n visited: true,\n }\n\n item.visible = visible\n item.visited = true\n\n this.registry.set(flowId, item)\n }\n}\n","import {\n FlowStateDTO,\n FlowStates,\n FrigadeConfig,\n PropertyPayload,\n SessionDTO,\n StatefulFlow,\n} from './types'\nimport {\n clearCache,\n cloneFlow,\n getContext,\n GUEST_PREFIX,\n isWeb,\n resetAllLocalStorage,\n} from '../shared/utils'\nimport { Flow } from './flow'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/fetchable'\nimport {\n type EnrichedRule,\n type Rule,\n Rules,\n type RulesList,\n type RulesRegistryBatch,\n} from './rules'\n\nexport class Frigade extends Fetchable {\n /**\n * @ignore\n */\n private flows: Flow[] = []\n /**\n * @ignore\n */\n private initPromise: Promise<void>\n /**\n * @ignore\n */\n private hasFailed = false\n\n /**\n * @ignore\n */\n private visibilityChangeHandler = async () => {\n if (document.visibilityState === 'visible') {\n await this.refreshStateFromAPI()\n }\n }\n\n constructor(apiKey: string, config?: FrigadeConfig) {\n super({\n apiKey,\n ...config,\n })\n this.init(this.config)\n if (isWeb() && this.config.syncOnWindowUpdates !== false) {\n document.addEventListener('visibilitychange', this.visibilityChangeHandler)\n // @ts-ignore\n if (window.navigation) {\n // @ts-ignore\n window.navigation.addEventListener('navigate', async (event) => {\n if (this.getGlobalState().currentUrl === event.destination.url) {\n return\n }\n this.getGlobalState().currentUrl = event.destination.url\n this.refreshStateFromAPI()\n })\n }\n }\n }\n\n /**\n * Gets the current configuration.\n */\n getConfig() {\n return this.config\n }\n\n /**\n * @ignore\n */\n destroy() {\n if (isWeb()) {\n document.removeEventListener('visibilitychange', this.visibilityChangeHandler)\n // Remove all other event listeners\n const globalStateKey = getGlobalStateKey(this.config)\n if (frigadeGlobalState[globalStateKey]) {\n frigadeGlobalState[globalStateKey].onFlowStateChangeHandlers = []\n }\n }\n }\n\n /**\n * @ignore\n */\n private async init(config: FrigadeConfig): Promise<void> {\n this.updateConfig({\n ...this.config,\n ...config,\n })\n\n if (!this.config.userId && this.config.generateGuestId === false) {\n return\n }\n\n this.initPromise = (async () => {\n if (!this.config.__readOnly) {\n if (this.config.userId?.startsWith(GUEST_PREFIX)) {\n // do nothing\n } else if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n userProperties: this.config.userProperties,\n groupProperties: this.config.groupProperties,\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userProperties: this.config.userProperties,\n })\n }\n }\n await this.refreshStateFromAPI()\n })()\n\n return this.initPromise\n }\n\n /**\n * Set the current user.\n * @param userId\n * @param properties\n */\n public async identify(userId: string, properties?: PropertyPayload): Promise<void> {\n await this.updateConfig({ ...this.config, userId })\n await this.initIfNeeded()\n await this.session({\n userId: this.config.userId,\n userProperties: properties,\n })\n await this.resync()\n }\n\n /**\n * Set the group for the current user.\n * @param groupId\n * @param properties\n */\n public async group(groupId?: string, properties?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n this.updateConfig({ ...this.config, groupId })\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupProperties: properties,\n })\n await this.resync()\n }\n\n /**\n * Track an event for the current user (and group if set).\n * @param event\n * @param properties\n */\n public async track(event: string, properties?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n if (!event) {\n console.error('Event name is required to track an event')\n return\n }\n if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupEvents: [\n {\n event,\n properties,\n },\n ],\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n }\n await this.resync()\n }\n\n /**\n * @ignore\n */\n private async session(sessionDTO: SessionDTO) {\n await this.fetch('/v1/public/sessions', {\n method: 'POST',\n body: JSON.stringify(sessionDTO),\n })\n }\n\n /**\n * @ignore\n */\n public isReady(): boolean {\n return Boolean(this.config.__instanceId && this.config.apiKey && this.initPromise)\n }\n\n /**\n * Get a Flow by its ID.\n * @param flowId\n */\n public async getFlow(flowId: string) {\n await this.initIfNeeded()\n\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n await this.initIfNeeded()\n return this.flows\n }\n\n public async getCollection(collectionId: string) {\n await this.initIfNeeded()\n const collection = this.getGlobalState().collections.getRule(collectionId)\n\n if (collection == null) {\n return undefined\n }\n\n const enrichedFlows = await Promise.all(\n collection.flows.map(async (item) => ({\n ...item,\n flow: await this.getFlow(item.flowId),\n }))\n )\n\n collection.flows = enrichedFlows\n\n return collection as EnrichedRule\n }\n\n public async getCollections() {\n await this.initIfNeeded()\n const collections = this.getGlobalState().collections.getRules()\n\n if (collections == null) {\n return undefined\n }\n\n return collections\n }\n\n /**\n * Reload the current state of the flows by calling the Frigade API.\n * This will trigger all event handlers.\n * @param config optional config to use when reloading. If not passed, the current config will be used.\n */\n public async reload(config?: FrigadeConfig) {\n resetAllLocalStorage()\n clearCache()\n if (config) {\n await this.updateConfig(config)\n this.mockFlowStates(getGlobalStateKey(this.config))\n }\n this.initPromise = null\n await this.init(this.config)\n // Trigger all event handlers\n this.flows.forEach((flow) => {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n })\n }\n\n private async resync() {\n await this.refreshStateFromAPI()\n }\n\n /**\n * Event handler that captures all changes that happen to the state of the Flows.\n * @param handler\n */\n public async onStateChange(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers.push(handler)\n }\n\n /**\n * Returns true if the JS SDK failed to connect to the Frigade API.\n */\n hasFailedToLoad() {\n return this.hasFailed\n }\n\n /**\n * Removes the given handler from the list of event handlers.\n * @param handler\n */\n public async removeStateChangeHandler(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== handler)\n }\n\n /**\n * @ignore\n */\n private async initIfNeeded() {\n if (this.initPromise) {\n return this.initPromise\n } else {\n return this.init(this.config)\n }\n }\n\n /**\n * @ignore\n */\n private async refreshStateFromAPI(): Promise<void> {\n const globalStateKey = getGlobalStateKey(this.config)\n\n if (!frigadeGlobalState[globalStateKey]) {\n const that = this\n\n let validator = {\n set: function (target: any, key: any, value: any) {\n if (target[key]) {\n const previousState = target[key] as StatefulFlow\n const newState = value as StatefulFlow\n if (JSON.stringify(previousState) !== JSON.stringify(newState)) {\n that.triggerEventHandlers(newState, previousState)\n }\n }\n\n target[key] = value\n return true\n },\n }\n\n frigadeGlobalState[globalStateKey] = {\n refreshStateFromAPI: async () => {},\n collections: new Rules(new Map()),\n flowStates: new Proxy({}, validator),\n onFlowStateChangeHandlerWrappers: new Map(),\n onStepStateChangeHandlerWrappers: new Map(),\n onFlowStateChangeHandlers: [],\n previousFlows: new Map(),\n variables: {},\n config: this.config,\n currentUrl: isWeb() ? window.location.href : '',\n }\n\n if (this.config.__readOnly && this.config.__flowStateOverrides) {\n this.mockFlowStates(globalStateKey)\n\n return\n }\n\n frigadeGlobalState[globalStateKey].refreshStateFromAPI = async (\n overrideFlowStateRaw?: FlowStates\n ) => {\n if (this.config.__readOnly) {\n return\n }\n\n const flowStateRaw: FlowStates = overrideFlowStateRaw\n ? overrideFlowStateRaw\n : await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n context: getContext(this.getGlobalState().currentUrl),\n } as FlowStateDTO),\n })\n\n const rulesData: RulesList = new Map()\n\n flowStateRaw.collections?.computedOrder?.forEach(\n ({ allowedComponents, collectionId, collectionType, flowId, visible }) => {\n const currentRule: Rule = rulesData.get(collectionId) ?? {\n allowedComponents,\n collectionType,\n flows: [],\n }\n\n currentRule.flows.push({\n flowId,\n visible,\n })\n\n rulesData.set(collectionId, currentRule)\n }\n )\n\n frigadeGlobalState[globalStateKey].collections.ingestRulesData(rulesData)\n\n if (flowStateRaw && flowStateRaw.eligibleFlows) {\n flowStateRaw.eligibleFlows.forEach((statefulFlow) => {\n frigadeGlobalState[globalStateKey].flowStates[statefulFlow.flowSlug] = statefulFlow\n if (!this.flows.find((flow) => flow.id == statefulFlow.flowSlug)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: statefulFlow.flowSlug,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == statefulFlow.flowSlug) {\n flow.resyncState(statefulFlow)\n }\n })\n }\n })\n this.hasFailed = false\n } else {\n this.hasFailed = true\n }\n }\n }\n\n await frigadeGlobalState[globalStateKey].refreshStateFromAPI()\n }\n\n /**\n * @ignore\n */\n private mockFlowStates(globalStateKey: string) {\n Object.keys(this.config.__flowStateOverrides).forEach((flowId) => {\n frigadeGlobalState[globalStateKey].flowStates[flowId] =\n this.config.__flowStateOverrides[flowId]\n\n if (!this.flows.find((flow) => flow.id == flowId)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: flowId,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == flowId) {\n flow.resyncState(this.config.__flowStateOverrides[flowId])\n }\n })\n }\n })\n }\n\n /**\n * @ignore\n */\n private async updateConfig(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n if (frigadeGlobalState[getGlobalStateKey(this.config)]) {\n this.getGlobalState().config = this.config\n }\n }\n\n /**\n * @ignore\n */\n private async triggerEventHandlers(newState: StatefulFlow, previousState?: StatefulFlow) {\n if (newState) {\n this.flows.forEach((flow) => {\n if (flow.id == previousState.flowSlug) {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n flow.resyncState(newState)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n }\n })\n }\n }\n\n /**\n * @ignore\n */\n async batchRegister(flowIds: RulesRegistryBatch) {\n const flowIdsWithWrappedCallbacks = flowIds.map(async ([flowId, callback]) => {\n const currentFlow = await this.getFlow(flowId)\n const wrappedCallback = (visible: boolean) => {\n const prevFlow = this.getGlobalState().previousFlows.get(flowId)\n\n if (prevFlow?.isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(currentFlow, prevFlow)\n this.getGlobalState().previousFlows.set(flowId, cloneFlow(currentFlow))\n })\n }\n\n callback?.(visible)\n }\n\n return [flowId, wrappedCallback] as RulesRegistryBatch[number]\n })\n\n Promise.all(flowIdsWithWrappedCallbacks).then((results) => {\n this.getGlobalState().collections.batchRegister(results)\n })\n }\n}\n","import type { Flow } from './flow'\n\nexport enum TriggerType {\n MANUAL = 'MANUAL',\n AUTOMATIC = 'AUTOMATIC',\n}\n\nexport enum FlowStatus {\n DRAFT = 'DRAFT',\n ACTIVE = 'ACTIVE',\n ARCHIVED = 'ARCHIVED',\n}\n\nexport type StepAction =\n | 'flow.back'\n | 'flow.complete'\n | 'flow.forward'\n | 'flow.restart'\n | 'flow.skip'\n | 'flow.start'\n | 'step.complete'\n | 'step.reset'\n | 'step.start'\n | false\n\nexport type PropertyPayload = Record<string, any>\n\nexport interface FlowStep extends StatefulStep {\n /**\n * Order of the step in the Flow.\n */\n order: number\n\n /**\n * Name of the step when shown in a list view.\n */\n stepName?: string\n\n /**\n * Title of the step.\n */\n title?: string\n\n /**\n * Subtitle of the step.\n */\n subtitle?: string\n\n /**\n * Config for the primary button in this step\n */\n primaryButton?: {\n /**\n * Primary button action. (defaults to step.complete)\n */\n action?: StepAction\n\n /**\n * Primary button URI target (defaults to _self).\n */\n target?: string\n\n /**\n * Primary button title. If omitted, the primary button will not be shown.\n */\n title?: string\n\n /**\n * Primary button URI.\n */\n uri?: string\n }\n\n /**\n * @deprecated Use primaryButton.title instead\n * @description Primary button title. If omitted, the primary button will not be shown.\n */\n primaryButtonTitle?: string\n\n /**\n * @deprecated Use primaryButton.uri instead\n * @description Primary button URI.\n */\n primaryButtonUri?: string\n\n /**\n * @deprecated Use primaryButton.target instead\n * @description Primary button URI target (defaults to _self).\n */\n primaryButtonUriTarget?: string\n\n /**\n * Config for the secondary button in this step\n */\n secondaryButton?: {\n /**\n * Secondary button action. (defaults to step.complete)\n */\n action?: StepAction\n\n /**\n * Secondary button URI target (defaults to _self).\n */\n target?: string\n\n /**\n * Secondary button title. If omitted, the secondary button will not be shown.\n */\n title?: string\n\n /**\n * Secondary button URI.\n */\n uri?: string\n }\n\n /**\n * @deprecated Use secondaryButton.title instead\n * @description Secondary button title. If omitted, the secondary button will not be shown.\n */\n secondaryButtonTitle?: string\n\n /**\n * @deprecated Use secondaryButton.uri instead\n * @description Secondary button URI.\n */\n secondaryButtonUri?: string\n\n /**\n * @deprecated Use secondaryButton.target instead\n * @description Secondary button URI target (defaults to _self)\n */\n secondaryButtonUriTarget?: string\n\n /**\n * Text on button if a back button is present.\n */\n backButtonTitle?: string\n\n /**\n * If true, the step will be marked as completed when the secondary button is clicked.\n */\n skippable?: boolean\n\n /**\n * Video url to be shown for components supporting video.\n */\n videoUri?: string\n\n /**\n * Image url to be shown for components supporting image.\n */\n imageUri?: string | null\n\n /**\n * Automatically mark the step as completed when the primary button is clicked. Default is false.\n */\n autoMarkCompleted?: boolean\n\n /**\n * @ignore\n */\n props?: any\n /**\n * Criteria that needs to be met for the step to complete.\n * Completion criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be completed.\n */\n completionCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to start.\n * Start criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be started.\n */\n startCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to be visible.\n * Visibility criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be visible.\n */\n visibilityCriteria?: string\n\n /**\n * Progress if the step is tied to another Frigade Flow through completionCriteria.\n */\n progress?: number\n\n /**\n * Whether the step is dismissible (for instance, tooltips or other non-essential steps).\n */\n dismissible?: boolean\n\n /**\n * Any other additional props defined in the YAML config.\n */\n [x: string | number | symbol]: unknown\n\n /**\n * Marks the step started.\n */\n start: (properties?: PropertyPayload) => Promise<void>\n\n /**\n * Marks the step completed.\n * @param optimistic If true, the step will be marked as completed without waiting for the API and validation of any targeting rules.\n */\n complete: (properties?: PropertyPayload, optimistic?: boolean) => Promise<void>\n\n /**\n * Resets the step (useful for undoing a finished step).\n */\n reset: () => Promise<void>\n\n /**\n * Event handler called when this step's state changes.\n */\n onStateChange: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Removes the given callback from the list of event handlers.\n */\n removeStateChangeHandler: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Reference to this step's parent Flow\n */\n flow: Flow\n}\n\nexport interface FrigadeConfig {\n /**\n * Frigade API key. You can find your API key in the Frigade Dashboard under \"Developer\".\n */\n apiKey?: string\n /**\n * API url to use for all requests. Defaults to https://api.frigade.com\n */\n apiUrl?: string\n\n /**\n * User ID to use for all requests. If not provided, a Guest ID will be generated.\n */\n userId?: string\n\n /**\n * Group ID (organization) to use for all requests.\n */\n groupId?: string\n\n /**\n * Optional user properties to send to the API.\n */\n userProperties?: PropertyPayload\n\n /**\n * Optional group properties to send to the API.\n */\n groupProperties?: PropertyPayload\n\n /**\n * Whether to generate a Guest ID and session if no userId is not provided on initialization.\n * If set to false, Frigade will not initialize until a userId is provided via `frigade.identify()`.\n *\n * Defaults to true.\n */\n generateGuestId?: boolean\n\n /**\n * Whether to sync state with Frigade on URL or focus change. Defaults to true.\n */\n syncOnWindowUpdates?: boolean\n\n /**\n * @ignore Internal use only.\n * If enabled, Frigade will not send any data to the API. A user's state will be reset on page refresh.\n */\n __readOnly?: boolean\n\n /**\n * @ignore Internal use only.\n * Map of Flow ID to Flow State for all flows in the app that should be mocked.\n */\n __flowStateOverrides?: Record<string, StatefulFlow>\n\n /**\n * @ignore Internal use only.\n */\n __instanceId?: string\n}\n\nexport interface StatefulStep {\n id: string\n $state: {\n completed: boolean\n started: boolean\n visible: boolean\n blocked: boolean\n lastActionAt?: Date\n }\n // allow any other properties\n [key: string]: any\n}\n\nexport interface StatefulFlow {\n flowSlug: string\n flowName: string\n flowType: FlowType\n data: {\n steps: StatefulStep[]\n // allow any other properties\n [key: string]: any\n }\n $state: {\n currentStepId: string\n currentStepIndex: number\n completed: boolean\n started: boolean\n skipped: boolean\n visible: boolean\n lastActionAt?: Date\n }\n}\n\nexport enum CollectionType {\n CUSTOM = 'CUSTOM',\n DEFAULT = 'DEFAULT',\n}\n\nexport interface ComputedCollection {\n collectionId: string\n flowId: string\n visible: boolean\n allowedComponents: []\n collectionType: CollectionType\n}\n\nexport interface CollectionMetadata {\n computedOrder: ComputedCollection[]\n}\n\nexport interface FlowStates {\n eligibleFlows: StatefulFlow[]\n ineligibleFlows: string[]\n collections?: CollectionMetadata\n}\n\nexport enum FlowType {\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}\n\nexport type FlowActionType =\n | 'STARTED_STEP'\n | 'COMPLETED_STEP'\n | 'NOT_STARTED_STEP'\n | 'STARTED_FLOW'\n | 'COMPLETED_FLOW'\n | 'SKIPPED_FLOW'\n | 'NOT_STARTED_FLOW'\n\nexport interface FlowStateDTO {\n userId: string\n groupId?: string\n flowSlug?: string\n stepId?: string\n data?: any\n actionType?: FlowActionType\n createdAt?: Date\n context?: FlowStateContext\n}\n\nexport interface FlowStateContext {\n url?: string\n userAgent?: string\n}\n\nexport interface TrackingEvent {\n event: string\n properties?: PropertyPayload\n}\n\nexport interface SessionDTO {\n userId: string\n groupId?: string\n userProperties?: PropertyPayload\n userEvents?: TrackingEvent[]\n groupProperties?: PropertyPayload\n groupEvents?: TrackingEvent[]\n linkGuestId?: string\n}\n"],"mappings":";ooBAAO,IAAMA,EAAiB,SCC9B,OAAS,MAAMC,MAAc,OCuBtB,IAAIC,EAAyD,CAAC,EAE9D,SAASC,EAAkBC,EAAuC,CACvE,MAAO,GAAGA,EAAe,gBAAgBA,EAAe,QAC1D,CCxBO,IAAMC,EAAN,KAAgB,CASrB,YAAYC,EAAuB,CARnC,KAAO,OAAwB,CAC7B,OAAQ,GACR,OAAQ,0BACR,OAAQC,EAAgB,EACxB,aAAc,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,UAAU,CAAC,EACpD,gBAAiB,EACnB,EAGE,IAAMC,EAAiB,OAAO,YAAY,OAAO,QAAQF,CAAM,EAAE,OAAO,CAAC,CAACG,EAAGC,CAAC,IAAMA,GAAK,IAAI,CAAC,EAC1F,CAACJ,EAAO,QAAUA,EAAO,kBAAoB,IAC/C,OAAO,KAAK,OAAO,OAErB,KAAK,OAASK,IAAA,GACT,KAAK,QACLH,EAEP,CAKa,MAAMI,EAAcC,EAA4B,QAAAC,EAAA,sBAC3D,OAAI,KAAK,OAAO,WACPC,EAAiB,EAGnBC,EAAc,KAAK,UAAUJ,CAAI,EAAGD,IAA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S,SACTA,EAAA,UAAY,YAFFA,OAAA,IAKAC,OACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SACTA,EAAA,SAAW,WAHDA,OAAA,IAkVL,IAAKC,OACVA,EAAA,aAAe,eACfA,EAAA,UAAY,YACZA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,QAAU,UACVA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,aAAe,eACfA,EAAA,WAAa,aACbA,EAAA,OAAS,SACTA,EAAA,KAAO,OAXGA,OAAA","names":["VERSION_NUMBER","uuidv4","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","filteredConfig","_","v","__spreadValues","path","options","__async","getEmptyResponse","gracefulFetch","getHeaders","globalStateKey","getGlobalStateKey","frigadeGlobalState","Flow","Fetchable","config","id","visible","overrideStatefulFlow","_a","_b","_c","statefulFlow","step","index","stepObj","existingStep","key","__spreadProps","__spreadValues","newSteps","properties","__async","thisStep","copy","clone","STARTED_STEP","optimistic","isLastStep","COMPLETED_STEP","NOT_STARTED_STEP","handler","wrapperHandler","flow","previousStep","h","STARTED_FLOW","COMPLETED_FLOW","SKIPPED_FLOW","nextStep","NOT_STARTED_FLOW","currentStep","previousFlow","variables","replaceVariables","str","matches","match","variable","action","data","stepId","date","flowStatesRaw","getContext","callback","prevFlow","cloneFlow","NOT_STARTED_STEP","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","GUEST_KEY","GUEST_PREFIX","GET_CACHE_PREFIX","LOCAL_STORAGE_PREFIX","cloneFlow","flow","Flow","clone","obj","getHeaders","apiKey","VERSION_NUMBER","getLocalStorage","key","isWeb","setLocalStorage","value","clearCache","frigadeGlobalState","key","GET_CACHE_PREFIX","resetAllLocalStorage","isWeb","LOCAL_STORAGE_PREFIX","CallQueue","call","now","item","callQueue","gracefulFetch","url","options","__async","_a","getEmptyResponse","lastCallDataKey","response","error","body","e","generateGuestId","guestId","getLocalStorage","GUEST_KEY","GUEST_PREFIX","uuidv4","setLocalStorage","isWeb","getContext","currentUrl","Rules","rulesData","ruleId","rule","flowId","callback","registeredFlow","flowInRules","item","visibleAPIOverride","otherFlowId","otherId","_a","otherVisible","otherVisited","flowIds","visible","Frigade","Fetchable","apiKey","config","__spreadValues","__async","isWeb","event","globalStateKey","getGlobalStateKey","frigadeGlobalState","_a","GUEST_PREFIX","userId","properties","__spreadProps","groupId","sessionDTO","flowId","flow","collectionId","collection","enrichedFlows","item","collections","resetAllLocalStorage","clearCache","handler","lastFlow","cloneFlow","h","that","validator","target","key","value","previousState","newState","Rules","overrideFlowStateRaw","_b","flowStateRaw","getContext","rulesData","allowedComponents","collectionType","visible","currentRule","statefulFlow","Flow","flowIds","flowIdsWithWrappedCallbacks","_0","callback","currentFlow","prevFlow","results","TriggerType","FlowStatus","FlowType"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/shared/fetchable.ts","../src/core/flow.ts","../src/core/rules.ts","../src/core/frigade.ts","../src/core/types.ts"],"sourcesContent":["export const VERSION_NUMBER = '0.2.20'\n","import { VERSION_NUMBER } from '../core/version'\nimport { v4 as uuidv4 } from 'uuid'\nimport { Flow } from '../core/flow'\nimport { frigadeGlobalState } from './state'\nimport { FlowStateContext } from '../core/types'\n\nexport const NOT_STARTED_STEP = 'NOT_STARTED_STEP'\nexport const COMPLETED_FLOW = 'COMPLETED_FLOW'\nexport const SKIPPED_FLOW = 'SKIPPED_FLOW'\nexport const STARTED_FLOW = 'STARTED_FLOW'\nexport const NOT_STARTED_FLOW = 'NOT_STARTED_FLOW'\nexport const COMPLETED_STEP = 'COMPLETED_STEP'\nexport const STARTED_STEP = 'STARTED_STEP'\nconst GUEST_KEY = 'frigade-guest-key'\nexport const GUEST_PREFIX = 'guest_'\nconst GET_CACHE_PREFIX = 'get-cache-'\nconst LOCAL_STORAGE_PREFIX = 'fr-js-'\n\nexport function cloneFlow(flow: Flow): Flow {\n const newFlow = new Flow({\n config: flow.config,\n id: flow.id,\n })\n return newFlow\n}\n\nexport function clone<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj))\n}\n\nexport function getHeaders(apiKey: string) {\n return {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Frigade-SDK-Version': VERSION_NUMBER,\n 'X-Frigade-SDK-Platform': 'Javascript',\n },\n }\n}\n\nfunction getLocalStorage(key: string) {\n if (isWeb()) {\n return window.localStorage.getItem(`${LOCAL_STORAGE_PREFIX}${key}`)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (isWeb()) {\n window.localStorage.setItem(`${LOCAL_STORAGE_PREFIX}${key}`, value)\n }\n}\n\nfunction setGlobalState(key: string, value: any) {\n frigadeGlobalState[key] = value\n}\n\nfunction getGlobalState(key: string): any {\n return frigadeGlobalState[key]\n}\n\nexport function clearCache() {\n Object.keys(frigadeGlobalState).forEach((key) => {\n if (key.startsWith(GET_CACHE_PREFIX)) {\n delete frigadeGlobalState[key]\n }\n })\n}\n\nexport function resetAllLocalStorage() {\n if (isWeb()) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith(LOCAL_STORAGE_PREFIX)) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nclass CallQueue {\n private queue: {\n call: string\n time: number\n }[] = []\n private readonly ttlInMS = 100\n private readonly cacheSize = 5\n\n public push(call: string) {\n const now = new Date()\n if (this.queue.length >= this.cacheSize) {\n this.queue.shift()\n }\n this.queue.push({\n call: call,\n time: now.getTime(),\n })\n }\n\n public hasIdenticalCall(call: string) {\n const now = new Date()\n this.queue = this.queue.filter((item) => now.getTime() - item.time < this.ttlInMS)\n return this.queue.some((item) => item.call === call)\n }\n}\n\nconst callQueue = new CallQueue()\n\nexport async function gracefulFetch(url: string, options: any) {\n if (typeof globalThis.fetch !== 'function') {\n return getEmptyResponse(\n \"- Attempted to call fetch() in an environment that doesn't support it.\"\n )\n }\n\n if (isWeb() && options && options.body && options.method === 'POST') {\n const lastCallDataKey = `${url}${JSON.stringify(options.body ?? {})}`\n if (callQueue.hasIdenticalCall(lastCallDataKey)) {\n return getEmptyResponse()\n }\n callQueue.push(lastCallDataKey)\n }\n\n let response\n try {\n response = fetch(url, options)\n response = await response\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse('Received an empty response')\n }\n\n if (response.status >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n try {\n if (response.status === 204) {\n return getEmptyResponse()\n }\n\n let body\n try {\n body = await response.json()\n } catch (e) {\n return getEmptyResponse()\n }\n\n if (body.error) {\n return getEmptyResponse(body.error)\n }\n return body\n } catch (e) {\n return getEmptyResponse(e)\n }\n}\n\nexport function getEmptyResponse(error?: any) {\n if (error) {\n console.log('Call to Frigade failed', error)\n }\n\n // Create empty response that contains the .json method and returns an empty object\n return {\n json: () => ({}),\n }\n}\n\nexport function generateGuestId() {\n if (isWeb()) {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n setLocalStorage(GUEST_KEY, guestId)\n }\n return guestId\n } else {\n return `${GUEST_PREFIX}${uuidv4()}`\n }\n}\n\nexport function fetcher(apiKey: string, path: string, options?: Record<any, any>) {\n return gracefulFetch(`//api.frigade.com/v1/public${path}`, {\n ...(options ?? {}),\n ...getHeaders(apiKey),\n })\n}\n\nexport function isWeb() {\n return (\n typeof window !== 'undefined' &&\n typeof window.document !== 'undefined' &&\n typeof window.localStorage !== 'undefined'\n )\n}\n\nexport function getContext(currentUrl: string): FlowStateContext {\n if (!isWeb()) {\n return {}\n }\n\n return {\n url: currentUrl,\n userAgent: navigator.userAgent,\n }\n}\n","import { FlowStates, FlowStep, FrigadeConfig, StatefulFlow } from '../core/types'\nimport { Flow } from '../core/flow'\nimport type { Rules } from '../core/rules'\n\nexport interface FrigadeGlobalState {\n refreshStateFromAPI: (overrideFlowStatesRaw?: FlowStates) => Promise<void>\n flowStates: Record<string, StatefulFlow>\n collections: Rules\n onFlowStateChangeHandlerWrappers: Map<\n (flow: Flow, previousFlow: Flow) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onStepStateChangeHandlerWrappers: Map<\n (step: FlowStep, previousStep: FlowStep) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onFlowStateChangeHandlers: ((flow: Flow, previousFlow: Flow) => void)[]\n previousFlows: Map<string, Flow>\n variables: Record<string, Record<string, any>>\n lastSyncDate?: Date\n config: FrigadeConfig\n currentUrl: string\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}`\n}\n","import { generateGuestId, getEmptyResponse, getHeaders, gracefulFetch } from './utils'\nimport { FrigadeConfig } from '../core/types'\nimport { frigadeGlobalState, FrigadeGlobalState, getGlobalStateKey } from './state'\n\nexport class Fetchable {\n public config: FrigadeConfig = {\n apiKey: '',\n apiUrl: 'https://api.frigade.com',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(12).substring(4),\n generateGuestId: true,\n }\n\n constructor(config: FrigadeConfig) {\n const filteredConfig = Object.fromEntries(Object.entries(config).filter(([_, v]) => v != null))\n if (!config.userId && config.generateGuestId === false) {\n delete this.config.userId\n }\n this.config = {\n ...this.config,\n ...filteredConfig,\n }\n }\n\n /**\n * @ignore\n */\n public async fetch(path: string, options?: Record<any, any>) {\n if (this.config.__readOnly) {\n return getEmptyResponse()\n }\n\n return gracefulFetch(this.getAPIUrl(path), {\n keepalive: true,\n ...(options ?? {}),\n ...getHeaders(this.config.apiKey),\n })\n }\n\n private getAPIUrl(path: string) {\n return `${this.config.apiUrl.replace(/\\/$/, '')}/${path.replace(/^\\//, '')}`\n }\n\n /**\n * @ignore\n */\n protected getGlobalState(): FrigadeGlobalState {\n const globalStateKey = getGlobalStateKey(this.config)\n if (!frigadeGlobalState[globalStateKey]) {\n throw new Error('Frigade has not yet been initialized')\n }\n return frigadeGlobalState[globalStateKey]\n }\n}\n","import {\n FlowActionType,\n FlowStateDTO,\n FlowStates,\n FlowStep,\n FrigadeConfig,\n PropertyPayload,\n StatefulFlow,\n StatefulStep,\n} from './types'\nimport {\n clone,\n cloneFlow,\n COMPLETED_FLOW,\n COMPLETED_STEP,\n getContext,\n NOT_STARTED_FLOW,\n NOT_STARTED_STEP,\n SKIPPED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { Fetchable } from '../shared/fetchable'\nimport { RulesRegistryCallback } from './rules'\n\nexport class Flow extends Fetchable {\n /**\n * The Flow's ID.\n */\n public id: string\n /**\n * The Flow's component ID.\n */\n public componentId: string\n /**\n * Ordered map of the Steps in the Flow.\n * See [Flow Step Definition](https://docs.frigade.com/v2/sdk/js/step) for more information.\n */\n public steps: Map<string, FlowStep>\n /**\n * The user-facing title of the Flow, if defined at the top level of the YAML config.\n */\n public title?: string\n /**\n * The user-facing description of the Flow, if defined at the top level of the YAML config.\n */\n public subtitle?: string\n /**\n * The metadata of the Flow.\n * @ignore\n */\n public rawData: StatefulFlow\n /**\n * Whether the Flow is completed or not.\n */\n public isCompleted: boolean\n /**\n * Whether the Flow is started or not.\n */\n public isStarted: boolean\n /**\n * Whether the Flow has been skipped or not.\n */\n public isSkipped: boolean\n /**\n * @ignore\n */\n private _isVisible: boolean = false\n /**\n * Whether the Flow is visible to the user based on the current user/group's state.\n */\n get isVisible() {\n if (this._isVisible === false) {\n return false\n }\n\n return this.getGlobalState().collections.isFlowVisible(this.id)\n }\n set isVisible(visible: boolean) {\n this._isVisible = visible\n }\n\n /**\n * @ignore\n */\n private lastStepUpdate: Map<(step: FlowStep, previousStep: FlowStep) => void, FlowStep> =\n new Map()\n\n constructor({ config, id }: { config: FrigadeConfig; id: string }) {\n super(config)\n this.id = id\n this.init()\n }\n\n /**\n * Reload the Flow data from the server\n */\n reload() {\n this.init()\n }\n\n /**\n * @ignore\n */\n resyncState(overrideStatefulFlow?: StatefulFlow) {\n const statefulFlow = overrideStatefulFlow ?? this.getStatefulFlow()\n\n this.rawData = statefulFlow\n this.title = statefulFlow?.data?.title\n this.subtitle = statefulFlow?.data?.subtitle\n\n this.isCompleted = statefulFlow.$state.completed\n this.isStarted = statefulFlow.$state.started\n this.isSkipped = statefulFlow.$state.skipped\n this._isVisible = statefulFlow.$state.visible\n\n statefulFlow.data.steps.forEach((step, index) => {\n const stepObj = this.initStepFromStatefulStep(step, index)\n\n const existingStep = this.steps?.get(step.id)\n if (existingStep) {\n Object.keys(stepObj).forEach((key) => {\n existingStep[key] = stepObj[key]\n })\n }\n })\n\n if (this.steps && this.steps.size > 0) {\n this.applyVariables(this.getGlobalState().variables[this.id] ?? {})\n }\n }\n\n /**\n * @ignore\n */\n private initStepFromStatefulStep(step: StatefulStep, index: number) {\n return {\n ...step,\n flow: this,\n $state: {\n ...step.$state,\n lastActionAt: step.$state.lastActionAt ? new Date(step.$state.lastActionAt) : undefined,\n },\n order: index,\n } as Partial<FlowStep>\n }\n\n /**\n * @ignore\n */\n private init() {\n const statefulFlow = this.getStatefulFlow()\n\n this.resyncState()\n\n const newSteps = new Map<string, FlowStep>()\n\n statefulFlow.data.steps.forEach((step, index) => {\n const stepObj = this.initStepFromStatefulStep(step, index)\n\n stepObj.start = async (properties?: PropertyPayload) => {\n const thisStep = this.steps.get(step.id)\n\n if (this.getCurrentStep().id === thisStep.id && thisStep.$state.started) {\n return\n }\n\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.data.steps[thisStep.order].$state.started = true\n copy.data.steps[thisStep.order].$state.lastActionAt = new Date()\n copy.$state.lastActionAt = new Date()\n copy.$state.currentStepId = thisStep.id\n copy.$state.currentStepIndex = thisStep.order\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n await this.sendFlowStateToAPI(STARTED_STEP, properties, thisStep.id)\n }\n\n stepObj.complete = async (properties?: PropertyPayload, optimistic: boolean = true) => {\n const thisStep = this.steps.get(step.id)\n\n if (thisStep.$state.completed && optimistic) {\n return\n }\n\n if (optimistic) {\n const isLastStep = thisStep.order + 1 === this.getNumberOfAvailableSteps()\n const copy = clone(this.getGlobalState().flowStates[this.id])\n\n copy.$state.started = true\n copy.data.steps[thisStep.order].$state.completed = true\n copy.data.steps[thisStep.order].$state.started = true\n copy.data.steps[thisStep.order].$state.lastActionAt = new Date()\n\n // If there are more index, advance current step\n if (!isLastStep) {\n copy.$state.currentStepId = this.getStepByIndex(thisStep.order + 1).id\n copy.$state.currentStepIndex = thisStep.order + 1\n }\n\n if (isLastStep) {\n copy.$state.completed = true\n }\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n }\n\n await this.sendFlowStateToAPI(COMPLETED_STEP, properties, thisStep.id)\n }\n\n stepObj.reset = async () => {\n const thisStep = this.steps.get(step.id)\n\n if (!thisStep.$state.completed) {\n return\n }\n\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.data.steps[thisStep.order].$state.started = false\n copy.data.steps[thisStep.order].$state.completed = false\n copy.data.steps[thisStep.order].$state.lastActionAt = undefined\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n await this.sendFlowStateToAPI(NOT_STARTED_STEP, undefined, thisStep.id)\n }\n\n stepObj.onStateChange = (handler: (step: FlowStep, previousStep: FlowStep) => void) => {\n const wrapperHandler = (flow: Flow) => {\n if (flow.id !== this.id) {\n return\n }\n const thisStep = flow.steps.get(step.id)\n const previousStep = this.lastStepUpdate.get(handler)\n\n if (\n thisStep.$state.completed !== previousStep?.$state.completed ||\n thisStep.$state.started !== previousStep?.$state.started ||\n thisStep.$state.visible !== previousStep?.$state.visible ||\n thisStep.$state.blocked !== previousStep?.$state.blocked\n ) {\n handler(thisStep, previousStep ?? clone(thisStep))\n this.lastStepUpdate.set(handler, clone(thisStep))\n }\n }\n this.getGlobalState().onStepStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n stepObj.removeStateChangeHandler = (\n handler: (step: FlowStep, previousStep: FlowStep) => void\n ) => {\n const wrapperHandler = this.getGlobalState().onStepStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n newSteps.set(step.id, stepObj as FlowStep)\n })\n this.steps = newSteps\n // Check if empty object\n if (\n this.getGlobalState().variables &&\n this.getGlobalState().variables[this.id] &&\n Object.keys(this.getGlobalState().variables[this.id]).length > 0\n ) {\n this.applyVariables(this.getGlobalState().variables[this.id])\n }\n }\n\n /**\n * Marks the flow started\n */\n public async start(properties?: PropertyPayload) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowStarted()\n\n await this.sendFlowStateToAPI(STARTED_FLOW, properties)\n }\n\n /**\n * Marks the flow completed\n */\n public async complete(properties?: PropertyPayload) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n await this.sendFlowStateToAPI(COMPLETED_FLOW, properties)\n }\n\n /**\n * Marks the flow skipped\n */\n public async skip(properties?: PropertyPayload) {\n if (this.isSkipped) {\n return\n }\n this.optimisticallyMarkFlowSkipped()\n await this.sendFlowStateToAPI(SKIPPED_FLOW, properties)\n }\n\n /**\n * Navigates the flow to the next step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async forward(properties?: PropertyPayload) {\n const nextStep = this.getStepByIndex(this.getCurrentStepIndex() + 1)\n if (nextStep) {\n await nextStep.start(properties)\n } else {\n await this.complete(properties)\n }\n }\n\n /**\n * Navigates the flow to the previous step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async back(properties?: PropertyPayload) {\n const previousStep = this.getStepByIndex(this.getCurrentStepIndex() - 1)\n if (previousStep) {\n await previousStep.start(properties)\n }\n }\n\n /**\n * Restarts the flow/marks it not started\n */\n public async restart() {\n this.optimisticallyMarkFlowNotStarted()\n await this.sendFlowStateToAPI(NOT_STARTED_FLOW)\n }\n\n /**\n * Get a step by index\n * @param index\n */\n public getStepByIndex(index: number): FlowStep | undefined {\n return this.steps.get(Array.from(this.steps.keys())[index])\n }\n\n /**\n * Gets current step\n */\n public getCurrentStep(): FlowStep {\n return (\n this.steps.get(this.getStatefulFlow().$state.currentStepId) ??\n this.steps.get(Array.from(this.steps.keys())[0])\n )\n }\n\n /**\n * Get the index of the current step. Starts at 0\n */\n public getCurrentStepIndex(): number {\n const currentStep = this.getCurrentStep()\n return Array.from(this.steps.keys()).indexOf(currentStep.id)\n }\n\n /**\n * Get the number of completed steps for the current user in the current flow\n */\n public getNumberOfCompletedSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.$state.completed).length\n }\n\n /**\n * Get the number of available steps for the current user in the current flow. This is the number of steps that are not hidden.\n */\n public getNumberOfAvailableSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.$state.visible).length\n }\n\n /**\n * @ignore\n */\n public onStateChange(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = (flow: Flow, previousFlow: Flow) => {\n if (flow.id === this.id) {\n if (\n flow.isCompleted !== previousFlow?.isCompleted ||\n flow.isStarted !== previousFlow?.isStarted ||\n flow.isSkipped !== previousFlow?.isSkipped ||\n flow.isVisible !== previousFlow?.isVisible ||\n JSON.stringify(flow.steps) !== JSON.stringify(previousFlow?.steps)\n ) {\n handler(flow, previousFlow)\n }\n }\n }\n this.getGlobalState().onFlowStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n /**\n * @ignore\n */\n public removeStateChangeHandler(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = this.getGlobalState().onFlowStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n /**\n * Apply variables to the flow. This will replace any `${variable}` in the title, subtitle, and step fields with the value of the variable.\n * @param variables A record of variables to apply to the flow.\n */\n public applyVariables(variables: Record<string, any>) {\n // Replace ${variable} with the value of the variable\n const replaceVariables = (str: string) => {\n const matches = str.match(/\\${(.*?)}/g)\n if (matches) {\n matches.forEach((match) => {\n const variable = match.replace('${', '').replace('}', '')\n if (!variables[variable]) {\n return\n }\n str = str.replace(match, variables[variable])\n })\n }\n return str\n }\n\n this.title = replaceVariables(this.title ?? '')\n this.subtitle = replaceVariables(this.subtitle ?? '')\n this.steps.forEach((step) => {\n // Iterate over every string field in the step and replace variables\n Object.keys(step).forEach((key) => {\n if (typeof step[key] === 'string') {\n // @ts-ignore\n step[key] = replaceVariables(step[key])\n }\n })\n })\n\n this.getGlobalState().variables[this.id] = variables\n }\n\n /**\n * @ignore\n */\n private getStatefulFlow(): StatefulFlow {\n const userFlowStates = this.getGlobalState().flowStates\n return userFlowStates[this.id]\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowCompleted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = true\n copy.$state.started = true\n copy.$state.visible = false\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.started = true\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowNotStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = false\n copy.$state.started = false\n copy.$state.visible = true\n copy.$state.currentStepIndex = 0\n copy.$state.currentStepId = this.getStepByIndex(0)?.id\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n private async sendFlowStateToAPI(\n action: FlowActionType,\n data?: PropertyPayload,\n stepId?: string\n ) {\n const date = new Date()\n this.getGlobalState().lastSyncDate = date\n const flowStatesRaw: FlowStates = await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n flowSlug: this.id,\n stepId: stepId ?? this.getCurrentStep().id,\n data: data ? data : {},\n actionType: action,\n createdAt: date,\n context: getContext(this.getGlobalState().currentUrl),\n } as FlowStateDTO),\n })\n if (date < this.getGlobalState().lastSyncDate) {\n return\n }\n await this.getGlobalState().refreshStateFromAPI(flowStatesRaw)\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowSkipped() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.skipped = true\n copy.$state.visible = false\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n public register(callback?: RulesRegistryCallback) {\n const globalState = this.getGlobalState()\n\n globalState.collections.register(this.id, (visible) => {\n const prevFlow = this.getGlobalState().previousFlows.get(this.id)\n\n if (prevFlow?._isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(this, prevFlow)\n this.getGlobalState().previousFlows.set(this.id, cloneFlow(this))\n })\n }\n\n callback?.(visible)\n })\n }\n\n public unregister() {\n if (!this.getGlobalState().collections) {\n return\n }\n this.getGlobalState().collections.unregister(this.id)\n }\n}\n","import type { Flow } from './flow'\n\nexport type RulesRegistryCallback = (visible: boolean) => void\n\nexport type RulesRegistryBatch = [string, RulesRegistryCallback][]\n\nexport interface RulesRegistryItem {\n visible: boolean\n visited: boolean\n callback: RulesRegistryCallback\n}\n\nexport interface Rule {\n allowedComponents: string[]\n collectionType: 'DEFAULT' | 'CUSTOM'\n flows: {\n flowId: string\n visible: boolean\n }[]\n}\n\nexport interface EnrichedRule extends Omit<Rule, 'flows'> {\n flows: Array<\n Rule['flows'][number] & {\n flow: Flow\n }\n >\n}\n\nexport type RulesList = Map<string, Rule>\n\nexport class Rules {\n private readonly registry: Map<string, RulesRegistryItem> = new Map()\n private registryStateLocked: boolean = false\n private rules: RulesList = new Map()\n private flowsInRules: Set<string> = new Set()\n\n constructor(rulesData: RulesList) {\n this.ingestRulesData(rulesData)\n }\n\n getRule(ruleId: string) {\n return this.rules.get(ruleId)\n }\n\n getRules() {\n return this.rules\n }\n\n ingestRulesData(rulesData: RulesList) {\n this.rules = rulesData\n\n for (const [, rule] of this.rules) {\n for (const { flowId } of rule.flows) {\n this.flowsInRules.add(flowId)\n }\n }\n\n if (this.registry.size > 0) {\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n }\n\n this.fireCallbacks()\n }\n\n fireCallbacks() {\n for (const [flowId, { callback }] of this.registry) {\n if (typeof callback === 'function') {\n callback(this.isFlowVisible(flowId))\n }\n }\n }\n\n isFlowVisible(flowId: string) {\n const registeredFlow = this.registry.get(flowId)\n const flowInRules = this.flowsInRules.has(flowId)\n\n if (registeredFlow == null || !flowInRules) {\n return true\n }\n\n return registeredFlow.visible\n }\n\n lockRegistryState() {\n this.registryStateLocked = true\n }\n\n unlockRegistryState() {\n this.registryStateLocked = false\n }\n\n resetRegistryState() {\n for (const [flowId, item] of this.registry) {\n item.visible = false\n item.visited = false\n\n this.registry.set(flowId, item)\n }\n }\n\n processRules() {\n for (const [, rule] of this.rules) {\n for (const { flowId, visible: visibleAPIOverride } of rule.flows) {\n const registeredFlow = this.registry.get(flowId)\n\n // If this flow in the rule isn't registered, we have no opinion on it yet\n if (registeredFlow == null) {\n continue\n }\n\n // The API can force a flow to be hidden due to cool-offs, etc.\n if (visibleAPIOverride === false && registeredFlow.visible !== true) {\n this.visit(flowId, false)\n continue\n }\n\n // If this flow was processed in a previous rule and the registry is locked,\n // visibility shouldn't change until next time we run processRules\n if (registeredFlow.visited && this.registryStateLocked) {\n continue\n }\n\n const flowIdsInThisRule = rule.flows\n .map(({ flowId: otherFlowId }) => otherFlowId)\n .filter((otherFlowId) => otherFlowId !== flowId)\n\n // If another flow in this rule has been visited already and is visible...\n const anotherFlowInThisRuleIsVisible = flowIdsInThisRule.some((otherId) => {\n const { visible: otherVisible, visited: otherVisited } = this.registry.get(otherId) ?? {}\n\n return otherVisible && otherVisited\n })\n\n // ...then this flow is hidden\n if (anotherFlowInThisRuleIsVisible) {\n this.visit(flowId, false)\n\n continue\n }\n\n // No other flows are visible, so this flow is visible by default\n this.visit(flowId)\n }\n }\n }\n\n register(flowId: string | RulesRegistryBatch, callback?: RulesRegistryCallback) {\n if (Array.isArray(flowId)) {\n this.batchRegister(flowId)\n return\n }\n\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.fireCallbacks()\n }\n\n batchRegister(flowIds: RulesRegistryBatch) {\n flowIds.forEach(([flowId, callback]) => {\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.lockRegistryState()\n\n this.fireCallbacks()\n }\n\n unregister(flowId: string) {\n this.registry.delete(flowId)\n\n this.resetRegistryState()\n this.processRules()\n\n this.fireCallbacks()\n }\n\n private visit(flowId: string, visible: boolean = true) {\n const item = this.registry.get(flowId) ?? {\n callback: () => {},\n visible,\n visited: true,\n }\n\n item.visible = visible\n item.visited = true\n\n this.registry.set(flowId, item)\n }\n}\n","import {\n FlowStateDTO,\n FlowStates,\n FrigadeConfig,\n PropertyPayload,\n SessionDTO,\n StatefulFlow,\n} from './types'\nimport {\n clearCache,\n cloneFlow,\n getContext,\n GUEST_PREFIX,\n isWeb,\n resetAllLocalStorage,\n} from '../shared/utils'\nimport { Flow } from './flow'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/fetchable'\nimport {\n type EnrichedRule,\n type Rule,\n Rules,\n type RulesList,\n type RulesRegistryBatch,\n} from './rules'\n\nexport class Frigade extends Fetchable {\n /**\n * @ignore\n */\n private flows: Flow[] = []\n /**\n * @ignore\n */\n private initPromise: Promise<void>\n /**\n * @ignore\n */\n private hasFailed = false\n\n /**\n * @ignore\n */\n private visibilityChangeHandler = async () => {\n if (document.visibilityState === 'visible') {\n await this.refreshStateFromAPI()\n }\n }\n\n constructor(apiKey: string, config?: FrigadeConfig) {\n super({\n apiKey,\n ...config,\n })\n this.init(this.config)\n if (isWeb() && this.config.syncOnWindowUpdates !== false) {\n document.addEventListener('visibilitychange', this.visibilityChangeHandler)\n // @ts-ignore\n if (window.navigation) {\n // @ts-ignore\n window.navigation.addEventListener('navigate', async (event) => {\n if (this.getGlobalState().currentUrl === event.destination.url) {\n return\n }\n try {\n this.getGlobalState().currentUrl = event.destination.url\n this.refreshStateFromAPI()\n } catch (e) {}\n })\n }\n }\n }\n\n /**\n * Gets the current configuration.\n */\n getConfig() {\n return this.config\n }\n\n /**\n * @ignore\n */\n destroy() {\n if (isWeb()) {\n document.removeEventListener('visibilitychange', this.visibilityChangeHandler)\n // Remove all other event listeners\n const globalStateKey = getGlobalStateKey(this.config)\n if (frigadeGlobalState[globalStateKey]) {\n frigadeGlobalState[globalStateKey].onFlowStateChangeHandlers = []\n }\n }\n }\n\n /**\n * @ignore\n */\n private async init(config: FrigadeConfig): Promise<void> {\n this.updateConfig({\n ...this.config,\n ...config,\n })\n\n if (!this.config.userId && this.config.generateGuestId === false) {\n return\n }\n\n this.initPromise = (async () => {\n if (!this.config.__readOnly) {\n if (this.config.userId?.startsWith(GUEST_PREFIX)) {\n // do nothing\n } else if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n userProperties: this.config.userProperties,\n groupProperties: this.config.groupProperties,\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userProperties: this.config.userProperties,\n })\n }\n }\n await this.refreshStateFromAPI()\n })()\n\n return this.initPromise\n }\n\n /**\n * Set the current user.\n * @param userId\n * @param properties\n */\n public async identify(userId: string, properties?: PropertyPayload): Promise<void> {\n await this.updateConfig({ ...this.config, userId })\n await this.initIfNeeded()\n await this.session({\n userId: this.config.userId,\n userProperties: properties,\n })\n await this.resync()\n }\n\n /**\n * Set the group for the current user.\n * @param groupId\n * @param properties\n */\n public async group(groupId?: string, properties?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n this.updateConfig({ ...this.config, groupId })\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupProperties: properties,\n })\n await this.resync()\n }\n\n /**\n * Track an event for the current user (and group if set).\n * @param event\n * @param properties\n */\n public async track(event: string, properties?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n if (!event) {\n console.error('Event name is required to track an event')\n return\n }\n if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupEvents: [\n {\n event,\n properties,\n },\n ],\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n }\n await this.resync()\n }\n\n /**\n * @ignore\n */\n private async session(sessionDTO: SessionDTO) {\n await this.fetch('/v1/public/sessions', {\n method: 'POST',\n body: JSON.stringify(sessionDTO),\n })\n }\n\n /**\n * @ignore\n */\n public isReady(): boolean {\n return Boolean(this.config.__instanceId && this.config.apiKey && this.initPromise)\n }\n\n /**\n * Get a Flow by its ID.\n * @param flowId\n */\n public async getFlow(flowId: string) {\n await this.initIfNeeded()\n\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n await this.initIfNeeded()\n return this.flows\n }\n\n public async getCollection(collectionId: string) {\n await this.initIfNeeded()\n const collection = this.getGlobalState().collections.getRule(collectionId)\n\n if (collection == null) {\n return undefined\n }\n\n const enrichedFlows = await Promise.all(\n collection.flows.map(async (item) => ({\n ...item,\n flow: await this.getFlow(item.flowId),\n }))\n )\n\n collection.flows = enrichedFlows\n\n return collection as EnrichedRule\n }\n\n public async getCollections() {\n await this.initIfNeeded()\n const collections = this.getGlobalState().collections.getRules()\n\n if (collections == null) {\n return undefined\n }\n\n return collections\n }\n\n /**\n * Reload the current state of the flows by calling the Frigade API.\n * This will trigger all event handlers.\n * @param config optional config to use when reloading. If not passed, the current config will be used.\n */\n public async reload(config?: FrigadeConfig) {\n resetAllLocalStorage()\n clearCache()\n if (config) {\n await this.updateConfig(config)\n this.mockFlowStates(getGlobalStateKey(this.config))\n }\n this.initPromise = null\n await this.init(this.config)\n // Trigger all event handlers\n this.flows.forEach((flow) => {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n })\n }\n\n private async resync() {\n await this.refreshStateFromAPI()\n }\n\n /**\n * Event handler that captures all changes that happen to the state of the Flows.\n * @param handler\n */\n public async onStateChange(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers.push(handler)\n }\n\n /**\n * Returns true if the JS SDK failed to connect to the Frigade API.\n */\n hasFailedToLoad() {\n return this.hasFailed\n }\n\n /**\n * Removes the given handler from the list of event handlers.\n * @param handler\n */\n public async removeStateChangeHandler(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== handler)\n }\n\n /**\n * @ignore\n */\n private async initIfNeeded() {\n if (this.initPromise) {\n return this.initPromise\n } else {\n return this.init(this.config)\n }\n }\n\n /**\n * @ignore\n */\n private async refreshStateFromAPI(): Promise<void> {\n const globalStateKey = getGlobalStateKey(this.config)\n\n if (!frigadeGlobalState[globalStateKey]) {\n const that = this\n\n let validator = {\n set: function (target: any, key: any, value: any) {\n if (target[key]) {\n const previousState = target[key] as StatefulFlow\n const newState = value as StatefulFlow\n if (JSON.stringify(previousState) !== JSON.stringify(newState)) {\n that.triggerEventHandlers(newState, previousState)\n }\n }\n\n target[key] = value\n return true\n },\n }\n\n frigadeGlobalState[globalStateKey] = {\n refreshStateFromAPI: async () => {},\n collections: new Rules(new Map()),\n flowStates: new Proxy({}, validator),\n onFlowStateChangeHandlerWrappers: new Map(),\n onStepStateChangeHandlerWrappers: new Map(),\n onFlowStateChangeHandlers: [],\n previousFlows: new Map(),\n variables: {},\n config: this.config,\n currentUrl: isWeb() ? window.location.href : '',\n }\n\n if (this.config.__readOnly && this.config.__flowStateOverrides) {\n this.mockFlowStates(globalStateKey)\n\n return\n }\n\n frigadeGlobalState[globalStateKey].refreshStateFromAPI = async (\n overrideFlowStateRaw?: FlowStates\n ) => {\n if (this.config.__readOnly) {\n return\n }\n\n const flowStateRaw: FlowStates = overrideFlowStateRaw\n ? overrideFlowStateRaw\n : await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n context: getContext(this.getGlobalState().currentUrl),\n } as FlowStateDTO),\n })\n\n const rulesData: RulesList = new Map()\n\n flowStateRaw.collections?.computedOrder?.forEach(\n ({ allowedComponents, collectionId, collectionType, flowId, visible }) => {\n const currentRule: Rule = rulesData.get(collectionId) ?? {\n allowedComponents,\n collectionType,\n flows: [],\n }\n\n currentRule.flows.push({\n flowId,\n visible,\n })\n\n rulesData.set(collectionId, currentRule)\n }\n )\n\n frigadeGlobalState[globalStateKey].collections.ingestRulesData(rulesData)\n\n if (flowStateRaw && flowStateRaw.eligibleFlows) {\n flowStateRaw.eligibleFlows.forEach((statefulFlow) => {\n frigadeGlobalState[globalStateKey].flowStates[statefulFlow.flowSlug] = statefulFlow\n if (!this.flows.find((flow) => flow.id == statefulFlow.flowSlug)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: statefulFlow.flowSlug,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == statefulFlow.flowSlug) {\n flow.resyncState(statefulFlow)\n }\n })\n }\n })\n this.hasFailed = false\n } else {\n this.hasFailed = true\n }\n }\n }\n\n await frigadeGlobalState[globalStateKey].refreshStateFromAPI()\n }\n\n /**\n * @ignore\n */\n private mockFlowStates(globalStateKey: string) {\n Object.keys(this.config.__flowStateOverrides).forEach((flowId) => {\n frigadeGlobalState[globalStateKey].flowStates[flowId] =\n this.config.__flowStateOverrides[flowId]\n\n if (!this.flows.find((flow) => flow.id == flowId)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: flowId,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == flowId) {\n flow.resyncState(this.config.__flowStateOverrides[flowId])\n }\n })\n }\n })\n }\n\n /**\n * @ignore\n */\n private async updateConfig(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n if (frigadeGlobalState[getGlobalStateKey(this.config)]) {\n this.getGlobalState().config = this.config\n }\n }\n\n /**\n * @ignore\n */\n private async triggerEventHandlers(newState: StatefulFlow, previousState?: StatefulFlow) {\n if (newState) {\n this.flows.forEach((flow) => {\n if (flow.id == previousState.flowSlug) {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n flow.resyncState(newState)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n }\n })\n }\n }\n\n /**\n * @ignore\n */\n async batchRegister(flowIds: RulesRegistryBatch) {\n const flowIdsWithWrappedCallbacks = flowIds.map(async ([flowId, callback]) => {\n const currentFlow = await this.getFlow(flowId)\n const wrappedCallback = (visible: boolean) => {\n const prevFlow = this.getGlobalState().previousFlows.get(flowId)\n\n if (prevFlow?.isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(currentFlow, prevFlow)\n this.getGlobalState().previousFlows.set(flowId, cloneFlow(currentFlow))\n })\n }\n\n callback?.(visible)\n }\n\n return [flowId, wrappedCallback] as RulesRegistryBatch[number]\n })\n\n Promise.all(flowIdsWithWrappedCallbacks).then((results) => {\n this.getGlobalState().collections.batchRegister(results)\n })\n }\n}\n","import type { Flow } from './flow'\n\nexport enum TriggerType {\n MANUAL = 'MANUAL',\n AUTOMATIC = 'AUTOMATIC',\n}\n\nexport enum FlowStatus {\n DRAFT = 'DRAFT',\n ACTIVE = 'ACTIVE',\n ARCHIVED = 'ARCHIVED',\n}\n\nexport type StepAction =\n | 'flow.back'\n | 'flow.complete'\n | 'flow.forward'\n | 'flow.restart'\n | 'flow.skip'\n | 'flow.start'\n | 'step.complete'\n | 'step.reset'\n | 'step.start'\n | false\n\nexport type PropertyPayload = Record<string, any>\n\nexport interface FlowStep extends StatefulStep {\n /**\n * Order of the step in the Flow.\n */\n order: number\n\n /**\n * Name of the step when shown in a list view.\n */\n stepName?: string\n\n /**\n * Title of the step.\n */\n title?: string\n\n /**\n * Subtitle of the step.\n */\n subtitle?: string\n\n /**\n * Config for the primary button in this step\n */\n primaryButton?: {\n /**\n * Primary button action. (defaults to step.complete)\n */\n action?: StepAction\n\n /**\n * Primary button URI target (defaults to _self).\n */\n target?: string\n\n /**\n * Primary button title. If omitted, the primary button will not be shown.\n */\n title?: string\n\n /**\n * Primary button URI.\n */\n uri?: string\n }\n\n /**\n * @deprecated Use primaryButton.title instead\n * @description Primary button title. If omitted, the primary button will not be shown.\n */\n primaryButtonTitle?: string\n\n /**\n * @deprecated Use primaryButton.uri instead\n * @description Primary button URI.\n */\n primaryButtonUri?: string\n\n /**\n * @deprecated Use primaryButton.target instead\n * @description Primary button URI target (defaults to _self).\n */\n primaryButtonUriTarget?: string\n\n /**\n * Config for the secondary button in this step\n */\n secondaryButton?: {\n /**\n * Secondary button action. (defaults to step.complete)\n */\n action?: StepAction\n\n /**\n * Secondary button URI target (defaults to _self).\n */\n target?: string\n\n /**\n * Secondary button title. If omitted, the secondary button will not be shown.\n */\n title?: string\n\n /**\n * Secondary button URI.\n */\n uri?: string\n }\n\n /**\n * @deprecated Use secondaryButton.title instead\n * @description Secondary button title. If omitted, the secondary button will not be shown.\n */\n secondaryButtonTitle?: string\n\n /**\n * @deprecated Use secondaryButton.uri instead\n * @description Secondary button URI.\n */\n secondaryButtonUri?: string\n\n /**\n * @deprecated Use secondaryButton.target instead\n * @description Secondary button URI target (defaults to _self)\n */\n secondaryButtonUriTarget?: string\n\n /**\n * Text on button if a back button is present.\n */\n backButtonTitle?: string\n\n /**\n * If true, the step will be marked as completed when the secondary button is clicked.\n */\n skippable?: boolean\n\n /**\n * Video url to be shown for components supporting video.\n */\n videoUri?: string\n\n /**\n * Image url to be shown for components supporting image.\n */\n imageUri?: string | null\n\n /**\n * Automatically mark the step as completed when the primary button is clicked. Default is false.\n */\n autoMarkCompleted?: boolean\n\n /**\n * @ignore\n */\n props?: any\n /**\n * Criteria that needs to be met for the step to complete.\n * Completion criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be completed.\n */\n completionCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to start.\n * Start criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be started.\n */\n startCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to be visible.\n * Visibility criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be visible.\n */\n visibilityCriteria?: string\n\n /**\n * Progress if the step is tied to another Frigade Flow through completionCriteria.\n */\n progress?: number\n\n /**\n * Whether the step is dismissible (for instance, tooltips or other non-essential steps).\n */\n dismissible?: boolean\n\n /**\n * Any other additional props defined in the YAML config.\n */\n [x: string | number | symbol]: unknown\n\n /**\n * Marks the step started.\n */\n start: (properties?: PropertyPayload) => Promise<void>\n\n /**\n * Marks the step completed.\n * @param optimistic If true, the step will be marked as completed without waiting for the API and validation of any targeting rules.\n */\n complete: (properties?: PropertyPayload, optimistic?: boolean) => Promise<void>\n\n /**\n * Resets the step (useful for undoing a finished step).\n */\n reset: () => Promise<void>\n\n /**\n * Event handler called when this step's state changes.\n */\n onStateChange: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Removes the given callback from the list of event handlers.\n */\n removeStateChangeHandler: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Reference to this step's parent Flow\n */\n flow: Flow\n}\n\nexport interface FrigadeConfig {\n /**\n * Frigade API key. You can find your API key in the Frigade Dashboard under \"Developer\".\n */\n apiKey?: string\n /**\n * API url to use for all requests. Defaults to https://api.frigade.com\n */\n apiUrl?: string\n\n /**\n * User ID to use for all requests. If not provided, a Guest ID will be generated.\n */\n userId?: string\n\n /**\n * Group ID (organization) to use for all requests.\n */\n groupId?: string\n\n /**\n * Optional user properties to send to the API.\n */\n userProperties?: PropertyPayload\n\n /**\n * Optional group properties to send to the API.\n */\n groupProperties?: PropertyPayload\n\n /**\n * Whether to generate a Guest ID and session if no userId is not provided on initialization.\n * If set to false, Frigade will not initialize until a userId is provided via `frigade.identify()`.\n *\n * Defaults to true.\n */\n generateGuestId?: boolean\n\n /**\n * Whether to sync state with Frigade on URL or focus change. Defaults to true.\n */\n syncOnWindowUpdates?: boolean\n\n /**\n * @ignore Internal use only.\n * If enabled, Frigade will not send any data to the API. A user's state will be reset on page refresh.\n */\n __readOnly?: boolean\n\n /**\n * @ignore Internal use only.\n * Map of Flow ID to Flow State for all flows in the app that should be mocked.\n */\n __flowStateOverrides?: Record<string, StatefulFlow>\n\n /**\n * @ignore Internal use only.\n */\n __instanceId?: string\n}\n\nexport interface StatefulStep {\n id: string\n $state: {\n completed: boolean\n started: boolean\n visible: boolean\n blocked: boolean\n lastActionAt?: Date\n }\n // allow any other properties\n [key: string]: any\n}\n\nexport interface StatefulFlow {\n flowSlug: string\n flowName: string\n flowType: FlowType\n data: {\n steps: StatefulStep[]\n // allow any other properties\n [key: string]: any\n }\n $state: {\n currentStepId: string\n currentStepIndex: number\n completed: boolean\n started: boolean\n skipped: boolean\n visible: boolean\n lastActionAt?: Date\n }\n}\n\nexport enum CollectionType {\n CUSTOM = 'CUSTOM',\n DEFAULT = 'DEFAULT',\n}\n\nexport interface ComputedCollection {\n collectionId: string\n flowId: string\n visible: boolean\n allowedComponents: []\n collectionType: CollectionType\n}\n\nexport interface CollectionMetadata {\n computedOrder: ComputedCollection[]\n}\n\nexport interface FlowStates {\n eligibleFlows: StatefulFlow[]\n ineligibleFlows: string[]\n collections?: CollectionMetadata\n}\n\nexport enum FlowType {\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}\n\nexport type FlowActionType =\n | 'STARTED_STEP'\n | 'COMPLETED_STEP'\n | 'NOT_STARTED_STEP'\n | 'STARTED_FLOW'\n | 'COMPLETED_FLOW'\n | 'SKIPPED_FLOW'\n | 'NOT_STARTED_FLOW'\n\nexport interface FlowStateDTO {\n userId: string\n groupId?: string\n flowSlug?: string\n stepId?: string\n data?: any\n actionType?: FlowActionType\n createdAt?: Date\n context?: FlowStateContext\n}\n\nexport interface FlowStateContext {\n url?: string\n userAgent?: string\n}\n\nexport interface TrackingEvent {\n event: string\n properties?: PropertyPayload\n}\n\nexport interface SessionDTO {\n userId: string\n groupId?: string\n userProperties?: PropertyPayload\n userEvents?: TrackingEvent[]\n groupProperties?: PropertyPayload\n groupEvents?: TrackingEvent[]\n linkGuestId?: string\n}\n"],"mappings":";ooBAAO,IAAMA,EAAiB,SCC9B,OAAS,MAAMC,MAAc,OCuBtB,IAAIC,EAA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,CAEL,CAAC,CAEL,GAKM,cAAc+B,EAA6B,QAAA9C,EAAA,sBAC/C,IAAM+C,EAA8BD,EAAQ,IAAWE,GAAuBhD,EAAA,MAAvBgD,GAAuB,UAAvB,CAAClC,EAAQmC,CAAQ,EAAM,CAC5E,IAAMC,EAAc,MAAM,KAAK,QAAQpC,CAAM,EAe7C,MAAO,CAACA,EAdiB4B,GAAqB,CAC5C,IAAMS,EAAW,KAAK,eAAe,EAAE,cAAc,IAAIrC,CAAM,GAE3DqC,GAAA,YAAAA,EAAU,aAAcT,GAE1B,KAAK,eAAe,EAAE,0BAA0B,QAASnB,GAAY,CACnEA,EAAQ2B,EAAaC,CAAQ,EAC7B,KAAK,eAAe,EAAE,cAAc,IAAIrC,EAAQW,EAAUyB,CAAW,CAAC,CACxE,CAAC,EAGHD,GAAA,MAAAA,EAAWP,EACb,CAE+B,CACjC,EAAC,EAED,QAAQ,IAAIK,CAA2B,EAAE,KAAMK,GAAY,CACzD,KAAK,eAAe,EAAE,YAAY,cAAcA,CAAO,CACzD,CAAC,CACH,GACF,EC5gBO,IAAKC,OACVA,EAAA,OAAS,SACTA,EAAA,UAAY,YAFFA,OAAA,IAKAC,OACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SACTA,EAAA,SAAW,WAHDA,OAAA,IAkVL,IAAKC,OACVA,EAAA,aAAe,eACfA,EAAA,UAAY,YACZA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,QAAU,UACVA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,aAAe,eACfA,EAAA,WAAa,aACbA,EAAA,OAAS,SACTA,EAAA,KAAO,OAXGA,OAAA","names":["VERSION_NUMBER","uuidv4","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","filteredConfig","_","v","__spreadValues","path","options","__async","getEmptyResponse","gracefulFetch","getHeaders","globalStateKey","getGlobalStateKey","frigadeGlobalState","Flow","Fetchable","config","id","visible","overrideStatefulFlow","_a","_b","_c","statefulFlow","step","index","stepObj","existingStep","key","__spreadProps","__spreadValues","newSteps","properties","__async","thisStep","copy","clone","STARTED_STEP","optimistic","isLastStep","COMPLETED_STEP","NOT_STARTED_STEP","handler","wrapperHandler","flow","previousStep","h","STARTED_FLOW","COMPLETED_FLOW","SKIPPED_FLOW","nextStep","NOT_STARTED_FLOW","currentStep","previousFlow","variables","replaceVariables","str","matches","match","variable","action","data","stepId","date","flowStatesRaw","getContext","callback","prevFlow","cloneFlow","NOT_STARTED_STEP","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","GUEST_KEY","GUEST_PREFIX","GET_CACHE_PREFIX","LOCAL_STORAGE_PREFIX","cloneFlow","flow","Flow","clone","obj","getHeaders","apiKey","VERSION_NUMBER","getLocalStorage","key","isWeb","setLocalStorage","value","clearCache","frigadeGlobalState","key","GET_CACHE_PREFIX","resetAllLocalStorage","isWeb","LOCAL_STORAGE_PREFIX","CallQueue","call","now","item","callQueue","gracefulFetch","url","options","__async","_a","getEmptyResponse","lastCallDataKey","response","error","body","e","generateGuestId","guestId","getLocalStorage","GUEST_KEY","GUEST_PREFIX","uuidv4","setLocalStorage","isWeb","getContext","currentUrl","Rules","rulesData","ruleId","rule","flowId","callback","registeredFlow","flowInRules","item","visibleAPIOverride","otherFlowId","otherId","_a","otherVisible","otherVisited","flowIds","visible","Frigade","Fetchable","apiKey","config","__spreadValues","__async","isWeb","event","e","globalStateKey","getGlobalStateKey","frigadeGlobalState","_a","GUEST_PREFIX","userId","properties","__spreadProps","groupId","sessionDTO","flowId","flow","collectionId","collection","enrichedFlows","item","collections","resetAllLocalStorage","clearCache","handler","lastFlow","cloneFlow","h","that","validator","target","key","value","previousState","newState","Rules","overrideFlowStateRaw","_b","flowStateRaw","getContext","rulesData","allowedComponents","collectionType","visible","currentRule","statefulFlow","Flow","flowIds","flowIdsWithWrappedCallbacks","_0","callback","currentFlow","prevFlow","results","TriggerType","FlowStatus","FlowType"]}
|