@frigade/js 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -1,4 +1,59 @@
1
- interface FlowStepData {
1
+ interface FrigadeConfig {
2
+ /**
3
+ * API url to use for all requests. Defaults to https://api.frigade.com
4
+ */
5
+ apiUrl?: string;
6
+ /**
7
+ * User ID to use for all requests. Defaults to null.
8
+ */
9
+ userId?: string;
10
+ /**
11
+ * Organization ID to use for all requests. Defaults to null.
12
+ */
13
+ organizationId?: string;
14
+ }
15
+ interface InternalConfig {
16
+ apiKey: string;
17
+ userId?: string;
18
+ organizationId?: string;
19
+ }
20
+
21
+ interface FlowDataRaw {
22
+ id: number;
23
+ name: string;
24
+ description: string;
25
+ data: string;
26
+ createdAt: string;
27
+ modifiedAt: string;
28
+ slug: string;
29
+ targetingLogic: string;
30
+ type: FlowType;
31
+ triggerType: TriggerType;
32
+ status: FlowStatus;
33
+ version: number;
34
+ active: boolean;
35
+ }
36
+ declare enum FlowType {
37
+ CHECKLIST = "CHECKLIST",
38
+ FORM = "FORM",
39
+ TOUR = "TOUR",
40
+ SUPPORT = "SUPPORT",
41
+ CUSTOM = "CUSTOM",
42
+ BANNER = "BANNER",
43
+ EMBEDDED_TIP = "EMBEDDED_TIP",
44
+ NPS_SURVEY = "NPS_SURVEY"
45
+ }
46
+ declare enum TriggerType {
47
+ MANUAL = "MANUAL",
48
+ AUTOMATIC = "AUTOMATIC"
49
+ }
50
+ declare enum FlowStatus {
51
+ DRAFT = "DRAFT",
52
+ ACTIVE = "ACTIVE",
53
+ ARCHIVED = "ARCHIVED"
54
+ }
55
+
56
+ interface FlowStep {
2
57
  /**
3
58
  * Unique identifier for the step.
4
59
  */
@@ -62,7 +117,11 @@ interface FlowStepData {
62
117
  /**
63
118
  * Whether the step has been completed (equivalent to step status === COMPLETED_STEP)
64
119
  */
65
- complete: boolean;
120
+ isCompleted: boolean;
121
+ /**
122
+ * Whether the step has been completed (equivalent to step status === COMPLETED_STEP)
123
+ */
124
+ isStarted: boolean;
66
125
  /**
67
126
  * Whether the step is blocked (can't be accessed yet) based on `startCriteria`
68
127
  */
@@ -71,14 +130,6 @@ interface FlowStepData {
71
130
  * Whether the step is hidden (not shown in the list view) based on `visibilityCriteria`
72
131
  */
73
132
  hidden?: boolean;
74
- /**
75
- * Handler for when the primary button is clicked.
76
- */
77
- handlePrimaryButtonClick?: () => void;
78
- /**
79
- * Handler for when the secondary button is clicked.
80
- */
81
- handleSecondaryButtonClick?: () => void;
82
133
  props?: any;
83
134
  /**
84
135
  * Criteria that needs to be met for the step to complete
@@ -96,87 +147,75 @@ interface FlowStepData {
96
147
  * Whether the step is dismissible (for instance, tooltips or other non-essential steps)
97
148
  */
98
149
  dismissible?: boolean;
99
- }
100
- interface FrigadeConfig {
101
150
  /**
102
- * API url to use for all requests. Defaults to https://api.frigade.com
151
+ * Any other additional props defined in flow-data.yml
103
152
  */
104
- apiUrl?: string;
153
+ [x: string | number | symbol]: unknown;
105
154
  /**
106
- * User ID to use for all requests. Defaults to null.
155
+ * Function that marks the step started
107
156
  */
108
- userId?: string;
157
+ start: (properties?: Record<string | number, any>) => void;
109
158
  /**
110
- * Organization ID to use for all requests. Defaults to null.
159
+ * Function that marks the step completed
111
160
  */
112
- organizationId?: string;
113
- }
114
-
115
- interface FlowMetadata {
116
- id: number;
117
- name: string;
118
- description: string;
119
- data: string;
120
- createdAt: string;
121
- modifiedAt: string;
122
- slug: string;
123
- targetingLogic: string;
124
- type: FlowType;
125
- triggerType: TriggerType;
126
- status: FlowStatus;
127
- version: number;
128
- active: boolean;
129
- }
130
- declare enum FlowType {
131
- CHECKLIST = "CHECKLIST",
132
- FORM = "FORM",
133
- TOUR = "TOUR",
134
- SUPPORT = "SUPPORT",
135
- CUSTOM = "CUSTOM",
136
- BANNER = "BANNER",
137
- EMBEDDED_TIP = "EMBEDDED_TIP",
138
- NPS_SURVEY = "NPS_SURVEY"
139
- }
140
- declare enum TriggerType {
141
- MANUAL = "MANUAL",
142
- AUTOMATIC = "AUTOMATIC"
143
- }
144
- declare enum FlowStatus {
145
- DRAFT = "DRAFT",
146
- ACTIVE = "ACTIVE",
147
- ARCHIVED = "ARCHIVED"
161
+ complete: (properties?: Record<string | number, any>) => void;
148
162
  }
149
163
 
150
164
  declare class Flow {
151
165
  /**
152
166
  * THe Flow ID / slug of the flow
153
167
  */
154
- readonly id: string;
155
- /**
156
- * The status of the flow
157
- */
158
- readonly status: FlowStatus;
168
+ id: string;
159
169
  /**
160
170
  * The raw data defined in `flow-data.yml` as a JSON decoded object
161
171
  */
162
- readonly flowData: Record<any, any>;
172
+ flowData: Record<any, any>;
163
173
  /**
164
174
  * The steps contained in the `data` array in `flow-data.yml`
165
175
  */
166
- readonly steps: FlowStepData[];
176
+ steps: FlowStep[];
167
177
  /**
168
178
  * The user-facing title of the flow, if defined at the top level of `flow-data.yml`
169
179
  */
170
- readonly title?: string;
180
+ title?: string;
171
181
  /**
172
182
  * The user-facing description of the flow, if defined at the top level of `flow-data.yml`
173
183
  */
174
- readonly subtitle?: string;
184
+ subtitle?: string;
175
185
  /**
176
186
  * The metadata of the flow.
177
187
  */
178
- readonly metadata: FlowMetadata;
179
- constructor(id: string, status: FlowStatus, rawData: Record<any, any>, steps: FlowStepData[], title?: string, subtitle?: string, metadata?: FlowMetadata);
188
+ metadata: FlowDataRaw;
189
+ /**
190
+ * Whether the flow is completed or not
191
+ */
192
+ isCompleted: boolean;
193
+ /**
194
+ * Whether the flow is started or not
195
+ */
196
+ isStarted: boolean;
197
+ private flowDataRaw;
198
+ private internalConfig;
199
+ constructor(internalConfig: InternalConfig, flowDataRaw: FlowDataRaw);
200
+ private initFromRawData;
201
+ /**
202
+ * Function that marks the flow started
203
+ */
204
+ start(properties?: Record<string | number, any>): Promise<void>;
205
+ /**
206
+ * Function that marks the flow completed
207
+ */
208
+ complete(properties?: Record<string | number, any>): Promise<void>;
209
+ /**
210
+ * Function that restarts the flow/marks it not started
211
+ */
212
+ restart(): Promise<void>;
213
+ /**
214
+ * Function that gets current step index
215
+ */
216
+ getCurrentStepIndex(): number;
217
+ private getUserFlowState;
218
+ private refreshUserFlowState;
180
219
  }
181
220
 
182
221
  declare class Frigade {
@@ -185,11 +224,7 @@ declare class Frigade {
185
224
  private organizationId?;
186
225
  private config?;
187
226
  private hasInitialized;
188
- /**
189
- * Map flow IDs to their current state
190
- * @private
191
- */
192
- private userFlowStatuses;
227
+ private internalConfig?;
193
228
  private flows;
194
229
  init(apiKey: string, config?: FrigadeConfig): Promise<void>;
195
230
  identify(userId: string, properties?: Record<string, any>): Promise<void>;
@@ -201,6 +236,7 @@ declare class Frigade {
201
236
  private errorOnUninitialized;
202
237
  private refreshUserFlowStates;
203
238
  private refreshFlows;
239
+ private refreshInternalConfig;
204
240
  }
205
241
  declare const frigade: Frigade;
206
242
 
package/lib/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- var m=Object.create;var d=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty;var P=(e,t)=>{for(var i in t)d(e,i,{get:t[i],enumerable:!0})},p=(e,t,i,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of _(t))!R.call(e,r)&&r!==i&&d(e,r,{get:()=>t[r],enumerable:!(a=I(t,r))||a.enumerable});return e};var L=(e,t,i)=>(i=e!=null?m(D(e)):{},p(t||!e||!e.__esModule?d(i,"default",{value:e,enumerable:!0}):i,e)),b=e=>p(d({},"__esModule",{value:!0}),e);var W={};P(W,{Flow:()=>o,default:()=>N});module.exports=b(W);var S="1.0.1 ";var y=L(require("cross-fetch")),F=require("uuid");var A="frigade-last-call-at-",U="frigade-last-call-data-",h="frigade-guest-key",z="guest_";function x(e){return{config:{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Frigade-SDK-Version":S,"X-Frigade-SDK-Platform":"Javascript"}}}}function g(e){return window&&window.localStorage?window.localStorage.getItem(e):null}function T(e,t){window&&window.localStorage&&window.localStorage.setItem(e,t)}function E(){window&&window.localStorage&&Object.keys(window.localStorage).forEach(e=>{e.startsWith("frigade-")&&window.localStorage.removeItem(e)})}async function v(e,t){let i=A+e,a=U+e;if(window&&window.localStorage&&t&&t.body&&t.method==="POST"){let s=g(i),l=g(a);if(s&&l&&l==t.body){let u=new Date(s);if(new Date().getTime()-u.getTime()<1e3)return c()}T(i,new Date().toISOString()),T(a,t.body)}let r;try{r=await(0,y.default)(e,t)}catch(s){return c(s)}return r?r.staus>=400?c(r.statusText):r.json():c()}function c(e){return e&&console.log("Call to Frigade failed",e),{json:()=>({})}}function f(){if(window&&window.localStorage){let e=g(h);return e||(e=`${z}${(0,F.v4)()}`,window.localStorage.setItem(h,e)),e}}function n(e,t,i){return v(`//api.frigade.com/v1/public${t}`,{...i??{},...x(e).config})}var o=class{constructor(t,i,a,r,s,l,u){this.id=t,this.status=i,this.flowData=a,this.steps=r,this.title=s,this.subtitle=l,this.metadata=u}};var w=class{constructor(){this.userId=f();this.hasInitialized=!1;this.userFlowStatuses={};this.flows=[]}async init(t,i){this.apiKey=t,this.config=i,i!=null&&i.userId&&(this.userId=i.userId),i!=null&&i.organizationId&&(this.organizationId=i.organizationId),await Promise.all([this.refreshUserFlowStates(),this.refreshFlows()]),this.hasInitialized=!0}async identify(t,i){this.errorOnUninitialized(),this.userId=t,await n(this.apiKey,"/users",{method:"POST",body:JSON.stringify({foreignId:this.userId,properties:i})}),await this.refreshUserFlowStates()}async group(t,i){this.errorOnUninitialized(),this.organizationId=t,await n(this.apiKey,"/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,properties:i})}),await this.refreshUserFlowStates()}async track(t,i){this.errorOnUninitialized(),await n(this.apiKey,"/track",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,event:t,properties:i})})}async getFlow(t){return this.errorOnUninitialized(),this.flows.find(i=>i.id==t)}async getFlows(){return this.errorOnUninitialized(),this.flows}async reset(){E(),this.userId=f(),this.organizationId=void 0}errorOnUninitialized(){if(!this.hasInitialized)throw new Error("Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.")}async refreshUserFlowStates(){let t=await n(this.apiKey,`/userFlowStates?foreignUserId=${this.userId}${this.organizationId?`&foreignUserGroupId=${this.organizationId}`:""}`);t&&t.data&&t.data.forEach(a=>{this.userFlowStatuses[a.flowId]=a})}async refreshFlows(){this.flows=[];let t=await n(this.apiKey,"/flows");t&&t.data&&t.data.forEach(a=>{let r=JSON.parse(a.data);this.flows.push(new o(a.slug,a.status,r,(r==null?void 0:r.data)??[],r==null?void 0:r.title,r==null?void 0:r.subtitle,a))})}},C=new w,O=C;var N=O;0&&(module.exports={Flow});
2
+ var A=Object.create;var h=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var v=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var K=(i,t)=>{for(var e in t)h(i,e,{get:t[e],enumerable:!0})},O=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of x(t))!z.call(i,a)&&a!==e&&h(i,a,{get:()=>t[a],enumerable:!(r=L(t,a))||r.enumerable});return i};var N=(i,t,e)=>(e=i!=null?A(v(i)):{},O(t||!i||!i.__esModule?h(e,"default",{value:i,enumerable:!0}):e,i)),G=i=>O(h({},"__esModule",{value:!0}),i);var V={};K(V,{Flow:()=>d,default:()=>j});module.exports=G(V);var D="1.0.2 ";var b=N(require("cross-fetch")),R=require("uuid");var T="COMPLETED_FLOW";var I="STARTED_FLOW",U="NOT_STARTED_FLOW",S="COMPLETED_STEP",g="STARTED_STEP",W="frigade-last-call-at-",J="frigade-last-call-data-",C="frigade-guest-key",M="guest_";function $(i){return{config:{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Frigade-SDK-Version":D,"X-Frigade-SDK-Platform":"Javascript"}}}}function y(i){return window&&window.localStorage?window.localStorage.getItem(i):null}function E(i,t){window&&window.localStorage&&window.localStorage.setItem(i,t)}function _(){window&&window.localStorage&&Object.keys(window.localStorage).forEach(i=>{i.startsWith("frigade-")&&window.localStorage.removeItem(i)})}async function k(i,t){let e=W+i,r=J+i;if(window&&window.localStorage&&t&&t.body&&t.method==="POST"){let s=y(e),w=y(r);if(s&&w&&w==t.body){let n=new Date(s);if(new Date().getTime()-n.getTime()<1e3)return u()}E(e,new Date().toISOString()),E(r,t.body)}let a;try{a=await(0,b.default)(i,t)}catch(s){return u(s)}return a?a.staus>=400?u(a.statusText):a.json():u()}function u(i){return i&&console.log("Call to Frigade failed",i),{json:()=>({})}}function F(){if(window&&window.localStorage){let i=y(C);return i||(i=`${M}${(0,R.v4)()}`,window.localStorage.setItem(C,i)),i}}function o(i,t,e){return k(`//api.frigade.com/v1/public${t}`,{...e??{},...$(i).config})}var l={};function p(i){return`${i.apiKey}:${i.userId??""}:${i.organizationId??""}`}var d=class{constructor(t,e){this.internalConfig=t,this.flowDataRaw=e,this.initFromRawData(e)}initFromRawData(t){let e=JSON.parse(t.data),r=e.data;this.id=t.slug,this.metadata=t,this.flowData=e,this.title=this.flowData.title,this.subtitle=this.flowData.subtitle;let a=this.getUserFlowState();this.isCompleted=a.flowState==T,this.isStarted=a.flowState==I,this.steps=[...r.map(s=>{let w=a.stepStates[s.id],n={...s,isCompleted:w.actionType==S,isStarted:w.actionType==g};return n.start=async c=>{n.isCompleted=!0,await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:s.id,data:c??{},createdAt:new Date().toISOString(),actionType:g})}),await this.refreshUserFlowState();let f=this.getUserFlowState();n.isCompleted=f.stepStates[s.id].actionType==S,n.isStarted=f.stepStates[s.id].actionType==g},n.complete=async c=>{n.isCompleted=!0,await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:s.id,data:c??{},createdAt:new Date().toISOString(),actionType:S})}),await this.refreshUserFlowState();let f=this.getUserFlowState();n.isCompleted=f.stepStates[s.id].actionType==S,n.isStarted=f.stepStates[s.id].actionType==g},n})]}async start(t){let e=this.getCurrentStepIndex(),r=e!=-1?this.steps[e].id:"unknown";await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:r,data:t??{},createdAt:new Date().toISOString(),actionType:I})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async complete(t){let e=this.getCurrentStepIndex(),r=e!=-1?this.steps[e].id:"unknown";await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:r,data:t??{},createdAt:new Date().toISOString(),actionType:T})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async restart(){await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:"unknown",data:{},createdAt:new Date().toISOString(),actionType:U})})}getCurrentStepIndex(){let t=this.getUserFlowState();if(!t)return 0;let e=t.lastStepId,r=this.steps.findIndex(a=>a.id===e);return r==-1?0:r}getUserFlowState(){return l[p(this.internalConfig)].userFlowStates[this.id]}async refreshUserFlowState(){await l[p(this.internalConfig)].refreshUserFlowStates()}};var m=class{constructor(){this.userId=F();this.hasInitialized=!1;this.flows=[]}async init(t,e){this.apiKey=t,this.config=e,e!=null&&e.userId&&(this.userId=e.userId),e!=null&&e.organizationId&&(this.organizationId=e.organizationId),this.refreshInternalConfig(),await this.refreshUserFlowStates(),await this.refreshFlows(),this.hasInitialized=!0}async identify(t,e){this.errorOnUninitialized(),this.userId=t,this.refreshInternalConfig(),await o(this.apiKey,"/users",{method:"POST",body:JSON.stringify({foreignId:this.userId,properties:e})}),await this.refreshUserFlowStates()}async group(t,e){this.errorOnUninitialized(),this.organizationId=t,this.refreshInternalConfig(),await o(this.apiKey,"/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,properties:e})}),await this.refreshUserFlowStates()}async track(t,e){this.errorOnUninitialized(),await o(this.apiKey,"/track",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,event:t,properties:e})})}async getFlow(t){return this.errorOnUninitialized(),this.flows.find(e=>e.id==t)}async getFlows(){return this.errorOnUninitialized(),this.flows}async reset(){_(),this.userId=F(),this.organizationId=void 0}errorOnUninitialized(){if(!this.hasInitialized)throw new Error("Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.")}async refreshUserFlowStates(){let t=p(this.internalConfig);l[t]={refreshUserFlowStates:async()=>{},userFlowStates:{}},l[t].refreshUserFlowStates=async()=>{let e=await o(this.apiKey,`/userFlowStates?foreignUserId=${this.userId}${this.organizationId?`&foreignUserGroupId=${this.organizationId}`:""}`);e&&e.data&&e.data.forEach(a=>{l[t].userFlowStates[a.flowId]=a})},await l[t].refreshUserFlowStates()}async refreshFlows(){this.flows=[];let t=await o(this.apiKey,"/flows");t&&t.data&&t.data.forEach(r=>{this.flows.push(new d(this.internalConfig,r))})}refreshInternalConfig(){this.internalConfig={apiKey:this.apiKey,userId:this.userId,organizationId:this.organizationId}}},B=new m,P=B;var j=P;0&&(module.exports={Flow});
3
3
  //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/core/version.ts","../src/shared/utils.ts","../src/core/flow.ts","../src/core/frigade.ts"],"sourcesContent":["import frigade from './core/frigade'\nimport Flow from './core/flow'\n\nexport { Flow }\n\nexport default frigade\n","export const VERSION_NUMBER = '1.0.1 '\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 ABORTED_FLOW = 'ABORTED_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' | 'ABORTED_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\nfunction getConfig(apiKey: string) {\n return {\n config: {\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}\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 (window && window.localStorage) {\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 ...getConfig(apiKey).config,\n })\n}\n","import { FlowStepData } from '../types'\nimport { FlowMetadata, FlowStatus } from './types'\n\nexport default class Flow {\n /**\n * THe Flow ID / slug of the flow\n */\n public readonly id: string\n /**\n * The status of the flow\n */\n public readonly status: FlowStatus\n /**\n * The raw data defined in `flow-data.yml` as a JSON decoded object\n */\n public readonly flowData: Record<any, any>\n /**\n * The steps contained in the `data` array in `flow-data.yml`\n */\n public readonly steps: FlowStepData[]\n /**\n * The user-facing title of the flow, if defined at the top level of `flow-data.yml`\n */\n public readonly title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `flow-data.yml`\n */\n public readonly subtitle?: string\n /**\n * The metadata of the flow.\n */\n public readonly metadata: FlowMetadata\n\n constructor(\n id: string,\n status: FlowStatus,\n rawData: Record<any, any>,\n steps: FlowStepData[],\n title?: string,\n subtitle?: string,\n metadata?: FlowMetadata\n ) {\n this.id = id\n this.status = status\n this.flowData = rawData\n this.steps = steps\n this.title = title\n this.subtitle = subtitle\n this.metadata = metadata\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { fetcher, generateGuestId, resetAllLocalStorage } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowMetadata } from './types'\n\nexport class Frigade {\n private apiKey?: string\n private userId: string = generateGuestId()\n private organizationId?: string\n private config?: FrigadeConfig\n private hasInitialized = false\n /**\n * Map flow IDs to their current state\n * @private\n */\n private userFlowStatuses: Record<string, UserFlowState> = {}\n\n private flows: Flow[] = []\n\n public async init(apiKey: string, config?: FrigadeConfig): Promise<void> {\n this.apiKey = apiKey\n this.config = config\n if (config?.userId) {\n this.userId = config.userId\n }\n if (config?.organizationId) {\n this.organizationId = config.organizationId\n }\n await Promise.all([this.refreshUserFlowStates(), this.refreshFlows()])\n this.hasInitialized = true\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.userId = userId\n await fetcher(this.apiKey, '/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.userId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.organizationId = organizationId\n await fetcher(this.apiKey, '/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n await fetcher(this.apiKey, '/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n event,\n properties,\n }),\n })\n }\n\n public async getFlow(flowId: string) {\n this.errorOnUninitialized()\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n this.errorOnUninitialized()\n return this.flows\n }\n\n public async reset() {\n resetAllLocalStorage()\n this.userId = generateGuestId()\n this.organizationId = undefined\n }\n\n private errorOnUninitialized() {\n if (!this.hasInitialized) {\n throw new Error(\n 'Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.'\n )\n }\n }\n\n private async refreshUserFlowStates() {\n const userFlowStatesRaw = await fetcher(\n this.apiKey,\n `/userFlowStates?foreignUserId=${this.userId}${\n this.organizationId ? `&foreignUserGroupId=${this.organizationId}` : ''\n }`\n )\n if (userFlowStatesRaw && userFlowStatesRaw.data) {\n let userFlowStates = userFlowStatesRaw.data as UserFlowState[]\n userFlowStates.forEach((userFlowState) => {\n this.userFlowStatuses[userFlowState.flowId] = userFlowState\n })\n }\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await fetcher(this.apiKey, '/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowMetadatas = flowDataRaw.data as FlowMetadata[]\n flowMetadatas.forEach((flowMetadata) => {\n const rawData = JSON.parse(flowMetadata.data)\n this.flows.push(\n new Flow(\n flowMetadata.slug,\n flowMetadata.status,\n rawData,\n rawData?.data ?? [],\n rawData?.title,\n rawData?.subtitle,\n flowMetadata\n )\n )\n })\n }\n }\n}\n\nconst frigade = new Frigade()\nexport default frigade\n"],"mappings":";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GCAO,IAAMK,EAAiB,SCC9B,IAAAC,EAAkB,0BAClBC,EAA6B,gBAW7B,IAAMC,EAAoB,wBACpBC,EAAsB,0BACtBC,EAAY,oBACZC,EAAe,SAErB,SAASC,EAAUC,EAAgB,CACjC,MAAO,CACL,OAAQ,CACN,QAAS,CACP,cAAe,UAAUA,IACzB,eAAgB,mBAChB,wBAAyBC,EACzB,yBAA0B,YAC5B,CACF,CACF,CACF,CAEA,SAASC,EAAgBC,EAAa,CACpC,OAAI,QAAU,OAAO,aACZ,OAAO,aAAa,QAAQA,CAAG,EAEjC,IACT,CAEA,SAASC,EAAgBD,EAAaE,EAAe,CAC/C,QAA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C,CAEL,CACF,EAEMG,EAAU,IAAIlB,EACbmB,EAAQD,EJlIf,IAAOE,EAAQC","names":["src_exports","__export","Flow","src_default","__toCommonJS","VERSION_NUMBER","import_cross_fetch","import_uuid","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","getConfig","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","resetAllLocalStorage","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","fetch","error","generateGuestId","guestId","uuidv4","fetcher","path","Flow","id","status","rawData","steps","title","subtitle","metadata","Frigade","generateGuestId","apiKey","config","userId","properties","fetcher","organizationId","event","flowId","flow","resetAllLocalStorage","userFlowStatesRaw","userFlowState","flowDataRaw","flowMetadata","rawData","Flow","frigade","frigade_default","src_default","frigade_default"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/core/flow.ts","../src/core/frigade.ts"],"sourcesContent":["import frigade from './core/frigade'\nimport Flow from './core/flow'\n\nexport { Flow }\n\nexport default frigade\n","export const VERSION_NUMBER = '1.0.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 ABORTED_FLOW = 'ABORTED_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' | 'ABORTED_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\nfunction getConfig(apiKey: string) {\n return {\n config: {\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}\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 (window && window.localStorage) {\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 ...getConfig(apiKey).config,\n })\n}\n","import { InternalConfig, 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: InternalConfig): string {\n return `${internalConfig.apiKey}:${internalConfig.userId ?? ''}:${\n internalConfig.organizationId ?? ''\n }`\n}\n","import { InternalConfig, UserFlowState } from '../types'\nimport { FlowDataRaw } from './types'\nimport {\n COMPLETED_FLOW,\n COMPLETED_STEP,\n fetcher,\n NOT_STARTED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { FlowStep } from './flow-step'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\n\nexport default class Flow {\n /**\n * THe Flow ID / slug of the flow\n */\n public id: string\n /**\n * The raw data defined in `flow-data.yml` as a JSON decoded object\n */\n public flowData: Record<any, any>\n /**\n * The steps contained in the `data` array in `flow-data.yml`\n */\n public steps: FlowStep[]\n /**\n * The user-facing title of the flow, if defined at the top level of `flow-data.yml`\n */\n public title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `flow-data.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 private flowDataRaw: FlowDataRaw\n\n private internalConfig: InternalConfig\n\n constructor(internalConfig: InternalConfig, flowDataRaw: FlowDataRaw) {\n this.internalConfig = internalConfig\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.data\n this.id = flowDataRaw.slug\n this.metadata = flowDataRaw\n this.flowData = flowDataYml\n this.title = this.flowData.title\n this.subtitle = this.flowData.subtitle\n\n const userFlowState = this.getUserFlowState()\n\n this.isCompleted = userFlowState.flowState == COMPLETED_FLOW\n this.isStarted = userFlowState.flowState == STARTED_FLOW\n this.steps = [\n ...steps.map((step) => {\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 } as FlowStep\n\n stepObj.start = async (properties?: Record<string | number, any>) => {\n stepObj.isCompleted = true\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: step.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_STEP,\n }),\n })\n await this.refreshUserFlowState()\n const updatedUserFlowState = this.getUserFlowState()\n stepObj.isCompleted =\n updatedUserFlowState.stepStates[step.id].actionType == COMPLETED_STEP\n stepObj.isStarted = updatedUserFlowState.stepStates[step.id].actionType == STARTED_STEP\n }\n\n stepObj.complete = async (properties?: Record<string | number, any>) => {\n stepObj.isCompleted = true\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: step.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_STEP,\n }),\n })\n await this.refreshUserFlowState()\n const updatedUserFlowState = this.getUserFlowState()\n stepObj.isCompleted =\n updatedUserFlowState.stepStates[step.id].actionType == COMPLETED_STEP\n stepObj.isStarted = updatedUserFlowState.stepStates[step.id].actionType == STARTED_STEP\n }\n\n return stepObj\n }),\n ]\n }\n\n /**\n * Function that marks the flow started\n */\n public async start(properties?: Record<string | number, any>) {\n const currentStepIndex = this.getCurrentStepIndex()\n const currentStepId = currentStepIndex != -1 ? this.steps[currentStepIndex].id : 'unknown'\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: currentStepId,\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 const currentStepIndex = this.getCurrentStepIndex()\n const currentStepId = currentStepIndex != -1 ? this.steps[currentStepIndex].id : 'unknown'\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: currentStepId,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_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 await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: 'unknown',\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_FLOW,\n }),\n })\n }\n\n /**\n * Function that gets current step index\n */\n public getCurrentStepIndex(): number {\n // Find the userFlowState with most recent timestamp\n const userFlowState = this.getUserFlowState()\n if (!userFlowState) {\n return 0\n }\n const currentStepId = userFlowState.lastStepId\n const index = this.steps.findIndex((step) => step.id === currentStepId)\n return index == -1 ? 0 : index\n }\n\n private getUserFlowState(): UserFlowState {\n const userFlowStates = frigadeGlobalState[getGlobalStateKey(this.internalConfig)].userFlowStates\n return userFlowStates[this.id]\n }\n\n private async refreshUserFlowState() {\n await frigadeGlobalState[getGlobalStateKey(this.internalConfig)].refreshUserFlowStates()\n }\n}\n","import { FrigadeConfig, InternalConfig, UserFlowState } from '../types'\nimport { fetcher, generateGuestId, resetAllLocalStorage } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowDataRaw } from './types'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\n\nexport class Frigade {\n private apiKey?: string\n private userId: string = generateGuestId()\n private organizationId?: string\n private config?: FrigadeConfig\n private hasInitialized = false\n private internalConfig?: InternalConfig\n\n private flows: Flow[] = []\n\n public async init(apiKey: string, config?: FrigadeConfig): Promise<void> {\n this.apiKey = apiKey\n this.config = config\n if (config?.userId) {\n this.userId = config.userId\n }\n if (config?.organizationId) {\n this.organizationId = config.organizationId\n }\n this.refreshInternalConfig()\n await this.refreshUserFlowStates()\n await this.refreshFlows()\n this.hasInitialized = true\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.userId = userId\n this.refreshInternalConfig()\n await fetcher(this.apiKey, '/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.userId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.organizationId = organizationId\n this.refreshInternalConfig()\n await fetcher(this.apiKey, '/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n await fetcher(this.apiKey, '/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n event,\n properties,\n }),\n })\n }\n\n public async getFlow(flowId: string) {\n this.errorOnUninitialized()\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n this.errorOnUninitialized()\n return this.flows\n }\n\n public async reset() {\n resetAllLocalStorage()\n this.userId = generateGuestId()\n this.organizationId = undefined\n }\n\n private errorOnUninitialized() {\n if (!this.hasInitialized) {\n throw new Error(\n 'Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.'\n )\n }\n }\n\n private async refreshUserFlowStates(): Promise<void> {\n const globalStateKey = getGlobalStateKey(this.internalConfig)\n frigadeGlobalState[globalStateKey] = {\n refreshUserFlowStates: async () => {},\n userFlowStates: {},\n }\n frigadeGlobalState[globalStateKey].refreshUserFlowStates = async () => {\n const userFlowStatesRaw = await fetcher(\n this.apiKey,\n `/userFlowStates?foreignUserId=${this.userId}${\n this.organizationId ? `&foreignUserGroupId=${this.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 await frigadeGlobalState[globalStateKey].refreshUserFlowStates()\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await fetcher(this.apiKey, '/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowDatas = flowDataRaw.data as FlowDataRaw[]\n flowDatas.forEach((flowData) => {\n this.flows.push(new Flow(this.internalConfig, flowData))\n })\n }\n }\n\n private refreshInternalConfig() {\n this.internalConfig = {\n apiKey: this.apiKey,\n userId: this.userId,\n organizationId: this.organizationId,\n }\n }\n}\n\nconst frigade = new Frigade()\nexport default frigade\n"],"mappings":";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GCAO,IAAMK,EAAiB,SCC9B,IAAAC,EAAkB,0BAClBC,EAA6B,gBAGtB,IAAMC,EAAiB,iBAEv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OE,EAAQC","names":["src_exports","__export","Flow","src_default","__toCommonJS","VERSION_NUMBER","import_cross_fetch","import_uuid","COMPLETED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","getConfig","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","resetAllLocalStorage","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","fetch","error","generateGuestId","guestId","uuidv4","fetcher","path","frigadeGlobalState","getGlobalStateKey","internalConfig","Flow","internalConfig","flowDataRaw","flowDataYml","steps","userFlowState","COMPLETED_FLOW","STARTED_FLOW","step","userFlowStateStep","stepObj","COMPLETED_STEP","STARTED_STEP","properties","fetcher","updatedUserFlowState","currentStepIndex","currentStepId","NOT_STARTED_FLOW","index","frigadeGlobalState","getGlobalStateKey","Frigade","generateGuestId","apiKey","config","userId","properties","fetcher","organizationId","event","flowId","flow","resetAllLocalStorage","globalStateKey","getGlobalStateKey","frigadeGlobalState","userFlowStatesRaw","userFlowState","flowDataRaw","flowData","Flow","frigade","frigade_default","src_default","frigade_default"]}
package/lib/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- var w="1.0.1 ";import y from"cross-fetch";import{v4 as F}from"uuid";var E="frigade-last-call-at-",O="frigade-last-call-data-",p="frigade-guest-key",m="guest_";function I(i){return{config:{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Frigade-SDK-Version":w,"X-Frigade-SDK-Platform":"Javascript"}}}}function u(i){return window&&window.localStorage?window.localStorage.getItem(i):null}function S(i,t){window&&window.localStorage&&window.localStorage.setItem(i,t)}function h(){window&&window.localStorage&&Object.keys(window.localStorage).forEach(i=>{i.startsWith("frigade-")&&window.localStorage.removeItem(i)})}async function _(i,t){let e=E+i,a=O+i;if(window&&window.localStorage&&t&&t.body&&t.method==="POST"){let o=u(e),l=u(a);if(o&&l&&l==t.body){let c=new Date(o);if(new Date().getTime()-c.getTime()<1e3)return d()}S(e,new Date().toISOString()),S(a,t.body)}let r;try{r=await y(i,t)}catch(o){return d(o)}return r?r.staus>=400?d(r.statusText):r.json():d()}function d(i){return i&&console.log("Call to Frigade failed",i),{json:()=>({})}}function g(){if(window&&window.localStorage){let i=u(p);return i||(i=`${m}${F()}`,window.localStorage.setItem(p,i)),i}}function s(i,t,e){return _(`//api.frigade.com/v1/public${t}`,{...e??{},...I(i).config})}var n=class{constructor(t,e,a,r,o,l,c){this.id=t,this.status=e,this.flowData=a,this.steps=r,this.title=o,this.subtitle=l,this.metadata=c}};var f=class{constructor(){this.userId=g();this.hasInitialized=!1;this.userFlowStatuses={};this.flows=[]}async init(t,e){this.apiKey=t,this.config=e,e!=null&&e.userId&&(this.userId=e.userId),e!=null&&e.organizationId&&(this.organizationId=e.organizationId),await Promise.all([this.refreshUserFlowStates(),this.refreshFlows()]),this.hasInitialized=!0}async identify(t,e){this.errorOnUninitialized(),this.userId=t,await s(this.apiKey,"/users",{method:"POST",body:JSON.stringify({foreignId:this.userId,properties:e})}),await this.refreshUserFlowStates()}async group(t,e){this.errorOnUninitialized(),this.organizationId=t,await s(this.apiKey,"/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,properties:e})}),await this.refreshUserFlowStates()}async track(t,e){this.errorOnUninitialized(),await s(this.apiKey,"/track",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,event:t,properties:e})})}async getFlow(t){return this.errorOnUninitialized(),this.flows.find(e=>e.id==t)}async getFlows(){return this.errorOnUninitialized(),this.flows}async reset(){h(),this.userId=g(),this.organizationId=void 0}errorOnUninitialized(){if(!this.hasInitialized)throw new Error("Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.")}async refreshUserFlowStates(){let t=await s(this.apiKey,`/userFlowStates?foreignUserId=${this.userId}${this.organizationId?`&foreignUserGroupId=${this.organizationId}`:""}`);t&&t.data&&t.data.forEach(a=>{this.userFlowStatuses[a.flowId]=a})}async refreshFlows(){this.flows=[];let t=await s(this.apiKey,"/flows");t&&t.data&&t.data.forEach(a=>{let r=JSON.parse(a.data);this.flows.push(new n(a.slug,a.status,r,(r==null?void 0:r.data)??[],r==null?void 0:r.title,r==null?void 0:r.subtitle,a))})}},D=new f,T=D;var M=T;export{n as Flow,M as default};
2
+ var m="1.0.2 ";import R from"cross-fetch";import{v4 as U}from"uuid";var y="COMPLETED_FLOW";var T="STARTED_FLOW",C="NOT_STARTED_FLOW",S="COMPLETED_STEP",g="STARTED_STEP",_="frigade-last-call-at-",P="frigade-last-call-data-",O="frigade-guest-key",A="guest_";function L(i){return{config:{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Frigade-SDK-Version":m,"X-Frigade-SDK-Platform":"Javascript"}}}}function u(i){return window&&window.localStorage?window.localStorage.getItem(i):null}function D(i,t){window&&window.localStorage&&window.localStorage.setItem(i,t)}function E(){window&&window.localStorage&&Object.keys(window.localStorage).forEach(i=>{i.startsWith("frigade-")&&window.localStorage.removeItem(i)})}async function x(i,t){let e=_+i,a=P+i;if(window&&window.localStorage&&t&&t.body&&t.method==="POST"){let s=u(e),w=u(a);if(s&&w&&w==t.body){let n=new Date(s);if(new Date().getTime()-n.getTime()<1e3)return h()}D(e,new Date().toISOString()),D(a,t.body)}let r;try{r=await R(i,t)}catch(s){return h(s)}return r?r.staus>=400?h(r.statusText):r.json():h()}function h(i){return i&&console.log("Call to Frigade failed",i),{json:()=>({})}}function I(){if(window&&window.localStorage){let i=u(O);return i||(i=`${A}${U()}`,window.localStorage.setItem(O,i)),i}}function o(i,t,e){return x(`//api.frigade.com/v1/public${t}`,{...e??{},...L(i).config})}var l={};function p(i){return`${i.apiKey}:${i.userId??""}:${i.organizationId??""}`}var f=class{constructor(t,e){this.internalConfig=t,this.flowDataRaw=e,this.initFromRawData(e)}initFromRawData(t){let e=JSON.parse(t.data),a=e.data;this.id=t.slug,this.metadata=t,this.flowData=e,this.title=this.flowData.title,this.subtitle=this.flowData.subtitle;let r=this.getUserFlowState();this.isCompleted=r.flowState==y,this.isStarted=r.flowState==T,this.steps=[...a.map(s=>{let w=r.stepStates[s.id],n={...s,isCompleted:w.actionType==S,isStarted:w.actionType==g};return n.start=async c=>{n.isCompleted=!0,await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:s.id,data:c??{},createdAt:new Date().toISOString(),actionType:g})}),await this.refreshUserFlowState();let d=this.getUserFlowState();n.isCompleted=d.stepStates[s.id].actionType==S,n.isStarted=d.stepStates[s.id].actionType==g},n.complete=async c=>{n.isCompleted=!0,await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:s.id,data:c??{},createdAt:new Date().toISOString(),actionType:S})}),await this.refreshUserFlowState();let d=this.getUserFlowState();n.isCompleted=d.stepStates[s.id].actionType==S,n.isStarted=d.stepStates[s.id].actionType==g},n})]}async start(t){let e=this.getCurrentStepIndex(),a=e!=-1?this.steps[e].id:"unknown";await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:a,data:t??{},createdAt:new Date().toISOString(),actionType:T})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async complete(t){let e=this.getCurrentStepIndex(),a=e!=-1?this.steps[e].id:"unknown";await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:a,data:t??{},createdAt:new Date().toISOString(),actionType:y})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async restart(){await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:"unknown",data:{},createdAt:new Date().toISOString(),actionType:C})})}getCurrentStepIndex(){let t=this.getUserFlowState();if(!t)return 0;let e=t.lastStepId,a=this.steps.findIndex(r=>r.id===e);return a==-1?0:a}getUserFlowState(){return l[p(this.internalConfig)].userFlowStates[this.id]}async refreshUserFlowState(){await l[p(this.internalConfig)].refreshUserFlowStates()}};var F=class{constructor(){this.userId=I();this.hasInitialized=!1;this.flows=[]}async init(t,e){this.apiKey=t,this.config=e,e!=null&&e.userId&&(this.userId=e.userId),e!=null&&e.organizationId&&(this.organizationId=e.organizationId),this.refreshInternalConfig(),await this.refreshUserFlowStates(),await this.refreshFlows(),this.hasInitialized=!0}async identify(t,e){this.errorOnUninitialized(),this.userId=t,this.refreshInternalConfig(),await o(this.apiKey,"/users",{method:"POST",body:JSON.stringify({foreignId:this.userId,properties:e})}),await this.refreshUserFlowStates()}async group(t,e){this.errorOnUninitialized(),this.organizationId=t,this.refreshInternalConfig(),await o(this.apiKey,"/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,properties:e})}),await this.refreshUserFlowStates()}async track(t,e){this.errorOnUninitialized(),await o(this.apiKey,"/track",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,event:t,properties:e})})}async getFlow(t){return this.errorOnUninitialized(),this.flows.find(e=>e.id==t)}async getFlows(){return this.errorOnUninitialized(),this.flows}async reset(){E(),this.userId=I(),this.organizationId=void 0}errorOnUninitialized(){if(!this.hasInitialized)throw new Error("Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.")}async refreshUserFlowStates(){let t=p(this.internalConfig);l[t]={refreshUserFlowStates:async()=>{},userFlowStates:{}},l[t].refreshUserFlowStates=async()=>{let e=await o(this.apiKey,`/userFlowStates?foreignUserId=${this.userId}${this.organizationId?`&foreignUserGroupId=${this.organizationId}`:""}`);e&&e.data&&e.data.forEach(r=>{l[t].userFlowStates[r.flowId]=r})},await l[t].refreshUserFlowStates()}async refreshFlows(){this.flows=[];let t=await o(this.apiKey,"/flows");t&&t.data&&t.data.forEach(a=>{this.flows.push(new f(this.internalConfig,a))})}refreshInternalConfig(){this.internalConfig={apiKey:this.apiKey,userId:this.userId,organizationId:this.organizationId}}},v=new F,b=v;var H=b;export{f as Flow,H as default};
3
3
  //# sourceMappingURL=index.mjs.map
package/lib/index.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/version.ts","../src/shared/utils.ts","../src/core/flow.ts","../src/core/frigade.ts","../src/index.ts"],"sourcesContent":["export const VERSION_NUMBER = '1.0.1 '\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 ABORTED_FLOW = 'ABORTED_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' | 'ABORTED_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\nfunction getConfig(apiKey: string) {\n return {\n config: {\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}\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 (window && window.localStorage) {\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 ...getConfig(apiKey).config,\n })\n}\n","import { FlowStepData } from '../types'\nimport { FlowMetadata, FlowStatus } from './types'\n\nexport default class Flow {\n /**\n * THe Flow ID / slug of the flow\n */\n public readonly id: string\n /**\n * The status of the flow\n */\n public readonly status: FlowStatus\n /**\n * The raw data defined in `flow-data.yml` as a JSON decoded object\n */\n public readonly flowData: Record<any, any>\n /**\n * The steps contained in the `data` array in `flow-data.yml`\n */\n public readonly steps: FlowStepData[]\n /**\n * The user-facing title of the flow, if defined at the top level of `flow-data.yml`\n */\n public readonly title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `flow-data.yml`\n */\n public readonly subtitle?: string\n /**\n * The metadata of the flow.\n */\n public readonly metadata: FlowMetadata\n\n constructor(\n id: string,\n status: FlowStatus,\n rawData: Record<any, any>,\n steps: FlowStepData[],\n title?: string,\n subtitle?: string,\n metadata?: FlowMetadata\n ) {\n this.id = id\n this.status = status\n this.flowData = rawData\n this.steps = steps\n this.title = title\n this.subtitle = subtitle\n this.metadata = metadata\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { fetcher, generateGuestId, resetAllLocalStorage } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowMetadata } from './types'\n\nexport class Frigade {\n private apiKey?: string\n private userId: string = generateGuestId()\n private organizationId?: string\n private config?: FrigadeConfig\n private hasInitialized = false\n /**\n * Map flow IDs to their current state\n * @private\n */\n private userFlowStatuses: Record<string, UserFlowState> = {}\n\n private flows: Flow[] = []\n\n public async init(apiKey: string, config?: FrigadeConfig): Promise<void> {\n this.apiKey = apiKey\n this.config = config\n if (config?.userId) {\n this.userId = config.userId\n }\n if (config?.organizationId) {\n this.organizationId = config.organizationId\n }\n await Promise.all([this.refreshUserFlowStates(), this.refreshFlows()])\n this.hasInitialized = true\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.userId = userId\n await fetcher(this.apiKey, '/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.userId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.organizationId = organizationId\n await fetcher(this.apiKey, '/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n await fetcher(this.apiKey, '/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n event,\n properties,\n }),\n })\n }\n\n public async getFlow(flowId: string) {\n this.errorOnUninitialized()\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n this.errorOnUninitialized()\n return this.flows\n }\n\n public async reset() {\n resetAllLocalStorage()\n this.userId = generateGuestId()\n this.organizationId = undefined\n }\n\n private errorOnUninitialized() {\n if (!this.hasInitialized) {\n throw new Error(\n 'Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.'\n )\n }\n }\n\n private async refreshUserFlowStates() {\n const userFlowStatesRaw = await fetcher(\n this.apiKey,\n `/userFlowStates?foreignUserId=${this.userId}${\n this.organizationId ? `&foreignUserGroupId=${this.organizationId}` : ''\n }`\n )\n if (userFlowStatesRaw && userFlowStatesRaw.data) {\n let userFlowStates = userFlowStatesRaw.data as UserFlowState[]\n userFlowStates.forEach((userFlowState) => {\n this.userFlowStatuses[userFlowState.flowId] = userFlowState\n })\n }\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await fetcher(this.apiKey, '/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowMetadatas = flowDataRaw.data as FlowMetadata[]\n flowMetadatas.forEach((flowMetadata) => {\n const rawData = JSON.parse(flowMetadata.data)\n this.flows.push(\n new Flow(\n flowMetadata.slug,\n flowMetadata.status,\n rawData,\n rawData?.data ?? [],\n rawData?.title,\n rawData?.subtitle,\n flowMetadata\n )\n )\n })\n }\n }\n}\n\nconst frigade = new Frigade()\nexport default frigade\n","import frigade from './core/frigade'\nimport Flow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KACxB,QAASC,GAAkB,CACxC,KAAK,iBAAiBA,EAAc,MAAM,EAAIA,CAChD,CAAC,CAEL,CAEA,MAAc,cAAe,CAC3B,KAAK,MAAQ,CAAC,EACd,IAAMC,EAAc,MAAMR,EAAQ,KAAK,OAAQ,QAAQ,EACnDQ,GAAeA,EAAY,MACTA,EAAY,KAClB,QAASC,GAAiB,CACtC,IAAMC,EAAU,KAAK,MAAMD,EAAa,IAAI,EAC5C,KAAK,MAAM,KACT,IAAIE,EACFF,EAAa,KACbA,EAAa,OACbC,GACAA,GAAA,YAAAA,EAAS,OAAQ,CAAC,EAClBA,GAAA,YAAAA,EAAS,MACTA,GAAA,YAAAA,EAAS,SACTD,CACF,CACF,CACF,CAAC,CAEL,CACF,EAEMG,EAAU,IAAIlB,EACbmB,EAAQD,EClIf,IAAOE,EAAQC","names":["VERSION_NUMBER","fetch","uuidv4","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","getConfig","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","resetAllLocalStorage","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","fetch","error","generateGuestId","guestId","uuidv4","fetcher","path","Flow","id","status","rawData","steps","title","subtitle","metadata","Frigade","generateGuestId","apiKey","config","userId","properties","fetcher","organizationId","event","flowId","flow","resetAllLocalStorage","userFlowStatesRaw","userFlowState","flowDataRaw","flowMetadata","rawData","Flow","frigade","frigade_default","src_default","frigade_default"]}
1
+ {"version":3,"sources":["../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/core/flow.ts","../src/core/frigade.ts","../src/index.ts"],"sourcesContent":["export const VERSION_NUMBER = '1.0.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 ABORTED_FLOW = 'ABORTED_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' | 'ABORTED_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\nfunction getConfig(apiKey: string) {\n return {\n config: {\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}\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 (window && window.localStorage) {\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 ...getConfig(apiKey).config,\n })\n}\n","import { InternalConfig, 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: InternalConfig): string {\n return `${internalConfig.apiKey}:${internalConfig.userId ?? ''}:${\n internalConfig.organizationId ?? ''\n }`\n}\n","import { InternalConfig, UserFlowState } from '../types'\nimport { FlowDataRaw } from './types'\nimport {\n COMPLETED_FLOW,\n COMPLETED_STEP,\n fetcher,\n NOT_STARTED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { FlowStep } from './flow-step'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\n\nexport default class Flow {\n /**\n * THe Flow ID / slug of the flow\n */\n public id: string\n /**\n * The raw data defined in `flow-data.yml` as a JSON decoded object\n */\n public flowData: Record<any, any>\n /**\n * The steps contained in the `data` array in `flow-data.yml`\n */\n public steps: FlowStep[]\n /**\n * The user-facing title of the flow, if defined at the top level of `flow-data.yml`\n */\n public title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `flow-data.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 private flowDataRaw: FlowDataRaw\n\n private internalConfig: InternalConfig\n\n constructor(internalConfig: InternalConfig, flowDataRaw: FlowDataRaw) {\n this.internalConfig = internalConfig\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.data\n this.id = flowDataRaw.slug\n this.metadata = flowDataRaw\n this.flowData = flowDataYml\n this.title = this.flowData.title\n this.subtitle = this.flowData.subtitle\n\n const userFlowState = this.getUserFlowState()\n\n this.isCompleted = userFlowState.flowState == COMPLETED_FLOW\n this.isStarted = userFlowState.flowState == STARTED_FLOW\n this.steps = [\n ...steps.map((step) => {\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 } as FlowStep\n\n stepObj.start = async (properties?: Record<string | number, any>) => {\n stepObj.isCompleted = true\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: step.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_STEP,\n }),\n })\n await this.refreshUserFlowState()\n const updatedUserFlowState = this.getUserFlowState()\n stepObj.isCompleted =\n updatedUserFlowState.stepStates[step.id].actionType == COMPLETED_STEP\n stepObj.isStarted = updatedUserFlowState.stepStates[step.id].actionType == STARTED_STEP\n }\n\n stepObj.complete = async (properties?: Record<string | number, any>) => {\n stepObj.isCompleted = true\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: step.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_STEP,\n }),\n })\n await this.refreshUserFlowState()\n const updatedUserFlowState = this.getUserFlowState()\n stepObj.isCompleted =\n updatedUserFlowState.stepStates[step.id].actionType == COMPLETED_STEP\n stepObj.isStarted = updatedUserFlowState.stepStates[step.id].actionType == STARTED_STEP\n }\n\n return stepObj\n }),\n ]\n }\n\n /**\n * Function that marks the flow started\n */\n public async start(properties?: Record<string | number, any>) {\n const currentStepIndex = this.getCurrentStepIndex()\n const currentStepId = currentStepIndex != -1 ? this.steps[currentStepIndex].id : 'unknown'\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: currentStepId,\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 const currentStepIndex = this.getCurrentStepIndex()\n const currentStepId = currentStepIndex != -1 ? this.steps[currentStepIndex].id : 'unknown'\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: currentStepId,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_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 await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: 'unknown',\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_FLOW,\n }),\n })\n }\n\n /**\n * Function that gets current step index\n */\n public getCurrentStepIndex(): number {\n // Find the userFlowState with most recent timestamp\n const userFlowState = this.getUserFlowState()\n if (!userFlowState) {\n return 0\n }\n const currentStepId = userFlowState.lastStepId\n const index = this.steps.findIndex((step) => step.id === currentStepId)\n return index == -1 ? 0 : index\n }\n\n private getUserFlowState(): UserFlowState {\n const userFlowStates = frigadeGlobalState[getGlobalStateKey(this.internalConfig)].userFlowStates\n return userFlowStates[this.id]\n }\n\n private async refreshUserFlowState() {\n await frigadeGlobalState[getGlobalStateKey(this.internalConfig)].refreshUserFlowStates()\n }\n}\n","import { FrigadeConfig, InternalConfig, UserFlowState } from '../types'\nimport { fetcher, generateGuestId, resetAllLocalStorage } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowDataRaw } from './types'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\n\nexport class Frigade {\n private apiKey?: string\n private userId: string = generateGuestId()\n private organizationId?: string\n private config?: FrigadeConfig\n private hasInitialized = false\n private internalConfig?: InternalConfig\n\n private flows: Flow[] = []\n\n public async init(apiKey: string, config?: FrigadeConfig): Promise<void> {\n this.apiKey = apiKey\n this.config = config\n if (config?.userId) {\n this.userId = config.userId\n }\n if (config?.organizationId) {\n this.organizationId = config.organizationId\n }\n this.refreshInternalConfig()\n await this.refreshUserFlowStates()\n await this.refreshFlows()\n this.hasInitialized = true\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.userId = userId\n this.refreshInternalConfig()\n await fetcher(this.apiKey, '/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.userId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.organizationId = organizationId\n this.refreshInternalConfig()\n await fetcher(this.apiKey, '/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n await fetcher(this.apiKey, '/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n event,\n properties,\n }),\n })\n }\n\n public async getFlow(flowId: string) {\n this.errorOnUninitialized()\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n this.errorOnUninitialized()\n return this.flows\n }\n\n public async reset() {\n resetAllLocalStorage()\n this.userId = generateGuestId()\n this.organizationId = undefined\n }\n\n private errorOnUninitialized() {\n if (!this.hasInitialized) {\n throw new Error(\n 'Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.'\n )\n }\n }\n\n private async refreshUserFlowStates(): Promise<void> {\n const globalStateKey = getGlobalStateKey(this.internalConfig)\n frigadeGlobalState[globalStateKey] = {\n refreshUserFlowStates: async () => {},\n userFlowStates: {},\n }\n frigadeGlobalState[globalStateKey].refreshUserFlowStates = async () => {\n const userFlowStatesRaw = await fetcher(\n this.apiKey,\n `/userFlowStates?foreignUserId=${this.userId}${\n this.organizationId ? `&foreignUserGroupId=${this.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 await frigadeGlobalState[globalStateKey].refreshUserFlowStates()\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await fetcher(this.apiKey, '/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowDatas = flowDataRaw.data as FlowDataRaw[]\n flowDatas.forEach((flowData) => {\n this.flows.push(new Flow(this.internalConfig, flowData))\n })\n }\n }\n\n private refreshInternalConfig() {\n this.internalConfig = {\n apiKey: this.apiKey,\n userId: this.userId,\n organizationId: this.organizationId,\n }\n }\n}\n\nconst frigade = new Frigade()\nexport default frigade\n","import frigade from './core/frigade'\nimport Flow from './core/flow'\n\nexport { Flow }\n\nexport default frigade\n"],"mappings":";AAAO,IAAMA,EAAiB,SCC9B,OAAOC,MAAW,cAClB,OAAS,MAAMC,MAAc,OAGtB,IAAMC,EAAiB,iBAEvB,IAAMC,EAAe,eACfC,EAAmB,mBACnBC,EAAiB,iBACjBC,EAAe,eAGtBC,EAAoB,wBACpBC,EAAsB,0BACtBC,EAAY,oBACZC,EAAe,SAErB,SAASC,EAAUC,EAAgB,CACjC,MAAO,CACL,OAAQ,CACN,QAAS,CACP,cAAe,UAAUA,IACzB,eAAgB,mBAChB,wBAAyBC,EACzB,yBAA0B,YAC5B,CACF,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,EAAgBf,EAAoBa,EACpCG,EAAkBf,EAAsBY,EAC9C,GAAI,QAAU,OAAO,cAAgBC,GAAWA,EAAQ,MAAQA,EAAQ,SAAW,OAAQ,CACzF,IAAMG,EAAWV,EAAgBQ,CAAa,EACxCG,EAAeX,EAAgBS,CAAe,EACpD,GAAIC,GAAYC,GAAgBA,GAAgBJ,EAAQ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,MAAMX,EAAQ,KAAK,OAAQ,QAAQ,EACnDW,GAAeA,EAAY,MACbA,EAAY,KAClB,QAASC,GAAa,CAC9B,KAAK,MAAM,KAAK,IAAIC,EAAK,KAAK,eAAgBD,CAAQ,CAAC,CACzD,CAAC,CAEL,CAEQ,uBAAwB,CAC9B,KAAK,eAAiB,CACpB,OAAQ,KAAK,OACb,OAAQ,KAAK,OACb,eAAgB,KAAK,cACvB,CACF,CACF,EAEME,EAAU,IAAIpB,EACbqB,EAAQD,ECxIf,IAAOE,EAAQC","names":["VERSION_NUMBER","fetch","uuidv4","COMPLETED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","getConfig","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","resetAllLocalStorage","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","fetch","error","generateGuestId","guestId","uuidv4","fetcher","path","frigadeGlobalState","getGlobalStateKey","internalConfig","Flow","internalConfig","flowDataRaw","flowDataYml","steps","userFlowState","COMPLETED_FLOW","STARTED_FLOW","step","userFlowStateStep","stepObj","COMPLETED_STEP","STARTED_STEP","properties","fetcher","updatedUserFlowState","currentStepIndex","currentStepId","NOT_STARTED_FLOW","index","frigadeGlobalState","getGlobalStateKey","Frigade","generateGuestId","apiKey","config","userId","properties","fetcher","organizationId","event","flowId","flow","resetAllLocalStorage","globalStateKey","getGlobalStateKey","frigadeGlobalState","userFlowStatesRaw","userFlowState","flowDataRaw","flowData","Flow","frigade","frigade_default","src_default","frigade_default"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frigade/js",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "The official Javascript SDK for Frigade.",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",