@frigade/js 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -92,6 +92,19 @@ await frigade.track('EVENT_NAME', {
92
92
  })
93
93
  ```
94
94
 
95
+ #### Event handlers
96
+ ```js
97
+ // This callback will be called when a the current user/group changes state in the flow
98
+ const callback = (updatedFlow, previousFlow) => {
99
+ console.log('Flow state changed:', flow.isCompleted)
100
+ console.log('Step state changed:', flow.steps['STEP_ID'].isCompleted)
101
+ };
102
+
103
+ frigade.onFlowStateChange(callback);
104
+ // To remove the callback use:
105
+ frigade.removeOnFlowStateChangeHandler(callback);
106
+ ```
107
+
95
108
  ## Cross-platform support
96
109
 
97
110
  All non-UI related functionality of the SDK works in all JavaScript environments (Node.js, browser, React Native, etc.).
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- var J=Object.create;var m=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var M=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty;var H=(e,s)=>{for(var t in s)m(e,t,{get:s[t],enumerable:!0})},P=(e,s,t,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let a of K(s))!$.call(e,a)&&a!==t&&m(e,a,{get:()=>s[a],enumerable:!(i=W(s,a))||i.enumerable});return e};var z=(e,s,t)=>(t=e!=null?J(M(e)):{},P(s||!e||!e.__esModule?m(t,"default",{value:e,enumerable:!0}):t,e)),k=e=>P(m({},"__esModule",{value:!0}),e);var X={};H(X,{Flow:()=>w,Frigade:()=>b});module.exports=k(X);var C="0.1.2";var A=z(require("cross-fetch"),1),L=require("uuid");var T="COMPLETED_FLOW",R="SKIPPED_FLOW",I="STARTED_FLOW",N="NOT_STARTED_FLOW",g="COMPLETED_STEP",h="STARTED_STEP",j="frigade-last-call-at-",B="frigade-last-call-data-",U="frigade-guest-key",V="guest_";function x(e){return{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Frigade-SDK-Version":C,"X-Frigade-SDK-Platform":"Javascript"}}}function E(e){return window&&window.localStorage?window.localStorage.getItem(e):null}function _(e,s){window&&window.localStorage&&window.localStorage.setItem(e,s)}function v(){window&&window.localStorage&&Object.keys(window.localStorage).forEach(e=>{e.startsWith("frigade-")&&window.localStorage.removeItem(e)})}async function G(e,s){let t=j+e,i=B+e;if(window&&window.localStorage&&s&&s.body&&s.method==="POST"){let o=E(t),l=E(i);if(o&&l&&l==s.body){let f=new Date(o);if(new Date().getTime()-f.getTime()<1e3)return y()}_(t,new Date().toISOString()),_(i,s.body)}let a;try{a=await(0,A.default)(e,s)}catch(o){return y(o)}return a?a.staus>=400?y(a.statusText):a.json():y()}function y(e){return e&&console.log("Call to Frigade failed",e),{json:()=>({})}}function O(){if(typeof window<"u"&&typeof window.localStorage<"u"){let e=E(U);return e||(e=`${V}${(0,L.v4)()}`,window.localStorage.setItem(U,e)),e}}var n={};function d(e){return`${e.__instanceId}-${e.apiKey}:${e.userId??""}:${e.organizationId??""}`}var p=class{constructor(s){this.config={apiKey:"",apiUrl:"//api.frigade.com/v1/public",userId:O(),__instanceId:Math.random().toString(36).substring(7)};this.config={...this.config,...s}}async fetch(s,t){return G(`${this.config.apiUrl}${s}`,{...t??{},...x(this.config.apiKey)})}};var w=class extends p{constructor(t,i){super(t);this.flowDataRaw=i,this.initFromRawData(i)}initFromRawData(t){let i=JSON.parse(t.data),a=i.steps??i.data??[];this.id=t.slug,this.metadata=t,this.rawData=i,this.title=this.rawData.title,this.subtitle=this.rawData.subtitle;let o=this.getUserFlowState();this.isCompleted=o.flowState==T,this.isStarted=o.flowState==I,this.isSkipped=o.flowState==R,this.steps=new Map,a.forEach((l,f)=>{let c=o.stepStates[l.id],S={...l,isCompleted:c.actionType==g,isStarted:c.actionType==h,isHidden:c.hidden,isBlocked:c.blocked,order:f};S.start=async D=>{let r=this.steps.get(l.id);if(r.isStarted||r.isCompleted)return;r.isStarted=!0;let u={...n[d(this.config)].userFlowStates[this.id]};u.stepStates[r.id].actionType=h,n[d(this.config)].userFlowStates[this.id]=u,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:r.id,data:D??{},createdAt:new Date().toISOString(),actionType:h})}),await this.refreshUserFlowState();let F=this.getUserFlowState();r.isCompleted=F.stepStates[r.id].actionType==g,r.isStarted=F.stepStates[r.id].actionType==h},S.complete=async D=>{let r=this.steps.get(l.id);if(r.isCompleted)return;r.isCompleted=!0;let u={...n[d(this.config)].userFlowStates[this.id]};u.stepStates[r.id].actionType=g,n[d(this.config)].userFlowStates[this.id]=u,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:r.id,data:D??{},createdAt:new Date().toISOString(),actionType:g})}),await this.refreshUserFlowState();let F=this.getUserFlowState();r.isCompleted=F.stepStates[r.id].actionType==g,r.isStarted=F.stepStates[r.id].actionType==h},this.steps.set(l.id,S)})}async start(t){if(this.isStarted||this.isCompleted)return;this.isStarted=!0;let i={...n[d(this.config)].userFlowStates[this.id]};i.flowState=I,n[d(this.config)].userFlowStates[this.id]=i,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:I})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async complete(t){if(this.isCompleted)return;this.isCompleted=!0;let i={...n[d(this.config)].userFlowStates[this.id]};i.flowState=T,n[d(this.config)].userFlowStates[this.id]=i,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:T})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async skip(t){await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:R})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async restart(){this.isCompleted=!1,this.isCompleted=!0,n[d(this.config)].userFlowStates[this.id]=null,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:"unknown",data:{},createdAt:new Date().toISOString(),actionType:N})}),await this.refreshUserFlowState()}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){let t=this.getUserFlowState(),a=Array.from(this.steps.keys()).find(o=>this.steps.get(o).isCompleted===!1)??Array.from(this.steps.keys())[0];return this.steps.get(a)}getNumberOfCompletedSteps(){return Array.from(this.steps.values()).filter(t=>t.isCompleted).length}getUserFlowState(){return n[d(this.config)].userFlowStates[this.id]}async refreshUserFlowState(){await n[d(this.config)].refreshUserFlowStates()}};var b=class extends p{constructor(t,i){super({apiKey:t,...i});this.flows=[];this.onFlowStateChangeHandlers=[];this.init(this.config)}async init(t){return this.config={...this.config,...t},this.initPromise=(async()=>{await this.refreshUserFlowStates(),await this.refreshFlows()})(),this.initPromise}async identify(t,i){await this.initIfNeeded(),this.config.userId=t,await this.fetch("/users",{method:"POST",body:JSON.stringify({foreignId:this.config.userId,properties:i})}),await this.refreshUserFlowStates()}async group(t,i){await this.initIfNeeded(),this.config.organizationId=t,await this.fetch("/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.organizationId,properties:i})}),await this.refreshUserFlowStates()}async track(t,i){await this.initIfNeeded(),await this.fetch("/track",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.organizationId,event:t,properties:i})})}async getFlow(t){return await this.initIfNeeded(),this.flows.find(i=>i.id==t)}async getFlows(){return await this.initIfNeeded(),this.flows}async reset(){v(),this.config.userId=O(),this.config.organizationId=void 0}onFlowStateChange(t){this.onFlowStateChangeHandlers.push(t)}removeOnFlowStateChangeHandler(t){this.onFlowStateChangeHandlers=this.onFlowStateChangeHandlers.filter(i=>i!==t)}async initIfNeeded(){return this.initPromise!==null?this.initPromise:this.init(this.config)}async refreshUserFlowStates(){let t=d(this.config);if(!n[t]){let i=this,a={set:function(o,l,f){var c,S;return(o[l]&&((c=o[l])!=null&&c.flowState)&&JSON.stringify(o[l].flowState)!==JSON.stringify(f.flowState)||JSON.stringify((S=o[l])==null?void 0:S.stepStates)!==JSON.stringify(f.stepStates)||JSON.stringify(o[l].shouldTrigger)!==JSON.stringify(f.shouldTrigger))&&i.triggerEventHandlers(o[l],f),o[l]=f,!0}};n[t]={refreshUserFlowStates:async()=>{},userFlowStates:new Proxy({},a)},n[t].refreshUserFlowStates=async()=>{let o=await this.fetch(`/userFlowStates?foreignUserId=${this.config.userId}${this.config.organizationId?`&foreignUserGroupId=${this.config.organizationId}`:""}`);o&&o.data&&o.data.forEach(f=>{n[t].userFlowStates[f.flowId]=f})}}await n[t].refreshUserFlowStates()}async refreshFlows(){this.flows=[];let t=await this.fetch("/flows");t&&t.data&&t.data.forEach(a=>{this.flows.push(new w(this.config,a))})}triggerEventHandlers(t,i){t&&t.flowState!==i.flowState&&this.flows.forEach(a=>{a.id==i.flowId&&this.onFlowStateChangeHandlers.forEach(o=>{o(a,i.flowState,t==null?void 0:t.flowState)})})}};0&&(module.exports={Flow,Frigade});
2
+ var k=Object.create;var O=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty;var X=(e,s)=>{for(var t in s)O(e,t,{get:s[t],enumerable:!0})},N=(e,s,t,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of V(s))!B.call(e,r)&&r!==t&&O(e,r,{get:()=>s[r],enumerable:!(i=z(s,r))||i.enumerable});return e};var Y=(e,s,t)=>(t=e!=null?k(j(e)):{},N(s||!e||!e.__esModule?O(t,"default",{value:e,enumerable:!0}):t,e)),q=e=>N(O({},"__esModule",{value:!0}),e);var et={};X(et,{Flow:()=>f,Frigade:()=>E});module.exports=q(et);var L="0.1.4";var J=Y(require("cross-fetch"),1),G=require("uuid");var u="COMPLETED_FLOW",U="SKIPPED_FLOW",F="STARTED_FLOW",W="NOT_STARTED_FLOW",S="COMPLETED_STEP",g="STARTED_STEP",Q="frigade-last-call-at-",Z="frigade-last-call-data-",x="frigade-guest-key",tt="guest_";function m(e){return JSON.parse(JSON.stringify(e))}function K(e){return{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Frigade-SDK-Version":L,"X-Frigade-SDK-Platform":"Javascript"}}}function _(e){return window&&window.localStorage?window.localStorage.getItem(e):null}function M(e,s){window&&window.localStorage&&window.localStorage.setItem(e,s)}function $(){window&&window.localStorage&&Object.keys(window.localStorage).forEach(e=>{e.startsWith("frigade-")&&window.localStorage.removeItem(e)})}async function H(e,s){let t=Q+e,i=Z+e;if(window&&window.localStorage&&s&&s.body&&s.method==="POST"){let o=_(t),l=_(i);if(o&&l&&l==s.body){let c=new Date(o);if(new Date().getTime()-c.getTime()<1e3)return b()}M(t,new Date().toISOString()),M(i,s.body)}let r;try{r=await(0,J.default)(e,s)}catch(o){return b(o)}return r?r.staus>=400?b(r.statusText):r.json():b()}function b(e){return e&&console.log("Call to Frigade failed",e),{json:()=>({})}}function D(){if(typeof window<"u"&&typeof window.localStorage<"u"){let e=_(x);return e||(e=`${tt}${(0,G.v4)()}`,window.localStorage.setItem(x,e)),e}}var n={};function d(e){return`${e.__instanceId}-${e.apiKey}:${e.userId??""}:${e.organizationId??""}`}var h=class{constructor(s){this.config={apiKey:"",apiUrl:"//api.frigade.com/v1/public",userId:D(),__instanceId:Math.random().toString(36).substring(7)};this.config={...this.config,...s}}async fetch(s,t){return H(`${this.config.apiUrl}${s}`,{...t??{},...K(this.config.apiKey)})}};var f=class extends h{constructor(t,i){super(t);this.isVisible=!1;this.flowDataRaw=i,this.initFromRawData(i)}initFromRawData(t){let i=JSON.parse(t.data),r=i.steps??i.data??[];this.id=t.slug,this.metadata=t,this.rawData=i,this.title=this.rawData.title,this.subtitle=this.rawData.subtitle;let o=this.getUserFlowState();this.isCompleted=o.flowState==u,this.isStarted=o.flowState==F,this.isSkipped=o.flowState==U;let l=this.isCompleted||this.isSkipped,c=t.targetingLogic&&o.shouldTrigger===!1;this.isVisible=!l&&!c,this.steps=new Map,r.forEach((p,C)=>{let y=o.stepStates[p.id],R={...p,isCompleted:y.actionType==S,isStarted:y.actionType==g,isHidden:y.hidden,isBlocked:y.blocked,order:C};R.start=async P=>{let a=this.steps.get(p.id);if(a.isStarted||a.isCompleted)return;a.isStarted=!0;let T=m(n[d(this.config)].userFlowStates[this.id]);T.stepStates[a.id].actionType=g,T.lastStepId=a.id,n[d(this.config)].userFlowStates[this.id]=T,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:a.id,data:P??{},createdAt:new Date().toISOString(),actionType:g})}),await this.refreshUserFlowState();let w=this.getUserFlowState();a.isCompleted=w.stepStates[a.id].actionType==S,a.isStarted=w.stepStates[a.id].actionType==g},R.complete=async P=>{let a=this.steps.get(p.id);if(a.isCompleted)return;let w=this.getNumberOfCompletedSteps()+1==this.steps.size;a.isCompleted=!0,this.isStarted=!0;let I=m(n[d(this.config)].userFlowStates[this.id]);I.stepStates[a.id].actionType=S,I.flowState=w?u:F;let v=Array.from(this.steps.keys())[C+1];v&&(I.lastStepId=v),w&&this.optimisticallyMarkFlowCompleted(),n[d(this.config)].userFlowStates[this.id]=I,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:a.id,data:P??{},createdAt:new Date().toISOString(),actionType:S})}),w?await this.complete():await this.refreshUserFlowState();let A=this.getUserFlowState();a.isCompleted=A.stepStates[a.id].actionType==S,a.isStarted=A.stepStates[a.id].actionType==g},this.steps.set(p.id,R)})}async start(t){if(this.isStarted||this.isCompleted)return;this.isStarted=!0;let i=m(n[d(this.config)].userFlowStates[this.id]);i.flowState=F,n[d(this.config)].userFlowStates[this.id]=i,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:F})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async complete(t){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:u})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw))}optimisticallyMarkFlowCompleted(){this.isStarted=!0,this.isCompleted=!0;let t=m(n[d(this.config)].userFlowStates[this.id]);t.flowState=u,n[d(this.config)].userFlowStates[this.id]=t,this.isVisible=!1}async skip(t){await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:U})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async restart(){this.isCompleted=!1,this.isCompleted=!0,n[d(this.config)].userFlowStates[this.id]=null,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:"unknown",data:{},createdAt:new Date().toISOString(),actionType:W})}),await this.refreshUserFlowState()}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){let i=Array.from(this.steps.keys()).find(r=>this.steps.get(r).isCompleted===!1)??Array.from(this.steps.keys())[0];return this.steps.get(i)}getNumberOfCompletedSteps(){return Array.from(this.steps.values()).filter(t=>t.isCompleted).length}getUserFlowState(){return n[d(this.config)].userFlowStates[this.id]}async refreshUserFlowState(){await n[d(this.config)].refreshUserFlowStates()}};var E=class extends h{constructor(t,i){super({apiKey:t,...i});this.flows=[];this.onFlowStateChangeHandlers=[];this.previousFlows=new Map;this.init(this.config)}async init(t){return this.config={...this.config,...t},this.initPromise=(async()=>{await this.refreshUserFlowStates(),await this.refreshFlows()})(),this.initPromise}async identify(t,i){await this.initIfNeeded(),this.config.userId=t,await this.fetch("/users",{method:"POST",body:JSON.stringify({foreignId:this.config.userId,properties:i})}),await this.refreshUserFlowStates()}async group(t,i){await this.initIfNeeded(),this.config.organizationId=t,await this.fetch("/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.organizationId,properties:i})}),await this.refreshUserFlowStates()}async track(t,i){await this.initIfNeeded(),await this.fetch("/track",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.organizationId,event:t,properties:i})})}async getFlow(t){return await this.initIfNeeded(),this.flows.find(i=>i.id==t)}async getFlows(){return await this.initIfNeeded(),this.flows}async reset(){$(),this.config.userId=D(),this.config.organizationId=void 0}onFlowStateChange(t){this.onFlowStateChangeHandlers.push(t)}removeOnFlowStateChangeHandler(t){this.onFlowStateChangeHandlers=this.onFlowStateChangeHandlers.filter(i=>i!==t)}async initIfNeeded(){return this.initPromise!==null?this.initPromise:this.init(this.config)}async refreshUserFlowStates(){let t=d(this.config);if(!n[t]){let i=this,r={set:function(o,l,c){return o[l]&&o[l].flowState&&(JSON.stringify(o[l].flowState)!==JSON.stringify(c.flowState)||JSON.stringify(o[l].stepStates)!==JSON.stringify(c.stepStates)||JSON.stringify(o[l].shouldTrigger)!==JSON.stringify(c.shouldTrigger))&&i.triggerEventHandlers(o[l]),o[l]=c,!0}};n[t]={refreshUserFlowStates:async()=>{},userFlowStates:new Proxy({},r)},n[t].refreshUserFlowStates=async()=>{let o=await this.fetch(`/userFlowStates?foreignUserId=${this.config.userId}${this.config.organizationId?`&foreignUserGroupId=${this.config.organizationId}`:""}`);o&&o.data&&o.data.forEach(c=>{n[t].userFlowStates[c.flowId]=c})}}await n[t].refreshUserFlowStates()}async refreshFlows(){this.flows=[];let t=await this.fetch("/flows");t&&t.data&&t.data.forEach(r=>{this.flows.push(new f(this.config,r))})}async triggerEventHandlers(t){t&&this.flows.forEach(i=>{i.id==t.flowId&&this.onFlowStateChangeHandlers.forEach(r=>{let o=this.previousFlows.get(r),l=o?o.get(i.id):void 0;r(i,l),o||this.previousFlows.set(r,new Map),this.previousFlows.get(r).set(i.id,i)})})}};0&&(module.exports={Flow,Frigade});
3
3
  //# sourceMappingURL=index.cjs.map
@@ -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/frigade.ts"],"sourcesContent":["export { Frigade } from './core/frigade'\nimport Flow from './core/flow'\n\nexport { Flow }\n","export const VERSION_NUMBER = '0.1.2'\n","import { VERSION_NUMBER } from '../core/version'\nimport fetch from 'cross-fetch'\nimport { v4 as uuidv4 } from 'uuid'\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'\nexport type StepActionType = 'STARTED_STEP' | 'COMPLETED_STEP' | 'NOT_STARTED_STEP'\nexport type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'SKIPPED_FLOW'\nconst LAST_POST_CALL_AT = 'frigade-last-call-at-'\nconst LAST_POST_CALL_DATA = 'frigade-last-call-data-'\nconst GUEST_KEY = 'frigade-guest-key'\nconst GUEST_PREFIX = 'guest_'\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 (window && window.localStorage) {\n return window.localStorage.getItem(key)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (window && window.localStorage) {\n window.localStorage.setItem(key, value)\n }\n}\n\nexport function resetAllLocalStorage() {\n if (window && window.localStorage) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith('frigade-')) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nexport async function gracefulFetch(url: string, options: any) {\n const lastCallAtKey = LAST_POST_CALL_AT + url\n const lastCallDataKey = LAST_POST_CALL_DATA + url\n if (window && window.localStorage && options && options.body && options.method === 'POST') {\n const lastCall = getLocalStorage(lastCallAtKey)\n const lastCallData = getLocalStorage(lastCallDataKey)\n if (lastCall && lastCallData && lastCallData == options.body) {\n const lastCallDate = new Date(lastCall)\n const now = new Date()\n const diff = now.getTime() - lastCallDate.getTime()\n // Throttle consecutive POST calls to 1 second\n if (diff < 1000) {\n return getEmptyResponse()\n }\n }\n setLocalStorage(lastCallAtKey, new Date().toISOString())\n setLocalStorage(lastCallDataKey, options.body)\n }\n\n let response\n try {\n response = await fetch(url, options)\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse()\n }\n\n if (response.staus >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n return response.json()\n}\n\nfunction 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 (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n window.localStorage.setItem(GUEST_KEY, guestId)\n }\n return guestId\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","import { FrigadeConfig, UserFlowState } from '../types'\n\nexport interface FrigadeGlobalState {\n refreshUserFlowStates: () => Promise<void>\n userFlowStates: Record<string, UserFlowState>\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}:${internalConfig.userId ?? ''}:${\n internalConfig.organizationId ?? ''\n }`\n}\n","import { generateGuestId, getHeaders, gracefulFetch } from './utils'\nimport { FrigadeConfig } from '../types'\n\nexport class Fetchable {\n public config: FrigadeConfig = {\n apiKey: '',\n apiUrl: '//api.frigade.com/v1/public',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(36).substring(7),\n }\n\n constructor(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n }\n\n public async fetch(path: string, options?: Record<any, any>) {\n return gracefulFetch(`${this.config.apiUrl}${path}`, {\n ...(options ?? {}),\n ...getHeaders(this.config.apiKey),\n })\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { FlowDataRaw } from './types'\nimport {\n COMPLETED_FLOW,\n COMPLETED_STEP,\n NOT_STARTED_FLOW,\n SKIPPED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { FlowStep } from './flow-step'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/Fetchable'\n\nexport default class Flow extends Fetchable {\n /**\n * THe Flow ID / slug of the flow\n */\n public id: string\n /**\n * The raw data defined in `config.yml` as a JSON decoded object\n */\n public rawData: Record<any, any>\n /**\n * Ordered map from Step ID to step data. The `steps` array in `config.yml`\n */\n public steps: Map<string, FlowStep>\n /**\n * The user-facing title of the flow, if defined at the top level of `config.yml`\n */\n public title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `config.yml`\n */\n public subtitle?: string\n /**\n * The metadata of the flow.\n */\n public metadata: FlowDataRaw\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 private flowDataRaw: FlowDataRaw\n\n constructor(config: FrigadeConfig, flowDataRaw: FlowDataRaw) {\n super(config)\n this.flowDataRaw = flowDataRaw\n this.initFromRawData(flowDataRaw)\n }\n\n private initFromRawData(flowDataRaw: FlowDataRaw) {\n const flowDataYml = JSON.parse(flowDataRaw.data)\n const steps = flowDataYml.steps ?? flowDataYml.data ?? []\n this.id = flowDataRaw.slug\n this.metadata = flowDataRaw\n this.rawData = flowDataYml\n this.title = this.rawData.title\n this.subtitle = this.rawData.subtitle\n\n const userFlowState = this.getUserFlowState()\n\n this.isCompleted = userFlowState.flowState == COMPLETED_FLOW\n this.isStarted = userFlowState.flowState == STARTED_FLOW\n this.isSkipped = userFlowState.flowState == SKIPPED_FLOW\n this.steps = new Map()\n\n steps.forEach((step, index) => {\n const userFlowStateStep = userFlowState.stepStates[step.id]\n const stepObj = {\n ...step,\n isCompleted: userFlowStateStep.actionType == COMPLETED_STEP,\n isStarted: userFlowStateStep.actionType == STARTED_STEP,\n isHidden: userFlowStateStep.hidden,\n isBlocked: userFlowStateStep.blocked,\n order: index,\n } as FlowStep\n\n stepObj.start = async (properties?: Record<string | number, any>) => {\n const currentStep = this.steps.get(step.id)\n\n if (currentStep.isStarted || currentStep.isCompleted) {\n return\n }\n\n currentStep.isStarted = true\n const clone = {\n ...frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id],\n }\n clone.stepStates[currentStep.id].actionType = STARTED_STEP\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = clone\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: currentStep.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_STEP,\n }),\n })\n\n await this.refreshUserFlowState()\n\n const updatedUserFlowState = this.getUserFlowState()\n currentStep.isCompleted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == COMPLETED_STEP\n currentStep.isStarted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == STARTED_STEP\n }\n\n stepObj.complete = async (properties?: Record<string | number, any>) => {\n const currentStep = this.steps.get(step.id)\n\n if (currentStep.isCompleted) {\n return\n }\n\n currentStep.isCompleted = true\n const clone = {\n ...frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id],\n }\n clone.stepStates[currentStep.id].actionType = COMPLETED_STEP\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = clone\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: currentStep.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_STEP,\n }),\n })\n\n await this.refreshUserFlowState()\n\n const updatedUserFlowState = this.getUserFlowState()\n currentStep.isCompleted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == COMPLETED_STEP\n currentStep.isStarted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == STARTED_STEP\n }\n\n this.steps.set(step.id, stepObj)\n })\n }\n\n /**\n * Function that marks the flow started\n */\n public async start(properties?: Record<string | number, any>) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n\n this.isStarted = true\n const clone = { ...frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] }\n clone.flowState = STARTED_FLOW\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = clone\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that marks the flow completed\n */\n public async complete(properties?: Record<string | number, any>) {\n if (this.isCompleted) {\n return\n }\n\n this.isCompleted = true\n const clone = { ...frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] }\n clone.flowState = COMPLETED_FLOW\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = clone\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_FLOW,\n }),\n })\n\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that marks the flow skipped\n */\n public async skip(properties?: Record<string | number, any>) {\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: SKIPPED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that restarts the flow/marks it not started\n */\n public async restart() {\n this.isCompleted = false\n this.isCompleted = true\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = null\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: 'unknown',\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\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 * Function that gets current step\n */\n public getCurrentStep(): FlowStep {\n // Find the userFlowState with most recent timestamp\n const userFlowState = this.getUserFlowState()\n\n // TEMP: lastStepId appears to be the last step that a flowState event was recorded for?\n // const lastStepId =\n // userFlowState?.lastStepId?.length > 0 && userFlowState?.lastStepId !== 'unknown'\n // ? userFlowState?.lastStepId\n // : undefined\n\n // TEMP: Return the lowest-ordered incomplete step in the flow\n const lastStepId = Array.from(this.steps.keys()).find(\n (key) => this.steps.get(key).isCompleted === false\n )\n\n const currentStepId = lastStepId ?? Array.from(this.steps.keys())[0]\n return this.steps.get(currentStepId)\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.isCompleted).length\n }\n\n private getUserFlowState(): UserFlowState {\n const userFlowStates = frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates\n return userFlowStates[this.id]\n }\n\n private async refreshUserFlowState() {\n await frigadeGlobalState[getGlobalStateKey(this.config)].refreshUserFlowStates()\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { generateGuestId, resetAllLocalStorage, UserFlowStatus } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowDataRaw } from './types'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/Fetchable'\n\nexport class Frigade extends Fetchable {\n private flows: Flow[] = []\n private initPromise: Promise<void>\n private onFlowStateChangeHandlers: ((\n flow: Flow,\n newState: UserFlowStatus,\n previousState: UserFlowStatus\n ) => void)[] = []\n\n constructor(apiKey: string, config?: FrigadeConfig) {\n super({\n apiKey,\n ...config,\n })\n\n this.init(this.config)\n }\n\n private async init(config: FrigadeConfig): Promise<void> {\n this.config = {\n ...this.config,\n ...config,\n }\n\n this.initPromise = (async () => {\n await this.refreshUserFlowStates()\n await this.refreshFlows()\n })()\n\n return this.initPromise\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n this.config.userId = userId\n await this.fetch('/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.config.userId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n this.config.organizationId = organizationId\n await this.fetch('/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.organizationId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n await this.fetch('/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.organizationId,\n event,\n properties,\n }),\n })\n }\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 reset() {\n resetAllLocalStorage()\n this.config.userId = generateGuestId()\n this.config.organizationId = undefined\n }\n\n public onFlowStateChange(\n handler: (flow: Flow, newState: UserFlowStatus, previousState: UserFlowStatus) => void\n ) {\n this.onFlowStateChangeHandlers.push(handler)\n }\n\n public removeOnFlowStateChangeHandler(\n handler: (flow: Flow, newState: UserFlowStatus, previousState: UserFlowStatus) => void\n ) {\n this.onFlowStateChangeHandlers = this.onFlowStateChangeHandlers.filter((h) => h !== handler)\n }\n\n private async initIfNeeded() {\n if (this.initPromise !== null) {\n return this.initPromise\n } else {\n return this.init(this.config)\n }\n }\n\n private async refreshUserFlowStates(): 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 (\n (target[key] &&\n target[key]?.flowState &&\n JSON.stringify(target[key].flowState) !== JSON.stringify(value.flowState)) ||\n JSON.stringify(target[key]?.stepStates) !== JSON.stringify(value.stepStates) ||\n JSON.stringify(target[key].shouldTrigger) !== JSON.stringify(value.shouldTrigger)\n ) {\n that.triggerEventHandlers(target[key], value)\n }\n\n target[key] = value\n return true\n },\n }\n\n frigadeGlobalState[globalStateKey] = {\n refreshUserFlowStates: async () => {},\n userFlowStates: new Proxy({}, validator),\n }\n frigadeGlobalState[globalStateKey].refreshUserFlowStates = async () => {\n const userFlowStatesRaw = await this.fetch(\n `/userFlowStates?foreignUserId=${this.config.userId}${\n this.config.organizationId ? `&foreignUserGroupId=${this.config.organizationId}` : ''\n }`\n )\n if (userFlowStatesRaw && userFlowStatesRaw.data) {\n let userFlowStates = userFlowStatesRaw.data as UserFlowState[]\n userFlowStates.forEach((userFlowState) => {\n frigadeGlobalState[globalStateKey].userFlowStates[userFlowState.flowId] = userFlowState\n })\n }\n }\n }\n\n await frigadeGlobalState[globalStateKey].refreshUserFlowStates()\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await this.fetch('/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowDatas = flowDataRaw.data as FlowDataRaw[]\n flowDatas.forEach((flowData) => {\n this.flows.push(new Flow(this.config, flowData))\n })\n }\n }\n\n private triggerEventHandlers(\n previousUserFlowState: UserFlowState,\n newUserFlowState: UserFlowState\n ) {\n if (previousUserFlowState && previousUserFlowState.flowState !== newUserFlowState.flowState) {\n this.flows.forEach((flow) => {\n if (flow.id == newUserFlowState.flowId) {\n this.onFlowStateChangeHandlers.forEach((handler) => {\n handler(flow, newUserFlowState.flowState, previousUserFlowState?.flowState)\n })\n }\n })\n }\n }\n}\n"],"mappings":";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GCAO,IAAMK,EAAiB,QCC9B,IAAAC,EAAkB,4BAClBC,EAA6B,gBAGtB,IAAMC,EAAiB,iBACjBC,EAAe,eACfC,EAAe,eACfC,EAAmB,mBACnBC,EAAiB,iBACjBC,EAAe,eAGtBC,EAAoB,wBACpBC,EAAsB,0BACtBC,EAAY,oBACZC,EAAe,SAEd,SAASC,EAAWC,EAAgB,CACzC,MAA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L,CAEQ,qBACNE,EACAC,EACA,CACID,GAAyBA,EAAsB,YAAcC,EAAiB,WAChF,KAAK,MAAM,QAASrB,GAAS,CACvBA,EAAK,IAAMqB,EAAiB,QAC9B,KAAK,0BAA0B,QAASlB,GAAY,CAClDA,EAAQH,EAAMqB,EAAiB,UAAWD,GAAA,YAAAA,EAAuB,SAAS,CAC5E,CAAC,CAEL,CAAC,CAEL,CACF","names":["src_exports","__export","Flow","Frigade","__toCommonJS","VERSION_NUMBER","import_cross_fetch","import_uuid","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","getHeaders","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","resetAllLocalStorage","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","fetch","error","generateGuestId","guestId","uuidv4","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","path","options","gracefulFetch","getHeaders","Flow","Fetchable","config","flowDataRaw","flowDataYml","steps","userFlowState","COMPLETED_FLOW","STARTED_FLOW","SKIPPED_FLOW","step","index","userFlowStateStep","stepObj","COMPLETED_STEP","STARTED_STEP","properties","currentStep","clone","frigadeGlobalState","getGlobalStateKey","updatedUserFlowState","NOT_STARTED_FLOW","currentStepId","key","Frigade","Fetchable","apiKey","config","userId","properties","organizationId","event","flowId","flow","resetAllLocalStorage","generateGuestId","handler","h","globalStateKey","getGlobalStateKey","frigadeGlobalState","that","validator","target","key","value","_a","_b","userFlowStatesRaw","userFlowState","flowDataRaw","flowData","Flow","previousUserFlowState","newUserFlowState"]}
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/frigade.ts"],"sourcesContent":["export { Frigade } from './core/frigade'\nimport Flow from './core/flow'\n\nexport { Flow }\n\nexport * from './types'\n","export const VERSION_NUMBER = '0.1.4'\n","import { VERSION_NUMBER } from '../core/version'\nimport fetch from 'cross-fetch'\nimport { v4 as uuidv4 } from 'uuid'\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'\nexport type StepActionType = 'STARTED_STEP' | 'COMPLETED_STEP' | 'NOT_STARTED_STEP'\nexport type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'SKIPPED_FLOW'\nconst LAST_POST_CALL_AT = 'frigade-last-call-at-'\nconst LAST_POST_CALL_DATA = 'frigade-last-call-data-'\nconst GUEST_KEY = 'frigade-guest-key'\nconst GUEST_PREFIX = 'guest_'\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 (window && window.localStorage) {\n return window.localStorage.getItem(key)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (window && window.localStorage) {\n window.localStorage.setItem(key, value)\n }\n}\n\nexport function resetAllLocalStorage() {\n if (window && window.localStorage) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith('frigade-')) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nexport async function gracefulFetch(url: string, options: any) {\n const lastCallAtKey = LAST_POST_CALL_AT + url\n const lastCallDataKey = LAST_POST_CALL_DATA + url\n if (window && window.localStorage && options && options.body && options.method === 'POST') {\n const lastCall = getLocalStorage(lastCallAtKey)\n const lastCallData = getLocalStorage(lastCallDataKey)\n if (lastCall && lastCallData && lastCallData == options.body) {\n const lastCallDate = new Date(lastCall)\n const now = new Date()\n const diff = now.getTime() - lastCallDate.getTime()\n // Throttle consecutive POST calls to 1 second\n if (diff < 1000) {\n return getEmptyResponse()\n }\n }\n setLocalStorage(lastCallAtKey, new Date().toISOString())\n setLocalStorage(lastCallDataKey, options.body)\n }\n\n let response\n try {\n response = await fetch(url, options)\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse()\n }\n\n if (response.staus >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n return response.json()\n}\n\nfunction 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 (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n window.localStorage.setItem(GUEST_KEY, guestId)\n }\n return guestId\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","import { FrigadeConfig, UserFlowState } from '../types'\n\nexport interface FrigadeGlobalState {\n refreshUserFlowStates: () => Promise<void>\n userFlowStates: Record<string, UserFlowState>\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}:${internalConfig.userId ?? ''}:${\n internalConfig.organizationId ?? ''\n }`\n}\n","import { generateGuestId, getHeaders, gracefulFetch } from './utils'\nimport { FrigadeConfig } from '../types'\n\nexport class Fetchable {\n public config: FrigadeConfig = {\n apiKey: '',\n apiUrl: '//api.frigade.com/v1/public',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(36).substring(7),\n }\n\n constructor(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n }\n\n public async fetch(path: string, options?: Record<any, any>) {\n return gracefulFetch(`${this.config.apiUrl}${path}`, {\n ...(options ?? {}),\n ...getHeaders(this.config.apiKey),\n })\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { FlowDataRaw } from './types'\nimport {\n clone,\n COMPLETED_FLOW,\n COMPLETED_STEP,\n NOT_STARTED_FLOW,\n SKIPPED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { FlowStep } from './flow-step'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/Fetchable'\n\nexport default class Flow extends Fetchable {\n /**\n * THe Flow ID / slug of the flow\n */\n public id: string\n /**\n * The raw data defined in `config.yml` as a JSON decoded object\n */\n public rawData: Record<any, any>\n /**\n * Ordered map from Step ID to step data. The `steps` array in `config.yml`\n */\n public steps: Map<string, FlowStep>\n /**\n * The user-facing title of the flow, if defined at the top level of `config.yml`\n */\n public title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `config.yml`\n */\n public subtitle?: string\n /**\n * The metadata of the flow.\n */\n public metadata: FlowDataRaw\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 * Whether the flow is visible to the user based on the current user/group's state\n */\n public isVisible: boolean = false\n\n private flowDataRaw: FlowDataRaw\n\n constructor(config: FrigadeConfig, flowDataRaw: FlowDataRaw) {\n super(config)\n this.flowDataRaw = flowDataRaw\n this.initFromRawData(flowDataRaw)\n }\n\n private initFromRawData(flowDataRaw: FlowDataRaw) {\n const flowDataYml = JSON.parse(flowDataRaw.data)\n const steps = flowDataYml.steps ?? flowDataYml.data ?? []\n this.id = flowDataRaw.slug\n this.metadata = flowDataRaw\n this.rawData = flowDataYml\n this.title = this.rawData.title\n this.subtitle = this.rawData.subtitle\n\n const userFlowState = this.getUserFlowState()\n\n this.isCompleted = userFlowState.flowState == COMPLETED_FLOW\n this.isStarted = userFlowState.flowState == STARTED_FLOW\n this.isSkipped = userFlowState.flowState == SKIPPED_FLOW\n const hasCompleted = this.isCompleted || this.isSkipped\n const targetingShouldHideFlow =\n flowDataRaw.targetingLogic && userFlowState.shouldTrigger === false\n this.isVisible = !hasCompleted && !targetingShouldHideFlow\n this.steps = new Map()\n\n steps.forEach((step, index) => {\n const userFlowStateStep = userFlowState.stepStates[step.id]\n const stepObj = {\n ...step,\n isCompleted: userFlowStateStep.actionType == COMPLETED_STEP,\n isStarted: userFlowStateStep.actionType == STARTED_STEP,\n isHidden: userFlowStateStep.hidden,\n isBlocked: userFlowStateStep.blocked,\n order: index,\n } as FlowStep\n\n stepObj.start = async (properties?: Record<string | number, any>) => {\n const currentStep = this.steps.get(step.id)\n\n if (currentStep.isStarted || currentStep.isCompleted) {\n return\n }\n\n currentStep.isStarted = true\n const copy = clone(\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id]\n )\n copy.stepStates[currentStep.id].actionType = STARTED_STEP\n copy.lastStepId = currentStep.id\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = copy\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: currentStep.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_STEP,\n }),\n })\n\n await this.refreshUserFlowState()\n\n const updatedUserFlowState = this.getUserFlowState()\n currentStep.isCompleted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == COMPLETED_STEP\n currentStep.isStarted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == STARTED_STEP\n }\n\n stepObj.complete = async (properties?: Record<string | number, any>) => {\n const currentStep = this.steps.get(step.id)\n\n if (currentStep.isCompleted) {\n return\n }\n\n const numberOfCompletedSteps = this.getNumberOfCompletedSteps()\n const isLastStep = numberOfCompletedSteps + 1 == this.steps.size\n\n currentStep.isCompleted = true\n this.isStarted = true\n const copy = clone(\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id]\n )\n\n copy.stepStates[currentStep.id].actionType = COMPLETED_STEP\n copy.flowState = isLastStep ? COMPLETED_FLOW : STARTED_FLOW\n\n const nextStepId = Array.from(this.steps.keys())[index + 1]\n if (nextStepId) {\n copy.lastStepId = nextStepId\n }\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = copy\n\n // if all steps are now completed, mark flow completed\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: currentStep.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_STEP,\n }),\n })\n\n if (isLastStep) {\n await this.complete()\n } else {\n await this.refreshUserFlowState()\n }\n\n const updatedUserFlowState = this.getUserFlowState()\n currentStep.isCompleted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == COMPLETED_STEP\n currentStep.isStarted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == STARTED_STEP\n }\n\n this.steps.set(step.id, stepObj)\n })\n }\n\n /**\n * Function that marks the flow started\n */\n public async start(properties?: Record<string | number, any>) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n\n this.isStarted = true\n const copy = clone(frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id])\n copy.flowState = STARTED_FLOW\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = copy\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that marks the flow completed\n */\n public async complete(properties?: Record<string | number, any>) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_FLOW,\n }),\n })\n\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n private optimisticallyMarkFlowCompleted() {\n this.isStarted = true\n this.isCompleted = true\n const copy = clone(frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id])\n copy.flowState = COMPLETED_FLOW\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = copy\n this.isVisible = false\n }\n\n /**\n * Function that marks the flow skipped\n */\n public async skip(properties?: Record<string | number, any>) {\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: SKIPPED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that restarts the flow/marks it not started\n */\n public async restart() {\n this.isCompleted = false\n this.isCompleted = true\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = null\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: 'unknown',\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\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 * Function that gets current step\n */\n public getCurrentStep(): FlowStep {\n const lastStepId = Array.from(this.steps.keys()).find(\n (key) => this.steps.get(key).isCompleted === false\n )\n\n const currentStepId = lastStepId ?? Array.from(this.steps.keys())[0]\n return this.steps.get(currentStepId)\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.isCompleted).length\n }\n\n private getUserFlowState(): UserFlowState {\n const userFlowStates = frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates\n return userFlowStates[this.id]\n }\n\n private async refreshUserFlowState() {\n await frigadeGlobalState[getGlobalStateKey(this.config)].refreshUserFlowStates()\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { generateGuestId, resetAllLocalStorage } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowDataRaw } from './types'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/Fetchable'\n\nexport class Frigade extends Fetchable {\n private flows: Flow[] = []\n private initPromise: Promise<void>\n private onFlowStateChangeHandlers: ((flow: Flow, previousFlow?: Flow) => void)[] = []\n private previousFlows: Map<(flow: Flow, previousFlow: Flow) => void, Map<string, Flow>> =\n new Map()\n\n constructor(apiKey: string, config?: FrigadeConfig) {\n super({\n apiKey,\n ...config,\n })\n\n this.init(this.config)\n }\n\n private async init(config: FrigadeConfig): Promise<void> {\n this.config = {\n ...this.config,\n ...config,\n }\n\n this.initPromise = (async () => {\n await this.refreshUserFlowStates()\n await this.refreshFlows()\n })()\n\n return this.initPromise\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n this.config.userId = userId\n await this.fetch('/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.config.userId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n this.config.organizationId = organizationId\n await this.fetch('/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.organizationId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n await this.fetch('/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.organizationId,\n event,\n properties,\n }),\n })\n }\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 reset() {\n resetAllLocalStorage()\n this.config.userId = generateGuestId()\n this.config.organizationId = undefined\n }\n\n public onFlowStateChange(handler: (flow: Flow, previousFlow?: Flow) => void) {\n this.onFlowStateChangeHandlers.push(handler)\n }\n\n public removeOnFlowStateChangeHandler(handler: (flow: Flow, previousFlow?: Flow) => void) {\n this.onFlowStateChangeHandlers = this.onFlowStateChangeHandlers.filter((h) => h !== handler)\n }\n\n private async initIfNeeded() {\n if (this.initPromise !== null) {\n return this.initPromise\n } else {\n return this.init(this.config)\n }\n }\n\n private async refreshUserFlowStates(): 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 (\n target[key] &&\n target[key].flowState &&\n (JSON.stringify(target[key].flowState) !== JSON.stringify(value.flowState) ||\n JSON.stringify(target[key].stepStates) !== JSON.stringify(value.stepStates) ||\n JSON.stringify(target[key].shouldTrigger) !== JSON.stringify(value.shouldTrigger))\n ) {\n that.triggerEventHandlers(target[key])\n }\n\n target[key] = value\n return true\n },\n }\n\n frigadeGlobalState[globalStateKey] = {\n refreshUserFlowStates: async () => {},\n userFlowStates: new Proxy({}, validator),\n }\n frigadeGlobalState[globalStateKey].refreshUserFlowStates = async () => {\n const userFlowStatesRaw = await this.fetch(\n `/userFlowStates?foreignUserId=${this.config.userId}${\n this.config.organizationId ? `&foreignUserGroupId=${this.config.organizationId}` : ''\n }`\n )\n if (userFlowStatesRaw && userFlowStatesRaw.data) {\n let userFlowStates = userFlowStatesRaw.data as UserFlowState[]\n userFlowStates.forEach((userFlowState) => {\n frigadeGlobalState[globalStateKey].userFlowStates[userFlowState.flowId] = userFlowState\n })\n }\n }\n }\n\n await frigadeGlobalState[globalStateKey].refreshUserFlowStates()\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await this.fetch('/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowDatas = flowDataRaw.data as FlowDataRaw[]\n flowDatas.forEach((flowData) => {\n this.flows.push(new Flow(this.config, flowData))\n })\n }\n }\n\n private async triggerEventHandlers(previousUserFlowState: UserFlowState) {\n if (previousUserFlowState) {\n this.flows.forEach((flow) => {\n if (flow.id == previousUserFlowState.flowId) {\n this.onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlows = this.previousFlows.get(handler)\n const lastFlow = lastFlows ? lastFlows.get(flow.id) : undefined\n handler(flow, lastFlow)\n if (!lastFlows) {\n this.previousFlows.set(handler, new Map())\n }\n this.previousFlows.get(handler).set(flow.id, flow)\n })\n }\n })\n }\n }\n}\n"],"mappings":";6iBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,UAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,ICAO,IAAMK,EAAiB,QCC9B,IAAAC,EAAkB,4BAClBC,EAA6B,gBAGtB,IAAMC,EAAiB,iBACjBC,EAAe,eACfC,EAAe,eACfC,EAAmB,mBACnBC,EAAiB,iBACjBC,EAAe,eAGtBC,EAAoB,wBACpBC,EAAsB,0BACtBC,EAAY,oBACZC,GAAe,SAEd,SAASC,EAASC,EAAW,CAClC,OAAO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,MAAM,KAAK,MACnC,iCAAiC,KAAK,OAAO,SAC3C,KAAK,OAAO,eAAiB,uBAAuB,KAAK,OAAO,iBAAmB,IAEvF,EACIA,GAAqBA,EAAkB,MACpBA,EAAkB,KACxB,QAASC,GAAkB,CACxCP,EAAmBF,CAAc,EAAE,eAAeS,EAAc,MAAM,EAAIA,CAC5E,CAAC,CAEL,EAGF,MAAMP,EAAmBF,CAAc,EAAE,sBAAsB,CACjE,CAEA,MAAc,cAAe,CAC3B,KAAK,MAAQ,CAAC,EACd,IAAMU,EAAc,MAAM,KAAK,MAAM,QAAQ,EACzCA,GAAeA,EAAY,MACbA,EAAY,KAClB,QAASC,GAAa,CAC9B,KAAK,MAAM,KAAK,IAAIC,EAAK,KAAK,OAAQD,CAAQ,CAAC,CACjD,CAAC,CAEL,CAEA,MAAc,qBAAqBE,EAAsC,CACnEA,GACF,KAAK,MAAM,QAASlB,GAAS,CACvBA,EAAK,IAAMkB,EAAsB,QACnC,KAAK,0BAA0B,QAASf,GAAY,CAClD,IAAMgB,EAAY,KAAK,cAAc,IAAIhB,CAAO,EAC1CiB,EAAWD,EAAYA,EAAU,IAAInB,EAAK,EAAE,EAAI,OACtDG,EAAQH,EAAMoB,CAAQ,EACjBD,GACH,KAAK,cAAc,IAAIhB,EAAS,IAAI,GAAK,EAE3C,KAAK,cAAc,IAAIA,CAAO,EAAE,IAAIH,EAAK,GAAIA,CAAI,CACnD,CAAC,CAEL,CAAC,CAEL,CACF","names":["src_exports","__export","Flow","Frigade","__toCommonJS","VERSION_NUMBER","import_cross_fetch","import_uuid","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","clone","obj","getHeaders","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","resetAllLocalStorage","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","fetch","error","generateGuestId","guestId","uuidv4","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","path","options","gracefulFetch","getHeaders","Flow","Fetchable","config","flowDataRaw","flowDataYml","steps","userFlowState","COMPLETED_FLOW","STARTED_FLOW","SKIPPED_FLOW","hasCompleted","targetingShouldHideFlow","step","index","userFlowStateStep","stepObj","COMPLETED_STEP","STARTED_STEP","properties","currentStep","copy","clone","frigadeGlobalState","getGlobalStateKey","updatedUserFlowState","isLastStep","nextStepId","NOT_STARTED_FLOW","currentStepId","key","Frigade","Fetchable","apiKey","config","userId","properties","organizationId","event","flowId","flow","resetAllLocalStorage","generateGuestId","handler","h","globalStateKey","getGlobalStateKey","frigadeGlobalState","that","validator","target","key","value","userFlowStatesRaw","userFlowState","flowDataRaw","flowData","Flow","previousUserFlowState","lastFlows","lastFlow"]}
package/dist/index.d.ts CHANGED
@@ -14,8 +14,29 @@ interface FrigadeConfig {
14
14
  organizationId?: string;
15
15
  __instanceId?: string;
16
16
  }
17
-
18
- type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'SKIPPED_FLOW';
17
+ interface UserFlowState {
18
+ flowId: string;
19
+ flowState: 'COMPLETED_FLOW' | 'STARTED_FLOW' | 'SKIPPED_FLOW' | 'NOT_STARTED_FLOW';
20
+ lastStepId: string;
21
+ userId: string;
22
+ foreignUserId: string;
23
+ stepStates: Record<string, UserFlowStepState>;
24
+ shouldTrigger: boolean;
25
+ }
26
+ interface UserFlowStepState {
27
+ stepId: string;
28
+ flowSlug: string;
29
+ actionType: 'NOT_STARTED_STEP' | 'STARTED_STEP' | 'COMPLETED_STEP';
30
+ createdAt: string;
31
+ blocked: boolean;
32
+ hidden: boolean;
33
+ }
34
+ interface InternalConfig {
35
+ apiKey: string;
36
+ userId?: string;
37
+ organizationId?: string;
38
+ __instanceId?: string;
39
+ }
19
40
 
20
41
  interface FlowDataRaw {
21
42
  id: number;
@@ -207,6 +228,10 @@ declare class Flow extends Fetchable {
207
228
  * Whether the flow has been skipped or not
208
229
  */
209
230
  isSkipped: boolean;
231
+ /**
232
+ * Whether the flow is visible to the user based on the current user/group's state
233
+ */
234
+ isVisible: boolean;
210
235
  private flowDataRaw;
211
236
  constructor(config: FrigadeConfig, flowDataRaw: FlowDataRaw);
212
237
  private initFromRawData;
@@ -218,6 +243,7 @@ declare class Flow extends Fetchable {
218
243
  * Function that marks the flow completed
219
244
  */
220
245
  complete(properties?: Record<string | number, any>): Promise<void>;
246
+ private optimisticallyMarkFlowCompleted;
221
247
  /**
222
248
  * Function that marks the flow skipped
223
249
  */
@@ -247,6 +273,7 @@ declare class Frigade extends Fetchable {
247
273
  private flows;
248
274
  private initPromise;
249
275
  private onFlowStateChangeHandlers;
276
+ private previousFlows;
250
277
  constructor(apiKey: string, config?: FrigadeConfig);
251
278
  private init;
252
279
  identify(userId: string, properties?: Record<string, any>): Promise<void>;
@@ -255,12 +282,12 @@ declare class Frigade extends Fetchable {
255
282
  getFlow(flowId: string): Promise<Flow>;
256
283
  getFlows(): Promise<Flow[]>;
257
284
  reset(): Promise<void>;
258
- onFlowStateChange(handler: (flow: Flow, newState: UserFlowStatus, previousState: UserFlowStatus) => void): void;
259
- removeOnFlowStateChangeHandler(handler: (flow: Flow, newState: UserFlowStatus, previousState: UserFlowStatus) => void): void;
285
+ onFlowStateChange(handler: (flow: Flow, previousFlow?: Flow) => void): void;
286
+ removeOnFlowStateChangeHandler(handler: (flow: Flow, previousFlow?: Flow) => void): void;
260
287
  private initIfNeeded;
261
288
  private refreshUserFlowStates;
262
289
  private refreshFlows;
263
290
  private triggerEventHandlers;
264
291
  }
265
292
 
266
- export { Flow, Frigade };
293
+ export { Flow, Frigade, FrigadeConfig, InternalConfig, UserFlowState, UserFlowStepState };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- var R="0.1.2";import N from"cross-fetch";import{v4 as x}from"uuid";var y="COMPLETED_FLOW",D="SKIPPED_FLOW",T="STARTED_FLOW",U="NOT_STARTED_FLOW",w="COMPLETED_STEP",g="STARTED_STEP",v="frigade-last-call-at-",G="frigade-last-call-data-",P="frigade-guest-key",J="guest_";function _(i){return{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Frigade-SDK-Version":R,"X-Frigade-SDK-Platform":"Javascript"}}}function b(i){return window&&window.localStorage?window.localStorage.getItem(i):null}function C(i,l){window&&window.localStorage&&window.localStorage.setItem(i,l)}function A(){window&&window.localStorage&&Object.keys(window.localStorage).forEach(i=>{i.startsWith("frigade-")&&window.localStorage.removeItem(i)})}async function L(i,l){let t=v+i,e=G+i;if(window&&window.localStorage&&l&&l.body&&l.method==="POST"){let s=b(t),r=b(e);if(s&&r&&r==l.body){let f=new Date(s);if(new Date().getTime()-f.getTime()<1e3)return m()}C(t,new Date().toISOString()),C(e,l.body)}let n;try{n=await N(i,l)}catch(s){return m(s)}return n?n.staus>=400?m(n.statusText):n.json():m()}function m(i){return i&&console.log("Call to Frigade failed",i),{json:()=>({})}}function I(){if(typeof window<"u"&&typeof window.localStorage<"u"){let i=b(P);return i||(i=`${J}${x()}`,window.localStorage.setItem(P,i)),i}}var a={};function d(i){return`${i.__instanceId}-${i.apiKey}:${i.userId??""}:${i.organizationId??""}`}var h=class{constructor(l){this.config={apiKey:"",apiUrl:"//api.frigade.com/v1/public",userId:I(),__instanceId:Math.random().toString(36).substring(7)};this.config={...this.config,...l}}async fetch(l,t){return L(`${this.config.apiUrl}${l}`,{...t??{},..._(this.config.apiKey)})}};var p=class extends h{constructor(t,e){super(t);this.flowDataRaw=e,this.initFromRawData(e)}initFromRawData(t){let e=JSON.parse(t.data),n=e.steps??e.data??[];this.id=t.slug,this.metadata=t,this.rawData=e,this.title=this.rawData.title,this.subtitle=this.rawData.subtitle;let s=this.getUserFlowState();this.isCompleted=s.flowState==y,this.isStarted=s.flowState==T,this.isSkipped=s.flowState==D,this.steps=new Map,n.forEach((r,f)=>{let c=s.stepStates[r.id],S={...r,isCompleted:c.actionType==w,isStarted:c.actionType==g,isHidden:c.hidden,isBlocked:c.blocked,order:f};S.start=async O=>{let o=this.steps.get(r.id);if(o.isStarted||o.isCompleted)return;o.isStarted=!0;let u={...a[d(this.config)].userFlowStates[this.id]};u.stepStates[o.id].actionType=g,a[d(this.config)].userFlowStates[this.id]=u,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:o.id,data:O??{},createdAt:new Date().toISOString(),actionType:g})}),await this.refreshUserFlowState();let F=this.getUserFlowState();o.isCompleted=F.stepStates[o.id].actionType==w,o.isStarted=F.stepStates[o.id].actionType==g},S.complete=async O=>{let o=this.steps.get(r.id);if(o.isCompleted)return;o.isCompleted=!0;let u={...a[d(this.config)].userFlowStates[this.id]};u.stepStates[o.id].actionType=w,a[d(this.config)].userFlowStates[this.id]=u,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:o.id,data:O??{},createdAt:new Date().toISOString(),actionType:w})}),await this.refreshUserFlowState();let F=this.getUserFlowState();o.isCompleted=F.stepStates[o.id].actionType==w,o.isStarted=F.stepStates[o.id].actionType==g},this.steps.set(r.id,S)})}async start(t){if(this.isStarted||this.isCompleted)return;this.isStarted=!0;let e={...a[d(this.config)].userFlowStates[this.id]};e.flowState=T,a[d(this.config)].userFlowStates[this.id]=e,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:T})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async complete(t){if(this.isCompleted)return;this.isCompleted=!0;let e={...a[d(this.config)].userFlowStates[this.id]};e.flowState=y,a[d(this.config)].userFlowStates[this.id]=e,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:y})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async skip(t){await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:D})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async restart(){this.isCompleted=!1,this.isCompleted=!0,a[d(this.config)].userFlowStates[this.id]=null,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:"unknown",data:{},createdAt:new Date().toISOString(),actionType:U})}),await this.refreshUserFlowState()}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){let t=this.getUserFlowState(),n=Array.from(this.steps.keys()).find(s=>this.steps.get(s).isCompleted===!1)??Array.from(this.steps.keys())[0];return this.steps.get(n)}getNumberOfCompletedSteps(){return Array.from(this.steps.values()).filter(t=>t.isCompleted).length}getUserFlowState(){return a[d(this.config)].userFlowStates[this.id]}async refreshUserFlowState(){await a[d(this.config)].refreshUserFlowStates()}};var E=class extends h{constructor(t,e){super({apiKey:t,...e});this.flows=[];this.onFlowStateChangeHandlers=[];this.init(this.config)}async init(t){return this.config={...this.config,...t},this.initPromise=(async()=>{await this.refreshUserFlowStates(),await this.refreshFlows()})(),this.initPromise}async identify(t,e){await this.initIfNeeded(),this.config.userId=t,await this.fetch("/users",{method:"POST",body:JSON.stringify({foreignId:this.config.userId,properties:e})}),await this.refreshUserFlowStates()}async group(t,e){await this.initIfNeeded(),this.config.organizationId=t,await this.fetch("/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.organizationId,properties:e})}),await this.refreshUserFlowStates()}async track(t,e){await this.initIfNeeded(),await this.fetch("/track",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.organizationId,event:t,properties:e})})}async getFlow(t){return await this.initIfNeeded(),this.flows.find(e=>e.id==t)}async getFlows(){return await this.initIfNeeded(),this.flows}async reset(){A(),this.config.userId=I(),this.config.organizationId=void 0}onFlowStateChange(t){this.onFlowStateChangeHandlers.push(t)}removeOnFlowStateChangeHandler(t){this.onFlowStateChangeHandlers=this.onFlowStateChangeHandlers.filter(e=>e!==t)}async initIfNeeded(){return this.initPromise!==null?this.initPromise:this.init(this.config)}async refreshUserFlowStates(){let t=d(this.config);if(!a[t]){let e=this,n={set:function(s,r,f){var c,S;return(s[r]&&((c=s[r])!=null&&c.flowState)&&JSON.stringify(s[r].flowState)!==JSON.stringify(f.flowState)||JSON.stringify((S=s[r])==null?void 0:S.stepStates)!==JSON.stringify(f.stepStates)||JSON.stringify(s[r].shouldTrigger)!==JSON.stringify(f.shouldTrigger))&&e.triggerEventHandlers(s[r],f),s[r]=f,!0}};a[t]={refreshUserFlowStates:async()=>{},userFlowStates:new Proxy({},n)},a[t].refreshUserFlowStates=async()=>{let s=await this.fetch(`/userFlowStates?foreignUserId=${this.config.userId}${this.config.organizationId?`&foreignUserGroupId=${this.config.organizationId}`:""}`);s&&s.data&&s.data.forEach(f=>{a[t].userFlowStates[f.flowId]=f})}}await a[t].refreshUserFlowStates()}async refreshFlows(){this.flows=[];let t=await this.fetch("/flows");t&&t.data&&t.data.forEach(n=>{this.flows.push(new p(this.config,n))})}triggerEventHandlers(t,e){t&&t.flowState!==e.flowState&&this.flows.forEach(n=>{n.id==e.flowId&&this.onFlowStateChangeHandlers.forEach(s=>{s(n,e.flowState,t==null?void 0:t.flowState)})})}};export{p as Flow,E as Frigade};
2
+ var A="0.1.4";import W from"cross-fetch";import{v4 as K}from"uuid";var u="COMPLETED_FLOW",P="SKIPPED_FLOW",F="STARTED_FLOW",x="NOT_STARTED_FLOW",w="COMPLETED_STEP",S="STARTED_STEP",$="frigade-last-call-at-",H="frigade-last-call-data-",N="frigade-guest-key",k="guest_";function m(i){return JSON.parse(JSON.stringify(i))}function M(i){return{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Frigade-SDK-Version":A,"X-Frigade-SDK-Platform":"Javascript"}}}function R(i){return window&&window.localStorage?window.localStorage.getItem(i):null}function L(i,l){window&&window.localStorage&&window.localStorage.setItem(i,l)}function J(){window&&window.localStorage&&Object.keys(window.localStorage).forEach(i=>{i.startsWith("frigade-")&&window.localStorage.removeItem(i)})}async function G(i,l){let t=$+i,e=H+i;if(window&&window.localStorage&&l&&l.body&&l.method==="POST"){let s=R(t),n=R(e);if(s&&n&&n==l.body){let c=new Date(s);if(new Date().getTime()-c.getTime()<1e3)return O()}L(t,new Date().toISOString()),L(e,l.body)}let r;try{r=await W(i,l)}catch(s){return O(s)}return r?r.staus>=400?O(r.statusText):r.json():O()}function O(i){return i&&console.log("Call to Frigade failed",i),{json:()=>({})}}function b(){if(typeof window<"u"&&typeof window.localStorage<"u"){let i=R(N);return i||(i=`${k}${K()}`,window.localStorage.setItem(N,i)),i}}var a={};function d(i){return`${i.__instanceId}-${i.apiKey}:${i.userId??""}:${i.organizationId??""}`}var g=class{constructor(l){this.config={apiKey:"",apiUrl:"//api.frigade.com/v1/public",userId:b(),__instanceId:Math.random().toString(36).substring(7)};this.config={...this.config,...l}}async fetch(l,t){return G(`${this.config.apiUrl}${l}`,{...t??{},...M(this.config.apiKey)})}};var h=class extends g{constructor(t,e){super(t);this.isVisible=!1;this.flowDataRaw=e,this.initFromRawData(e)}initFromRawData(t){let e=JSON.parse(t.data),r=e.steps??e.data??[];this.id=t.slug,this.metadata=t,this.rawData=e,this.title=this.rawData.title,this.subtitle=this.rawData.subtitle;let s=this.getUserFlowState();this.isCompleted=s.flowState==u,this.isStarted=s.flowState==F,this.isSkipped=s.flowState==P;let n=this.isCompleted||this.isSkipped,c=t.targetingLogic&&s.shouldTrigger===!1;this.isVisible=!n&&!c,this.steps=new Map,r.forEach((f,D)=>{let y=s.stepStates[f.id],E={...f,isCompleted:y.actionType==w,isStarted:y.actionType==S,isHidden:y.hidden,isBlocked:y.blocked,order:D};E.start=async C=>{let o=this.steps.get(f.id);if(o.isStarted||o.isCompleted)return;o.isStarted=!0;let T=m(a[d(this.config)].userFlowStates[this.id]);T.stepStates[o.id].actionType=S,T.lastStepId=o.id,a[d(this.config)].userFlowStates[this.id]=T,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:o.id,data:C??{},createdAt:new Date().toISOString(),actionType:S})}),await this.refreshUserFlowState();let p=this.getUserFlowState();o.isCompleted=p.stepStates[o.id].actionType==w,o.isStarted=p.stepStates[o.id].actionType==S},E.complete=async C=>{let o=this.steps.get(f.id);if(o.isCompleted)return;let p=this.getNumberOfCompletedSteps()+1==this.steps.size;o.isCompleted=!0,this.isStarted=!0;let I=m(a[d(this.config)].userFlowStates[this.id]);I.stepStates[o.id].actionType=w,I.flowState=p?u:F;let U=Array.from(this.steps.keys())[D+1];U&&(I.lastStepId=U),p&&this.optimisticallyMarkFlowCompleted(),a[d(this.config)].userFlowStates[this.id]=I,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:o.id,data:C??{},createdAt:new Date().toISOString(),actionType:w})}),p?await this.complete():await this.refreshUserFlowState();let v=this.getUserFlowState();o.isCompleted=v.stepStates[o.id].actionType==w,o.isStarted=v.stepStates[o.id].actionType==S},this.steps.set(f.id,E)})}async start(t){if(this.isStarted||this.isCompleted)return;this.isStarted=!0;let e=m(a[d(this.config)].userFlowStates[this.id]);e.flowState=F,a[d(this.config)].userFlowStates[this.id]=e,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:F})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async complete(t){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:u})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw))}optimisticallyMarkFlowCompleted(){this.isStarted=!0,this.isCompleted=!0;let t=m(a[d(this.config)].userFlowStates[this.id]);t.flowState=u,a[d(this.config)].userFlowStates[this.id]=t,this.isVisible=!1}async skip(t){await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t??{},createdAt:new Date().toISOString(),actionType:P})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async restart(){this.isCompleted=!1,this.isCompleted=!0,a[d(this.config)].userFlowStates[this.id]=null,await this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,flowSlug:this.id,stepId:"unknown",data:{},createdAt:new Date().toISOString(),actionType:x})}),await this.refreshUserFlowState()}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){let e=Array.from(this.steps.keys()).find(r=>this.steps.get(r).isCompleted===!1)??Array.from(this.steps.keys())[0];return this.steps.get(e)}getNumberOfCompletedSteps(){return Array.from(this.steps.values()).filter(t=>t.isCompleted).length}getUserFlowState(){return a[d(this.config)].userFlowStates[this.id]}async refreshUserFlowState(){await a[d(this.config)].refreshUserFlowStates()}};var _=class extends g{constructor(t,e){super({apiKey:t,...e});this.flows=[];this.onFlowStateChangeHandlers=[];this.previousFlows=new Map;this.init(this.config)}async init(t){return this.config={...this.config,...t},this.initPromise=(async()=>{await this.refreshUserFlowStates(),await this.refreshFlows()})(),this.initPromise}async identify(t,e){await this.initIfNeeded(),this.config.userId=t,await this.fetch("/users",{method:"POST",body:JSON.stringify({foreignId:this.config.userId,properties:e})}),await this.refreshUserFlowStates()}async group(t,e){await this.initIfNeeded(),this.config.organizationId=t,await this.fetch("/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.organizationId,properties:e})}),await this.refreshUserFlowStates()}async track(t,e){await this.initIfNeeded(),await this.fetch("/track",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.organizationId,event:t,properties:e})})}async getFlow(t){return await this.initIfNeeded(),this.flows.find(e=>e.id==t)}async getFlows(){return await this.initIfNeeded(),this.flows}async reset(){J(),this.config.userId=b(),this.config.organizationId=void 0}onFlowStateChange(t){this.onFlowStateChangeHandlers.push(t)}removeOnFlowStateChangeHandler(t){this.onFlowStateChangeHandlers=this.onFlowStateChangeHandlers.filter(e=>e!==t)}async initIfNeeded(){return this.initPromise!==null?this.initPromise:this.init(this.config)}async refreshUserFlowStates(){let t=d(this.config);if(!a[t]){let e=this,r={set:function(s,n,c){return s[n]&&s[n].flowState&&(JSON.stringify(s[n].flowState)!==JSON.stringify(c.flowState)||JSON.stringify(s[n].stepStates)!==JSON.stringify(c.stepStates)||JSON.stringify(s[n].shouldTrigger)!==JSON.stringify(c.shouldTrigger))&&e.triggerEventHandlers(s[n]),s[n]=c,!0}};a[t]={refreshUserFlowStates:async()=>{},userFlowStates:new Proxy({},r)},a[t].refreshUserFlowStates=async()=>{let s=await this.fetch(`/userFlowStates?foreignUserId=${this.config.userId}${this.config.organizationId?`&foreignUserGroupId=${this.config.organizationId}`:""}`);s&&s.data&&s.data.forEach(c=>{a[t].userFlowStates[c.flowId]=c})}}await a[t].refreshUserFlowStates()}async refreshFlows(){this.flows=[];let t=await this.fetch("/flows");t&&t.data&&t.data.forEach(r=>{this.flows.push(new h(this.config,r))})}async triggerEventHandlers(t){t&&this.flows.forEach(e=>{e.id==t.flowId&&this.onFlowStateChangeHandlers.forEach(r=>{let s=this.previousFlows.get(r),n=s?s.get(e.id):void 0;r(e,n),s||this.previousFlows.set(r,new Map),this.previousFlows.get(r).set(e.id,e)})})}};export{h as Flow,_ as Frigade};
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/frigade.ts"],"sourcesContent":["export const VERSION_NUMBER = '0.1.2'\n","import { VERSION_NUMBER } from '../core/version'\nimport fetch from 'cross-fetch'\nimport { v4 as uuidv4 } from 'uuid'\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'\nexport type StepActionType = 'STARTED_STEP' | 'COMPLETED_STEP' | 'NOT_STARTED_STEP'\nexport type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'SKIPPED_FLOW'\nconst LAST_POST_CALL_AT = 'frigade-last-call-at-'\nconst LAST_POST_CALL_DATA = 'frigade-last-call-data-'\nconst GUEST_KEY = 'frigade-guest-key'\nconst GUEST_PREFIX = 'guest_'\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 (window && window.localStorage) {\n return window.localStorage.getItem(key)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (window && window.localStorage) {\n window.localStorage.setItem(key, value)\n }\n}\n\nexport function resetAllLocalStorage() {\n if (window && window.localStorage) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith('frigade-')) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nexport async function gracefulFetch(url: string, options: any) {\n const lastCallAtKey = LAST_POST_CALL_AT + url\n const lastCallDataKey = LAST_POST_CALL_DATA + url\n if (window && window.localStorage && options && options.body && options.method === 'POST') {\n const lastCall = getLocalStorage(lastCallAtKey)\n const lastCallData = getLocalStorage(lastCallDataKey)\n if (lastCall && lastCallData && lastCallData == options.body) {\n const lastCallDate = new Date(lastCall)\n const now = new Date()\n const diff = now.getTime() - lastCallDate.getTime()\n // Throttle consecutive POST calls to 1 second\n if (diff < 1000) {\n return getEmptyResponse()\n }\n }\n setLocalStorage(lastCallAtKey, new Date().toISOString())\n setLocalStorage(lastCallDataKey, options.body)\n }\n\n let response\n try {\n response = await fetch(url, options)\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse()\n }\n\n if (response.staus >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n return response.json()\n}\n\nfunction 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 (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n window.localStorage.setItem(GUEST_KEY, guestId)\n }\n return guestId\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","import { FrigadeConfig, UserFlowState } from '../types'\n\nexport interface FrigadeGlobalState {\n refreshUserFlowStates: () => Promise<void>\n userFlowStates: Record<string, UserFlowState>\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}:${internalConfig.userId ?? ''}:${\n internalConfig.organizationId ?? ''\n }`\n}\n","import { generateGuestId, getHeaders, gracefulFetch } from './utils'\nimport { FrigadeConfig } from '../types'\n\nexport class Fetchable {\n public config: FrigadeConfig = {\n apiKey: '',\n apiUrl: '//api.frigade.com/v1/public',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(36).substring(7),\n }\n\n constructor(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n }\n\n public async fetch(path: string, options?: Record<any, any>) {\n return gracefulFetch(`${this.config.apiUrl}${path}`, {\n ...(options ?? {}),\n ...getHeaders(this.config.apiKey),\n })\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { FlowDataRaw } from './types'\nimport {\n COMPLETED_FLOW,\n COMPLETED_STEP,\n NOT_STARTED_FLOW,\n SKIPPED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { FlowStep } from './flow-step'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/Fetchable'\n\nexport default class Flow extends Fetchable {\n /**\n * THe Flow ID / slug of the flow\n */\n public id: string\n /**\n * The raw data defined in `config.yml` as a JSON decoded object\n */\n public rawData: Record<any, any>\n /**\n * Ordered map from Step ID to step data. The `steps` array in `config.yml`\n */\n public steps: Map<string, FlowStep>\n /**\n * The user-facing title of the flow, if defined at the top level of `config.yml`\n */\n public title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `config.yml`\n */\n public subtitle?: string\n /**\n * The metadata of the flow.\n */\n public metadata: FlowDataRaw\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 private flowDataRaw: FlowDataRaw\n\n constructor(config: FrigadeConfig, flowDataRaw: FlowDataRaw) {\n super(config)\n this.flowDataRaw = flowDataRaw\n this.initFromRawData(flowDataRaw)\n }\n\n private initFromRawData(flowDataRaw: FlowDataRaw) {\n const flowDataYml = JSON.parse(flowDataRaw.data)\n const steps = flowDataYml.steps ?? flowDataYml.data ?? []\n this.id = flowDataRaw.slug\n this.metadata = flowDataRaw\n this.rawData = flowDataYml\n this.title = this.rawData.title\n this.subtitle = this.rawData.subtitle\n\n const userFlowState = this.getUserFlowState()\n\n this.isCompleted = userFlowState.flowState == COMPLETED_FLOW\n this.isStarted = userFlowState.flowState == STARTED_FLOW\n this.isSkipped = userFlowState.flowState == SKIPPED_FLOW\n this.steps = new Map()\n\n steps.forEach((step, index) => {\n const userFlowStateStep = userFlowState.stepStates[step.id]\n const stepObj = {\n ...step,\n isCompleted: userFlowStateStep.actionType == COMPLETED_STEP,\n isStarted: userFlowStateStep.actionType == STARTED_STEP,\n isHidden: userFlowStateStep.hidden,\n isBlocked: userFlowStateStep.blocked,\n order: index,\n } as FlowStep\n\n stepObj.start = async (properties?: Record<string | number, any>) => {\n const currentStep = this.steps.get(step.id)\n\n if (currentStep.isStarted || currentStep.isCompleted) {\n return\n }\n\n currentStep.isStarted = true\n const clone = {\n ...frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id],\n }\n clone.stepStates[currentStep.id].actionType = STARTED_STEP\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = clone\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: currentStep.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_STEP,\n }),\n })\n\n await this.refreshUserFlowState()\n\n const updatedUserFlowState = this.getUserFlowState()\n currentStep.isCompleted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == COMPLETED_STEP\n currentStep.isStarted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == STARTED_STEP\n }\n\n stepObj.complete = async (properties?: Record<string | number, any>) => {\n const currentStep = this.steps.get(step.id)\n\n if (currentStep.isCompleted) {\n return\n }\n\n currentStep.isCompleted = true\n const clone = {\n ...frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id],\n }\n clone.stepStates[currentStep.id].actionType = COMPLETED_STEP\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = clone\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: currentStep.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_STEP,\n }),\n })\n\n await this.refreshUserFlowState()\n\n const updatedUserFlowState = this.getUserFlowState()\n currentStep.isCompleted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == COMPLETED_STEP\n currentStep.isStarted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == STARTED_STEP\n }\n\n this.steps.set(step.id, stepObj)\n })\n }\n\n /**\n * Function that marks the flow started\n */\n public async start(properties?: Record<string | number, any>) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n\n this.isStarted = true\n const clone = { ...frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] }\n clone.flowState = STARTED_FLOW\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = clone\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that marks the flow completed\n */\n public async complete(properties?: Record<string | number, any>) {\n if (this.isCompleted) {\n return\n }\n\n this.isCompleted = true\n const clone = { ...frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] }\n clone.flowState = COMPLETED_FLOW\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = clone\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_FLOW,\n }),\n })\n\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that marks the flow skipped\n */\n public async skip(properties?: Record<string | number, any>) {\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: SKIPPED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that restarts the flow/marks it not started\n */\n public async restart() {\n this.isCompleted = false\n this.isCompleted = true\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = null\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: 'unknown',\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\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 * Function that gets current step\n */\n public getCurrentStep(): FlowStep {\n // Find the userFlowState with most recent timestamp\n const userFlowState = this.getUserFlowState()\n\n // TEMP: lastStepId appears to be the last step that a flowState event was recorded for?\n // const lastStepId =\n // userFlowState?.lastStepId?.length > 0 && userFlowState?.lastStepId !== 'unknown'\n // ? userFlowState?.lastStepId\n // : undefined\n\n // TEMP: Return the lowest-ordered incomplete step in the flow\n const lastStepId = Array.from(this.steps.keys()).find(\n (key) => this.steps.get(key).isCompleted === false\n )\n\n const currentStepId = lastStepId ?? Array.from(this.steps.keys())[0]\n return this.steps.get(currentStepId)\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.isCompleted).length\n }\n\n private getUserFlowState(): UserFlowState {\n const userFlowStates = frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates\n return userFlowStates[this.id]\n }\n\n private async refreshUserFlowState() {\n await frigadeGlobalState[getGlobalStateKey(this.config)].refreshUserFlowStates()\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { generateGuestId, resetAllLocalStorage, UserFlowStatus } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowDataRaw } from './types'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/Fetchable'\n\nexport class Frigade extends Fetchable {\n private flows: Flow[] = []\n private initPromise: Promise<void>\n private onFlowStateChangeHandlers: ((\n flow: Flow,\n newState: UserFlowStatus,\n previousState: UserFlowStatus\n ) => void)[] = []\n\n constructor(apiKey: string, config?: FrigadeConfig) {\n super({\n apiKey,\n ...config,\n })\n\n this.init(this.config)\n }\n\n private async init(config: FrigadeConfig): Promise<void> {\n this.config = {\n ...this.config,\n ...config,\n }\n\n this.initPromise = (async () => {\n await this.refreshUserFlowStates()\n await this.refreshFlows()\n })()\n\n return this.initPromise\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n this.config.userId = userId\n await this.fetch('/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.config.userId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n this.config.organizationId = organizationId\n await this.fetch('/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.organizationId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n await this.fetch('/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.organizationId,\n event,\n properties,\n }),\n })\n }\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 reset() {\n resetAllLocalStorage()\n this.config.userId = generateGuestId()\n this.config.organizationId = undefined\n }\n\n public onFlowStateChange(\n handler: (flow: Flow, newState: UserFlowStatus, previousState: UserFlowStatus) => void\n ) {\n this.onFlowStateChangeHandlers.push(handler)\n }\n\n public removeOnFlowStateChangeHandler(\n handler: (flow: Flow, newState: UserFlowStatus, previousState: UserFlowStatus) => void\n ) {\n this.onFlowStateChangeHandlers = this.onFlowStateChangeHandlers.filter((h) => h !== handler)\n }\n\n private async initIfNeeded() {\n if (this.initPromise !== null) {\n return this.initPromise\n } else {\n return this.init(this.config)\n }\n }\n\n private async refreshUserFlowStates(): 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 (\n (target[key] &&\n target[key]?.flowState &&\n JSON.stringify(target[key].flowState) !== JSON.stringify(value.flowState)) ||\n JSON.stringify(target[key]?.stepStates) !== JSON.stringify(value.stepStates) ||\n JSON.stringify(target[key].shouldTrigger) !== JSON.stringify(value.shouldTrigger)\n ) {\n that.triggerEventHandlers(target[key], value)\n }\n\n target[key] = value\n return true\n },\n }\n\n frigadeGlobalState[globalStateKey] = {\n refreshUserFlowStates: async () => {},\n userFlowStates: new Proxy({}, validator),\n }\n frigadeGlobalState[globalStateKey].refreshUserFlowStates = async () => {\n const userFlowStatesRaw = await this.fetch(\n `/userFlowStates?foreignUserId=${this.config.userId}${\n this.config.organizationId ? `&foreignUserGroupId=${this.config.organizationId}` : ''\n }`\n )\n if (userFlowStatesRaw && userFlowStatesRaw.data) {\n let userFlowStates = userFlowStatesRaw.data as UserFlowState[]\n userFlowStates.forEach((userFlowState) => {\n frigadeGlobalState[globalStateKey].userFlowStates[userFlowState.flowId] = userFlowState\n })\n }\n }\n }\n\n await frigadeGlobalState[globalStateKey].refreshUserFlowStates()\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await this.fetch('/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowDatas = flowDataRaw.data as FlowDataRaw[]\n flowDatas.forEach((flowData) => {\n this.flows.push(new Flow(this.config, flowData))\n })\n }\n }\n\n private triggerEventHandlers(\n previousUserFlowState: UserFlowState,\n newUserFlowState: UserFlowState\n ) {\n if (previousUserFlowState && previousUserFlowState.flowState !== newUserFlowState.flowState) {\n this.flows.forEach((flow) => {\n if (flow.id == newUserFlowState.flowId) {\n this.onFlowStateChangeHandlers.forEach((handler) => {\n handler(flow, newUserFlowState.flowState, previousUserFlowState?.flowState)\n })\n }\n })\n }\n }\n}\n"],"mappings":";AAAO,IAAMA,EAAiB,QCC9B,OAAOC,MAAW,cAClB,OAAS,MAAMC,MAAc,OAGtB,IAAMC,EAAiB,iBACjBC,EAAe,eACfC,EAAe,eACfC,EAAmB,mBACnBC,EAAiB,iBACjBC,EAAe,eAGtBC,EAAoB,wBACpBC,EAAsB,0BACtBC,EAAY,oBACZC,EAAe,SAEd,SAASC,EAAWC,EAAgB,CACzC,MAAO,CACL,QAAS,CACP,cAAe,UAAUA,IACzB,eAAgB,mBAChB,wBAAyBC,EACzB,yBAA0B,YAC5B,CACF,CACF,CAEA,SAASC,EAAgBC,EAAa,CACpC,OAAI,QAAU,OAAO,aACZ,OAAO,aAAa,QAAQA,CAAG,EAEjC,IACT,CAEA,SAASC,EAAgBD,EAAaE,EAAe,CAC/C,QAAU,OAAO,cACnB,OAAO,aAAa,QAAQF,EAAKE,CAAK,CAE1C,CAEO,SAASC,GAAuB,CACjC,QAAU,OAAO,cAEnB,OAAO,KAAK,OAAO,YAAY,EAAE,QAASH,GAAQ,CAC5CA,EAAI,WAAW,UAAU,GAC3B,OAAO,aAAa,WAAWA,CAAG,CAEtC,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AK,UAAUC,EAAM,aAAa,IAEhFJ,EAAK,qBAAqBE,EAAOC,CAAG,EAAGC,CAAK,EAG9CF,EAAOC,CAAG,EAAIC,EACP,EACT,CACF,EAEAL,EAAmBF,CAAc,EAAI,CACnC,sBAAuB,SAAY,CAAC,EACpC,eAAgB,IAAI,MAAM,CAAC,EAAGI,CAAS,CACzC,EACAF,EAAmBF,CAAc,EAAE,sBAAwB,SAAY,CACrE,IAAMU,EAAoB,MAAM,KAAK,MACnC,iCAAiC,KAAK,OAAO,SAC3C,KAAK,OAAO,eAAiB,uBAAuB,KAAK,OAAO,iBAAmB,IAEvF,EACIA,GAAqBA,EAAkB,MACpBA,EAAkB,KACxB,QAASC,GAAkB,CACxCT,EAAmBF,CAAc,EAAE,eAAeW,EAAc,MAAM,EAAIA,CAC5E,CAAC,CAEL,EAGF,MAAMT,EAAmBF,CAAc,EAAE,sBAAsB,CACjE,CAEA,MAAc,cAAe,CAC3B,KAAK,MAAQ,CAAC,EACd,IAAMY,EAAc,MAAM,KAAK,MAAM,QAAQ,EACzCA,GAAeA,EAAY,MACbA,EAAY,KAClB,QAASC,GAAa,CAC9B,KAAK,MAAM,KAAK,IAAIC,EAAK,KAAK,OAAQD,CAAQ,CAAC,CACjD,CAAC,CAEL,CAEQ,qBACNE,EACAC,EACA,CACID,GAAyBA,EAAsB,YAAcC,EAAiB,WAChF,KAAK,MAAM,QAASrB,GAAS,CACvBA,EAAK,IAAMqB,EAAiB,QAC9B,KAAK,0BAA0B,QAASlB,GAAY,CAClDA,EAAQH,EAAMqB,EAAiB,UAAWD,GAAA,YAAAA,EAAuB,SAAS,CAC5E,CAAC,CAEL,CAAC,CAEL,CACF","names":["VERSION_NUMBER","fetch","uuidv4","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","getHeaders","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","resetAllLocalStorage","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","fetch","error","generateGuestId","guestId","uuidv4","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","path","options","gracefulFetch","getHeaders","Flow","Fetchable","config","flowDataRaw","flowDataYml","steps","userFlowState","COMPLETED_FLOW","STARTED_FLOW","SKIPPED_FLOW","step","index","userFlowStateStep","stepObj","COMPLETED_STEP","STARTED_STEP","properties","currentStep","clone","frigadeGlobalState","getGlobalStateKey","updatedUserFlowState","NOT_STARTED_FLOW","currentStepId","key","Frigade","Fetchable","apiKey","config","userId","properties","organizationId","event","flowId","flow","resetAllLocalStorage","generateGuestId","handler","h","globalStateKey","getGlobalStateKey","frigadeGlobalState","that","validator","target","key","value","_a","_b","userFlowStatesRaw","userFlowState","flowDataRaw","flowData","Flow","previousUserFlowState","newUserFlowState"]}
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/frigade.ts"],"sourcesContent":["export const VERSION_NUMBER = '0.1.4'\n","import { VERSION_NUMBER } from '../core/version'\nimport fetch from 'cross-fetch'\nimport { v4 as uuidv4 } from 'uuid'\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'\nexport type StepActionType = 'STARTED_STEP' | 'COMPLETED_STEP' | 'NOT_STARTED_STEP'\nexport type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'SKIPPED_FLOW'\nconst LAST_POST_CALL_AT = 'frigade-last-call-at-'\nconst LAST_POST_CALL_DATA = 'frigade-last-call-data-'\nconst GUEST_KEY = 'frigade-guest-key'\nconst GUEST_PREFIX = 'guest_'\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 (window && window.localStorage) {\n return window.localStorage.getItem(key)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (window && window.localStorage) {\n window.localStorage.setItem(key, value)\n }\n}\n\nexport function resetAllLocalStorage() {\n if (window && window.localStorage) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith('frigade-')) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nexport async function gracefulFetch(url: string, options: any) {\n const lastCallAtKey = LAST_POST_CALL_AT + url\n const lastCallDataKey = LAST_POST_CALL_DATA + url\n if (window && window.localStorage && options && options.body && options.method === 'POST') {\n const lastCall = getLocalStorage(lastCallAtKey)\n const lastCallData = getLocalStorage(lastCallDataKey)\n if (lastCall && lastCallData && lastCallData == options.body) {\n const lastCallDate = new Date(lastCall)\n const now = new Date()\n const diff = now.getTime() - lastCallDate.getTime()\n // Throttle consecutive POST calls to 1 second\n if (diff < 1000) {\n return getEmptyResponse()\n }\n }\n setLocalStorage(lastCallAtKey, new Date().toISOString())\n setLocalStorage(lastCallDataKey, options.body)\n }\n\n let response\n try {\n response = await fetch(url, options)\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse()\n }\n\n if (response.staus >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n return response.json()\n}\n\nfunction 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 (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n window.localStorage.setItem(GUEST_KEY, guestId)\n }\n return guestId\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","import { FrigadeConfig, UserFlowState } from '../types'\n\nexport interface FrigadeGlobalState {\n refreshUserFlowStates: () => Promise<void>\n userFlowStates: Record<string, UserFlowState>\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}:${internalConfig.userId ?? ''}:${\n internalConfig.organizationId ?? ''\n }`\n}\n","import { generateGuestId, getHeaders, gracefulFetch } from './utils'\nimport { FrigadeConfig } from '../types'\n\nexport class Fetchable {\n public config: FrigadeConfig = {\n apiKey: '',\n apiUrl: '//api.frigade.com/v1/public',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(36).substring(7),\n }\n\n constructor(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n }\n\n public async fetch(path: string, options?: Record<any, any>) {\n return gracefulFetch(`${this.config.apiUrl}${path}`, {\n ...(options ?? {}),\n ...getHeaders(this.config.apiKey),\n })\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { FlowDataRaw } from './types'\nimport {\n clone,\n COMPLETED_FLOW,\n COMPLETED_STEP,\n NOT_STARTED_FLOW,\n SKIPPED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { FlowStep } from './flow-step'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/Fetchable'\n\nexport default class Flow extends Fetchable {\n /**\n * THe Flow ID / slug of the flow\n */\n public id: string\n /**\n * The raw data defined in `config.yml` as a JSON decoded object\n */\n public rawData: Record<any, any>\n /**\n * Ordered map from Step ID to step data. The `steps` array in `config.yml`\n */\n public steps: Map<string, FlowStep>\n /**\n * The user-facing title of the flow, if defined at the top level of `config.yml`\n */\n public title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `config.yml`\n */\n public subtitle?: string\n /**\n * The metadata of the flow.\n */\n public metadata: FlowDataRaw\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 * Whether the flow is visible to the user based on the current user/group's state\n */\n public isVisible: boolean = false\n\n private flowDataRaw: FlowDataRaw\n\n constructor(config: FrigadeConfig, flowDataRaw: FlowDataRaw) {\n super(config)\n this.flowDataRaw = flowDataRaw\n this.initFromRawData(flowDataRaw)\n }\n\n private initFromRawData(flowDataRaw: FlowDataRaw) {\n const flowDataYml = JSON.parse(flowDataRaw.data)\n const steps = flowDataYml.steps ?? flowDataYml.data ?? []\n this.id = flowDataRaw.slug\n this.metadata = flowDataRaw\n this.rawData = flowDataYml\n this.title = this.rawData.title\n this.subtitle = this.rawData.subtitle\n\n const userFlowState = this.getUserFlowState()\n\n this.isCompleted = userFlowState.flowState == COMPLETED_FLOW\n this.isStarted = userFlowState.flowState == STARTED_FLOW\n this.isSkipped = userFlowState.flowState == SKIPPED_FLOW\n const hasCompleted = this.isCompleted || this.isSkipped\n const targetingShouldHideFlow =\n flowDataRaw.targetingLogic && userFlowState.shouldTrigger === false\n this.isVisible = !hasCompleted && !targetingShouldHideFlow\n this.steps = new Map()\n\n steps.forEach((step, index) => {\n const userFlowStateStep = userFlowState.stepStates[step.id]\n const stepObj = {\n ...step,\n isCompleted: userFlowStateStep.actionType == COMPLETED_STEP,\n isStarted: userFlowStateStep.actionType == STARTED_STEP,\n isHidden: userFlowStateStep.hidden,\n isBlocked: userFlowStateStep.blocked,\n order: index,\n } as FlowStep\n\n stepObj.start = async (properties?: Record<string | number, any>) => {\n const currentStep = this.steps.get(step.id)\n\n if (currentStep.isStarted || currentStep.isCompleted) {\n return\n }\n\n currentStep.isStarted = true\n const copy = clone(\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id]\n )\n copy.stepStates[currentStep.id].actionType = STARTED_STEP\n copy.lastStepId = currentStep.id\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = copy\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: currentStep.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_STEP,\n }),\n })\n\n await this.refreshUserFlowState()\n\n const updatedUserFlowState = this.getUserFlowState()\n currentStep.isCompleted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == COMPLETED_STEP\n currentStep.isStarted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == STARTED_STEP\n }\n\n stepObj.complete = async (properties?: Record<string | number, any>) => {\n const currentStep = this.steps.get(step.id)\n\n if (currentStep.isCompleted) {\n return\n }\n\n const numberOfCompletedSteps = this.getNumberOfCompletedSteps()\n const isLastStep = numberOfCompletedSteps + 1 == this.steps.size\n\n currentStep.isCompleted = true\n this.isStarted = true\n const copy = clone(\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id]\n )\n\n copy.stepStates[currentStep.id].actionType = COMPLETED_STEP\n copy.flowState = isLastStep ? COMPLETED_FLOW : STARTED_FLOW\n\n const nextStepId = Array.from(this.steps.keys())[index + 1]\n if (nextStepId) {\n copy.lastStepId = nextStepId\n }\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = copy\n\n // if all steps are now completed, mark flow completed\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: currentStep.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_STEP,\n }),\n })\n\n if (isLastStep) {\n await this.complete()\n } else {\n await this.refreshUserFlowState()\n }\n\n const updatedUserFlowState = this.getUserFlowState()\n currentStep.isCompleted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == COMPLETED_STEP\n currentStep.isStarted =\n updatedUserFlowState.stepStates[currentStep.id].actionType == STARTED_STEP\n }\n\n this.steps.set(step.id, stepObj)\n })\n }\n\n /**\n * Function that marks the flow started\n */\n public async start(properties?: Record<string | number, any>) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n\n this.isStarted = true\n const copy = clone(frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id])\n copy.flowState = STARTED_FLOW\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = copy\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that marks the flow completed\n */\n public async complete(properties?: Record<string | number, any>) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_FLOW,\n }),\n })\n\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n private optimisticallyMarkFlowCompleted() {\n this.isStarted = true\n this.isCompleted = true\n const copy = clone(frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id])\n copy.flowState = COMPLETED_FLOW\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = copy\n this.isVisible = false\n }\n\n /**\n * Function that marks the flow skipped\n */\n public async skip(properties?: Record<string | number, any>) {\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: SKIPPED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that restarts the flow/marks it not started\n */\n public async restart() {\n this.isCompleted = false\n this.isCompleted = true\n frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates[this.id] = null\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n flowSlug: this.id,\n stepId: 'unknown',\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\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 * Function that gets current step\n */\n public getCurrentStep(): FlowStep {\n const lastStepId = Array.from(this.steps.keys()).find(\n (key) => this.steps.get(key).isCompleted === false\n )\n\n const currentStepId = lastStepId ?? Array.from(this.steps.keys())[0]\n return this.steps.get(currentStepId)\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.isCompleted).length\n }\n\n private getUserFlowState(): UserFlowState {\n const userFlowStates = frigadeGlobalState[getGlobalStateKey(this.config)].userFlowStates\n return userFlowStates[this.id]\n }\n\n private async refreshUserFlowState() {\n await frigadeGlobalState[getGlobalStateKey(this.config)].refreshUserFlowStates()\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { generateGuestId, resetAllLocalStorage } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowDataRaw } from './types'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/Fetchable'\n\nexport class Frigade extends Fetchable {\n private flows: Flow[] = []\n private initPromise: Promise<void>\n private onFlowStateChangeHandlers: ((flow: Flow, previousFlow?: Flow) => void)[] = []\n private previousFlows: Map<(flow: Flow, previousFlow: Flow) => void, Map<string, Flow>> =\n new Map()\n\n constructor(apiKey: string, config?: FrigadeConfig) {\n super({\n apiKey,\n ...config,\n })\n\n this.init(this.config)\n }\n\n private async init(config: FrigadeConfig): Promise<void> {\n this.config = {\n ...this.config,\n ...config,\n }\n\n this.initPromise = (async () => {\n await this.refreshUserFlowStates()\n await this.refreshFlows()\n })()\n\n return this.initPromise\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n this.config.userId = userId\n await this.fetch('/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.config.userId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n this.config.organizationId = organizationId\n await this.fetch('/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.organizationId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n await this.fetch('/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.organizationId,\n event,\n properties,\n }),\n })\n }\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 reset() {\n resetAllLocalStorage()\n this.config.userId = generateGuestId()\n this.config.organizationId = undefined\n }\n\n public onFlowStateChange(handler: (flow: Flow, previousFlow?: Flow) => void) {\n this.onFlowStateChangeHandlers.push(handler)\n }\n\n public removeOnFlowStateChangeHandler(handler: (flow: Flow, previousFlow?: Flow) => void) {\n this.onFlowStateChangeHandlers = this.onFlowStateChangeHandlers.filter((h) => h !== handler)\n }\n\n private async initIfNeeded() {\n if (this.initPromise !== null) {\n return this.initPromise\n } else {\n return this.init(this.config)\n }\n }\n\n private async refreshUserFlowStates(): 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 (\n target[key] &&\n target[key].flowState &&\n (JSON.stringify(target[key].flowState) !== JSON.stringify(value.flowState) ||\n JSON.stringify(target[key].stepStates) !== JSON.stringify(value.stepStates) ||\n JSON.stringify(target[key].shouldTrigger) !== JSON.stringify(value.shouldTrigger))\n ) {\n that.triggerEventHandlers(target[key])\n }\n\n target[key] = value\n return true\n },\n }\n\n frigadeGlobalState[globalStateKey] = {\n refreshUserFlowStates: async () => {},\n userFlowStates: new Proxy({}, validator),\n }\n frigadeGlobalState[globalStateKey].refreshUserFlowStates = async () => {\n const userFlowStatesRaw = await this.fetch(\n `/userFlowStates?foreignUserId=${this.config.userId}${\n this.config.organizationId ? `&foreignUserGroupId=${this.config.organizationId}` : ''\n }`\n )\n if (userFlowStatesRaw && userFlowStatesRaw.data) {\n let userFlowStates = userFlowStatesRaw.data as UserFlowState[]\n userFlowStates.forEach((userFlowState) => {\n frigadeGlobalState[globalStateKey].userFlowStates[userFlowState.flowId] = userFlowState\n })\n }\n }\n }\n\n await frigadeGlobalState[globalStateKey].refreshUserFlowStates()\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await this.fetch('/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowDatas = flowDataRaw.data as FlowDataRaw[]\n flowDatas.forEach((flowData) => {\n this.flows.push(new Flow(this.config, flowData))\n })\n }\n }\n\n private async triggerEventHandlers(previousUserFlowState: UserFlowState) {\n if (previousUserFlowState) {\n this.flows.forEach((flow) => {\n if (flow.id == previousUserFlowState.flowId) {\n this.onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlows = this.previousFlows.get(handler)\n const lastFlow = lastFlows ? lastFlows.get(flow.id) : undefined\n handler(flow, lastFlow)\n if (!lastFlows) {\n this.previousFlows.set(handler, new Map())\n }\n this.previousFlows.get(handler).set(flow.id, flow)\n })\n }\n })\n }\n }\n}\n"],"mappings":";AAAO,IAAMA,EAAiB,QCC9B,OAAOC,MAAW,cAClB,OAAS,MAAMC,MAAc,OAGtB,IAAMC,EAAiB,iBACjBC,EAAe,eACfC,EAAe,eACfC,EAAmB,mBACnBC,EAAiB,iBACjBC,EAAe,eAGtBC,EAAoB,wBACpBC,EAAsB,0BACtBC,EAAY,oBACZC,EAAe,SAEd,SAASC,EAASC,EAAW,CAClC,OAAO,KAAK,MAAM,KAAK,UAAUA,CAAG,CAAC,CACvC,CAEO,SAASC,EAAWC,EAAgB,CACzC,MAAO,CACL,QAAS,CACP,cAAe,UAAUA,IACzB,eAAgB,mBAChB,wBAAyBC,EACzB,yBAA0B,YAC5B,CACF,CACF,CAEA,SAASC,EAAgBC,EAAa,CACpC,OAAI,QAAU,OAAO,aACZ,OAAO,aAAa,QAAQA,CAAG,EAEjC,IACT,CAEA,SAASC,EAAgBD,EAAaE,EAAe,CAC/C,QAAU,OAAO,cACnB,OAAO,aAAa,QAAQF,EAAKE,CAAK,CAE1C,CAEO,SAASC,GAAuB,CACjC,QAAU,OAAO,cAEnB,OAAO,KAAK,OAAO,YAAY,EAAE,QAASH,GAAQ,CAC5CA,EAAI,WAAW,UAAU,GAC3B,OAAO,aAAa,WAAWA,CAAG,CAEtC,CAAC,CAEL,CAEA,eAAsBI,EAAcC,EAAaC,EAAc,CAC7D,IAAMC,EAAgBjB,EAAoBe,EACpCG,EAAkBjB,EAAsBc,EAC9C,GAAI,Q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AK,cAAc,IAAIhB,CAAO,EAC1CiB,EAAWD,EAAYA,EAAU,IAAInB,EAAK,EAAE,EAAI,OACtDG,EAAQH,EAAMoB,CAAQ,EACjBD,GACH,KAAK,cAAc,IAAIhB,EAAS,IAAI,GAAK,EAE3C,KAAK,cAAc,IAAIA,CAAO,EAAE,IAAIH,EAAK,GAAIA,CAAI,CACnD,CAAC,CAEL,CAAC,CAEL,CACF","names":["VERSION_NUMBER","fetch","uuidv4","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","clone","obj","getHeaders","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","resetAllLocalStorage","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","fetch","error","generateGuestId","guestId","uuidv4","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","path","options","gracefulFetch","getHeaders","Flow","Fetchable","config","flowDataRaw","flowDataYml","steps","userFlowState","COMPLETED_FLOW","STARTED_FLOW","SKIPPED_FLOW","hasCompleted","targetingShouldHideFlow","step","index","userFlowStateStep","stepObj","COMPLETED_STEP","STARTED_STEP","properties","currentStep","copy","clone","frigadeGlobalState","getGlobalStateKey","updatedUserFlowState","isLastStep","nextStepId","NOT_STARTED_FLOW","currentStepId","key","Frigade","Fetchable","apiKey","config","userId","properties","organizationId","event","flowId","flow","resetAllLocalStorage","generateGuestId","handler","h","globalStateKey","getGlobalStateKey","frigadeGlobalState","that","validator","target","key","value","userFlowStatesRaw","userFlowState","flowDataRaw","flowData","Flow","previousUserFlowState","lastFlows","lastFlow"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frigade/js",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "The official Javascript SDK for Frigade.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",