@imtbl/sdk 0.45.3-alpha → 0.45.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/config.js CHANGED
@@ -1,267 +1,5 @@
1
1
  import axios from 'axios';
2
2
 
3
- const isNode = () => typeof window === 'undefined';
4
- const isBrowser = () => !isNode();
5
-
6
- var Detail;
7
- (function (Detail) {
8
- Detail["RUNTIME_ID"] = "rid";
9
- Detail["PASSPORT_CLIENT_ID"] = "passportClientId";
10
- Detail["ENVIRONMENT"] = "env";
11
- Detail["PUBLISHABLE_API_KEY"] = "pak";
12
- Detail["IDENTITY"] = "uid";
13
- Detail["DOMAIN"] = "domain";
14
- })(Detail || (Detail = {}));
15
- var Store;
16
- (function (Store) {
17
- Store["EVENTS"] = "events";
18
- Store["RUNTIME"] = "runtime";
19
- })(Store || (Store = {}));
20
- const POLLING_FREQUENCY = 5000;
21
-
22
- const IMTBL_API = 'https://api.x.immutable.com';
23
- async function post(path, data) {
24
- const client = axios.create({
25
- baseURL: IMTBL_API,
26
- });
27
- const payload = JSON.stringify(data);
28
- const body = {
29
- payload: btoa(payload),
30
- };
31
- const response = await client.post(path, body);
32
- return response.data;
33
- }
34
-
35
- /**
36
- * Abstraction on localstorage
37
- */
38
- const localStoragePrefix = '__IMX-';
39
- const hasLocalstorage = () => isBrowser() && window.localStorage;
40
- const parseItem = (payload) => {
41
- // Try to parse, if can't be parsed assume string
42
- // and return string
43
- if (payload === null)
44
- return undefined;
45
- try {
46
- return JSON.parse(payload);
47
- }
48
- catch (error) {
49
- // Assumes it's a string.
50
- return payload;
51
- }
52
- };
53
- const serialiseItem = (payload) => {
54
- if (typeof payload === 'string') {
55
- return payload;
56
- }
57
- return JSON.stringify(payload);
58
- };
59
- /**
60
- * GenKey will take into account the namespace
61
- * as well as if being run in the Link, it will tap into the link
62
- * @param {string} key
63
- * @returns key
64
- */
65
- const genKey = (key) => `${localStoragePrefix}${key}`;
66
- function getItem(key) {
67
- if (hasLocalstorage()) {
68
- return parseItem(window.localStorage.getItem(genKey(key)));
69
- }
70
- return undefined;
71
- }
72
- const setItem = (key, payload) => {
73
- if (hasLocalstorage()) {
74
- window.localStorage.setItem(genKey(key), serialiseItem(payload));
75
- return true;
76
- }
77
- return false;
78
- };
79
-
80
- // In memory storage for events and other data
81
- let EVENT_STORE;
82
- let RUNTIME_DETAILS;
83
- // Initialise store and runtime
84
- const initialise$1 = () => {
85
- EVENT_STORE = getItem(Store.EVENTS) || [];
86
- RUNTIME_DETAILS = getItem(Store.RUNTIME) || {};
87
- };
88
- initialise$1();
89
- // Runtime Details
90
- const storeDetail = (key, value) => {
91
- RUNTIME_DETAILS = {
92
- ...RUNTIME_DETAILS,
93
- [key]: value,
94
- };
95
- setItem(Store.RUNTIME, RUNTIME_DETAILS);
96
- };
97
- const getDetail = (key) => {
98
- // Handle the scenario where detail is a falsy value
99
- if (RUNTIME_DETAILS[key] === undefined) {
100
- return undefined;
101
- }
102
- return RUNTIME_DETAILS[key];
103
- };
104
- const getAllDetails = () => RUNTIME_DETAILS;
105
- // Events
106
- const getEvents = () => EVENT_STORE;
107
- const addEvent = (event) => {
108
- EVENT_STORE.push(event);
109
- setItem(Store.EVENTS, EVENT_STORE);
110
- };
111
- const removeSentEvents = (numberOfEvents) => {
112
- EVENT_STORE = EVENT_STORE.slice(numberOfEvents);
113
- setItem(Store.EVENTS, EVENT_STORE);
114
- };
115
- const flattenProperties = (properties) => {
116
- const propertyMap = [];
117
- Object.entries(properties).forEach(([key, value]) => {
118
- if (typeof value === 'string' || typeof value === 'number') {
119
- propertyMap.push([key, value.toString()]);
120
- }
121
- });
122
- return propertyMap;
123
- };
124
-
125
- let initialised = false;
126
- const isInitialised = () => initialised;
127
- const getReferrer = () => {
128
- if (isNode()) {
129
- return '';
130
- }
131
- if (window.location.ancestorOrigins
132
- && window.location.ancestorOrigins.length > 0) {
133
- return new URL(window.location.ancestorOrigins[0]).hostname;
134
- }
135
- return document.referrer ? new URL(window.document.referrer).hostname : '';
136
- };
137
- const runtimeHost = () => {
138
- if (isNode()) {
139
- return '';
140
- }
141
- if (window.opener || window.parent !== window) {
142
- return getReferrer();
143
- }
144
- return new URL(window.location.href).hostname;
145
- };
146
- const getRuntimeDetails = () => {
147
- if (isNode()) {
148
- return { browser: 'nodejs' };
149
- }
150
- const domain = runtimeHost();
151
- if (domain) {
152
- storeDetail(Detail.DOMAIN, domain);
153
- }
154
- return {
155
- browser: window.navigator.userAgent,
156
- domain,
157
- tz: Intl.DateTimeFormat().resolvedOptions().timeZone,
158
- screen: `${window.screen.width}x${window.screen.height}`,
159
- };
160
- };
161
- const initialise = async () => {
162
- const runtimeDetails = flattenProperties(getRuntimeDetails());
163
- // Get any existing runtimeId and send it along with the initialise
164
- const existingRuntimeId = getDetail(Detail.RUNTIME_ID);
165
- const body = {
166
- version: 1,
167
- data: {
168
- runtimeDetails,
169
- runtimeId: existingRuntimeId,
170
- },
171
- };
172
- const response = await post('/v1/sdk/initialise', body);
173
- // Get runtimeId and store it
174
- const { runtimeId } = response;
175
- storeDetail(Detail.RUNTIME_ID, runtimeId);
176
- initialised = true;
177
- };
178
-
179
- function errorBoundary(fn) {
180
- const wrappedFunction = ((...args) => {
181
- try {
182
- // Execute the original function
183
- const result = fn(...args);
184
- if (result instanceof Promise) {
185
- // Silent fail for now, in future
186
- // we can send errors to a logging service
187
- return result.catch(() => undefined);
188
- }
189
- return result;
190
- }
191
- catch (error) {
192
- // As above, fail silently for now
193
- return undefined;
194
- }
195
- });
196
- return wrappedFunction;
197
- }
198
-
199
- function isTestEnvironment() {
200
- if (typeof process === 'undefined') {
201
- return false;
202
- }
203
- return process.env.JEST_WORKER_ID !== undefined;
204
- }
205
-
206
- // Store the event in the event store
207
- const trackFn = (moduleName, eventName, properties) => {
208
- const event = {
209
- event: `${moduleName}.${eventName}`,
210
- time: new Date().toISOString(),
211
- ...(properties && { properties: flattenProperties(properties) }),
212
- };
213
- addEvent(event);
214
- };
215
- const track = errorBoundary(trackFn);
216
- // Sending events to the server
217
- const flushFn = async () => {
218
- // Don't flush if not initialised
219
- if (isInitialised() === false) {
220
- await initialise();
221
- return;
222
- }
223
- const events = getEvents();
224
- if (events.length === 0) {
225
- return;
226
- }
227
- // Track events length here, incase
228
- const numEvents = events.length;
229
- // Get details and send it with the track request
230
- const details = getAllDetails();
231
- const metricsPayload = {
232
- version: 1,
233
- data: {
234
- events,
235
- details,
236
- },
237
- };
238
- const response = await post('/v1/sdk/metrics', metricsPayload);
239
- if (response instanceof Error) {
240
- return;
241
- }
242
- // Clear events if successfully posted
243
- removeSentEvents(numEvents);
244
- };
245
- const flush = errorBoundary(flushFn);
246
- // Flush events every 5 seconds
247
- const flushPoll = async () => {
248
- await flush();
249
- setTimeout(flushPoll, POLLING_FREQUENCY);
250
- };
251
- // This will get initialised when module is imported.
252
- if (!isTestEnvironment()) {
253
- errorBoundary(flushPoll)();
254
- }
255
-
256
- const setEnvironmentFn = (env) => {
257
- storeDetail(Detail.ENVIRONMENT, env);
258
- };
259
- const setEnvironment = errorBoundary(setEnvironmentFn);
260
- const setPublishableApiKeyFn = (publishableApiKey) => {
261
- storeDetail(Detail.PUBLISHABLE_API_KEY, publishableApiKey);
262
- };
263
- const setPublishableApiKey = errorBoundary(setPublishableApiKeyFn);
264
-
265
3
  var Environment;
266
4
  (function (Environment) {
267
5
  Environment["PRODUCTION"] = "production";
@@ -274,8 +12,6 @@ class ImmutableConfiguration {
274
12
  publishableKey;
275
13
  constructor(options) {
276
14
  this.environment = options.environment;
277
- setEnvironment(options.environment);
278
- track('config', 'load_imtbl_config');
279
15
  }
280
16
  }
281
17
  const API_KEY_PREFIX = 'sk_imapik-';
@@ -291,7 +27,6 @@ const addPublishableKeyToAxiosHeader = (publishableKey) => {
291
27
  throw new Error('Invalid Publishable key. Create your Publishable key in Immutable developer hub.'
292
28
  + ' https://hub.immutable.com');
293
29
  }
294
- setPublishableApiKey(publishableKey);
295
30
  axios.defaults.headers.common['x-immutable-publishable-key'] = publishableKey;
296
31
  };
297
32
  const addRateLimitingKeyToAxiosHeader = (rateLimitingKey) => {