@jitsu/js 1.1.0-canary.344.20230430234929 → 1.1.0-canary.388.20230519133920

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/jitsu.es.js CHANGED
@@ -65,7 +65,50 @@ function analyticsLib() {
65
65
  return ke(_objectSpread2(_objectSpread2({}, defaultSettings), opts));
66
66
  }
67
67
 
68
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
68
+ function findScript(src) {
69
+ const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
70
+ return scripts.find(s => s.src === src);
71
+ }
72
+ function loadScript(src, attributes) {
73
+ const found = findScript(src);
74
+ if (found !== undefined) {
75
+ const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
76
+ if (status === "loaded") {
77
+ return Promise.resolve(found);
78
+ }
79
+ if (status === "loading") {
80
+ return new Promise((resolve, reject) => {
81
+ found.addEventListener("load", () => resolve(found));
82
+ found.addEventListener("error", err => reject(err));
83
+ });
84
+ }
85
+ }
86
+ return new Promise((resolve, reject) => {
87
+ var _a;
88
+ const script = window.document.createElement("script");
89
+ script.type = "text/javascript";
90
+ script.src = src;
91
+ script.async = true;
92
+ script.setAttribute("status", "loading");
93
+ for (const [k, v] of Object.entries(attributes !== null && attributes !== void 0 ? attributes : {})) {
94
+ script.setAttribute(k, v);
95
+ }
96
+ script.onload = () => {
97
+ script.onerror = script.onload = null;
98
+ script.setAttribute("status", "loaded");
99
+ resolve(script);
100
+ };
101
+ script.onerror = () => {
102
+ script.onerror = script.onload = null;
103
+ script.setAttribute("status", "error");
104
+ reject(new Error(`Failed to load ${src}`));
105
+ };
106
+ const tag = window.document.getElementsByTagName("script")[0];
107
+ (_a = tag.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(script, tag);
108
+ });
109
+ }
110
+
111
+ var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
69
112
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
70
113
  return new (P || (P = Promise))(function (resolve, reject) {
71
114
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -74,18 +117,10 @@ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _argu
74
117
  step((generator = generator.apply(thisArg, _arguments || [])).next());
75
118
  });
76
119
  };
77
- function satisfyFilter(filter, subject) {
78
- return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
79
- }
80
- function applyFilters(event, creds) {
81
- const { hosts = ["*"], events = ["*"] } = creds;
82
- return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
83
- !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
84
- }
85
120
  const tagPlugin = {
86
121
  id: "tag",
87
122
  handle(config, payload) {
88
- return __awaiter$1(this, void 0, void 0, function* () {
123
+ return __awaiter$3(this, void 0, void 0, function* () {
89
124
  if (!applyFilters(payload, config)) {
90
125
  return;
91
126
  }
@@ -153,53 +188,193 @@ function execJs(code, event) {
153
188
  function replaceMacro(code, event) {
154
189
  return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
155
190
  }
156
- const internalDestinationPlugins = {
157
- [tagPlugin.id]: tagPlugin,
158
- };
159
191
 
160
- function findScript(src) {
161
- const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
162
- return scripts.find(s => s.src === src);
192
+ var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
193
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
194
+ return new (P || (P = Promise))(function (resolve, reject) {
195
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
196
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
197
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
198
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
199
+ });
200
+ };
201
+ const logrocketPlugin = {
202
+ id: "logrocket",
203
+ handle(config, payload) {
204
+ return __awaiter$2(this, void 0, void 0, function* () {
205
+ if (!applyFilters(payload, config)) {
206
+ return;
207
+ }
208
+ initLogrocketIfNeeded(config.appId);
209
+ const action = logRocket => {
210
+ if (payload.type === "identify" && payload.userId) {
211
+ logRocket.identify(payload.userId, payload.traits || {});
212
+ }
213
+ };
214
+ getLogRocketQueue().push(action);
215
+ if (getLogRocketState() === "loaded") {
216
+ flushLogRocketQueue(window["LogRocket"]);
217
+ }
218
+ });
219
+ },
220
+ };
221
+ function getLogRocketState() {
222
+ return window["__jitsuLrState"] || "fresh";
163
223
  }
164
- function loadScript(src, attributes) {
165
- const found = findScript(src);
166
- if (found !== undefined) {
167
- const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
168
- if (status === "loaded") {
169
- return Promise.resolve(found);
224
+ function setLogRocketState(s) {
225
+ window["__jitsuLrState"] = s;
226
+ }
227
+ function getLogRocketQueue() {
228
+ return window["__jitsuLrQueue"] || (window["__jitsuLrQueue"] = []);
229
+ }
230
+ function flushLogRocketQueue(lr) {
231
+ const queue = getLogRocketQueue();
232
+ while (queue.length > 0) {
233
+ const method = queue.shift();
234
+ try {
235
+ const res = method(lr);
236
+ if (res) {
237
+ res.catch(e => console.warn(`Async LogRocket method failed: ${e.message}`, e));
238
+ }
170
239
  }
171
- if (status === "loading") {
172
- return new Promise((resolve, reject) => {
173
- found.addEventListener("load", () => resolve(found));
174
- found.addEventListener("error", err => reject(err));
175
- });
240
+ catch (e) {
241
+ console.warn(`LogRocket method failed: ${e.message}`, e);
176
242
  }
177
243
  }
178
- return new Promise((resolve, reject) => {
179
- var _a;
180
- const script = window.document.createElement("script");
181
- script.type = "text/javascript";
182
- script.src = src;
183
- script.async = true;
184
- script.setAttribute("status", "loading");
185
- for (const [k, v] of Object.entries(attributes !== null && attributes !== void 0 ? attributes : {})) {
186
- script.setAttribute(k, v);
244
+ }
245
+ function initLogrocketIfNeeded(appId) {
246
+ return __awaiter$2(this, void 0, void 0, function* () {
247
+ if (getLogRocketState() !== "fresh") {
248
+ return;
187
249
  }
188
- script.onload = () => {
189
- script.onerror = script.onload = null;
190
- script.setAttribute("status", "loaded");
191
- resolve(script);
192
- };
193
- script.onerror = () => {
194
- script.onerror = script.onload = null;
195
- script.setAttribute("status", "error");
196
- reject(new Error(`Failed to load ${src}`));
250
+ setLogRocketState("loading");
251
+ loadScript(`https://cdn.lr-ingest.io/LogRocket.min.js`, { crossOrigin: "anonymous" })
252
+ .then(() => {
253
+ if (window["LogRocket"]) {
254
+ try {
255
+ window["LogRocket"].init(appId);
256
+ }
257
+ catch (e) {
258
+ console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
259
+ setLogRocketState("failed");
260
+ }
261
+ setLogRocketState("loaded");
262
+ flushLogRocketQueue(window["LogRocket"]);
263
+ }
264
+ })
265
+ .catch(e => {
266
+ console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
267
+ setLogRocketState("failed");
268
+ });
269
+ });
270
+ }
271
+
272
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
273
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
274
+ return new (P || (P = Promise))(function (resolve, reject) {
275
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
276
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
277
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
278
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
279
+ });
280
+ };
281
+ const defaultScriptSrc = "https://www.googletagmanager.com/gtag/js";
282
+ const gtmPlugin = {
283
+ id: "gtm",
284
+ handle(config, payload) {
285
+ return __awaiter$1(this, void 0, void 0, function* () {
286
+ if (!applyFilters(payload, config)) {
287
+ return;
288
+ }
289
+ yield initGtmIfNeeded(config);
290
+ const dataLayer = window[config.dataLayerName || "dataLayer"];
291
+ switch (payload.type) {
292
+ case "page":
293
+ const { properties: pageProperties } = payload;
294
+ const pageEvent = Object.assign({ event: "page_view" }, pageProperties);
295
+ if (config.debug) {
296
+ console.log("gtag push", pageEvent);
297
+ }
298
+ dataLayer.push(pageEvent);
299
+ break;
300
+ case "track":
301
+ const { properties: trackProperties } = payload;
302
+ const trackEvent = Object.assign({ event: payload.event }, trackProperties);
303
+ if (config.debug) {
304
+ console.log("gtag push", trackEvent);
305
+ }
306
+ dataLayer.push(trackEvent);
307
+ break;
308
+ case "identify":
309
+ const { anonymousId, userId, traits } = payload;
310
+ const user = traits;
311
+ if (userId) {
312
+ user.userId = userId;
313
+ }
314
+ if (anonymousId) {
315
+ user.anonymousId = anonymousId;
316
+ }
317
+ const identifyEvent = { event: "identify", user: user };
318
+ if (config.debug) {
319
+ console.log("gtag push", identifyEvent);
320
+ }
321
+ dataLayer.push(identifyEvent);
322
+ break;
323
+ }
324
+ });
325
+ },
326
+ };
327
+ function getGtmState() {
328
+ return window["__jitsuGtmState"] || "fresh";
329
+ }
330
+ function setGtmState(s) {
331
+ window["__jitsuGtmState"] = s;
332
+ }
333
+ function initGtmIfNeeded(config) {
334
+ return __awaiter$1(this, void 0, void 0, function* () {
335
+ if (getGtmState() !== "fresh") {
336
+ return;
337
+ }
338
+ setGtmState("loading");
339
+ const dlName = config.dataLayerName || "dataLayer";
340
+ const dlParam = dlName !== "dataLayer" ? "&l=" + dlName : "";
341
+ const previewParams = config.preview
342
+ ? `&gtm_preview=${config.preview}&gtm_auth=${config.auth}&gtm_cookies_win=x`
343
+ : "";
344
+ const scriptSrc = `${config.customScriptSrc || defaultScriptSrc}?id=${config.containerId}${dlParam}${previewParams}`;
345
+ window[dlName] = window[dlName] || [];
346
+ const gtag = function () {
347
+ window[dlName].push(arguments);
197
348
  };
198
- const tag = window.document.getElementsByTagName("script")[0];
199
- (_a = tag.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(script, tag);
349
+ // @ts-ignore
350
+ gtag("js", new Date());
351
+ // @ts-ignore
352
+ gtag("config", config.containerId);
353
+ loadScript(scriptSrc)
354
+ .then(() => {
355
+ setGtmState("loaded");
356
+ })
357
+ .catch(e => {
358
+ console.warn(`GTM (containerId=${config.containerId}) init failed: ${e.message}`, e);
359
+ setGtmState("failed");
360
+ });
200
361
  });
201
362
  }
202
363
 
364
+ function satisfyFilter(filter, subject) {
365
+ return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
366
+ }
367
+ function applyFilters(event, creds) {
368
+ const { hosts = ["*"], events = ["*"] } = creds;
369
+ return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
370
+ !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
371
+ }
372
+ const internalDestinationPlugins = {
373
+ [tagPlugin.id]: tagPlugin,
374
+ [gtmPlugin.id]: gtmPlugin,
375
+ [logrocketPlugin.id]: logrocketPlugin,
376
+ };
377
+
203
378
  /* global analytics */
204
379
  var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
205
380
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -218,6 +393,8 @@ const config = {
218
393
  debug: false,
219
394
  fetch: null,
220
395
  echoEvents: false,
396
+ cookieDomain: undefined,
397
+ runtime: undefined,
221
398
  };
222
399
  const parseQuery = (qs) => {
223
400
  if (!qs) {
@@ -441,7 +618,7 @@ function adjustPayload(payload, config, storage) {
441
618
  userAgent: runtime.userAgent(),
442
619
  locale: runtime.language(),
443
620
  screen: runtime.screen(),
444
- traits: payload.type != "identify" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
621
+ traits: payload.type != "identify" && payload.type != "group" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
445
622
  page: {
446
623
  path: properties.path || (parsedUrl && parsedUrl.pathname),
447
624
  referrer: referrer,
@@ -450,7 +627,7 @@ function adjustPayload(payload, config, storage) {
450
627
  search: properties.search || (parsedUrl && parsedUrl.search),
451
628
  title: properties.title || runtime.pageTitle(),
452
629
  url: properties.url || url,
453
- enconding: properties.enconding || runtime.documentEncoding(),
630
+ encoding: properties.encoding || runtime.documentEncoding(),
454
631
  },
455
632
  campaign: parseUtms(query),
456
633
  };
@@ -558,7 +735,7 @@ function send(method, payload, jitsuConfig, instance, store) {
558
735
  }
559
736
  if (response.destinations) {
560
737
  if (jitsuConfig.debug) {
561
- console.log(`[JITSU] Processing device destianations: `, JSON.stringify(response.destinations, null, 2));
738
+ console.log(`[JITSU] Processing device destinations: `, JSON.stringify(response.destinations, null, 2));
562
739
  }
563
740
  return processDestinations(response.destinations, method, adjustedPayload, !!jitsuConfig.debug, instance);
564
741
  }
@@ -587,9 +764,10 @@ const jitsuAnalyticsPlugin = (pluginConfig = {}) => {
587
764
  persistentStorage.removeItem(key);
588
765
  },
589
766
  });
767
+ const instanceConfig = Object.assign(Object.assign({}, config), pluginConfig);
590
768
  return {
591
769
  name: "jitsu",
592
- config: Object.assign(Object.assign({}, config), pluginConfig),
770
+ config: instanceConfig,
593
771
  initialize: args => {
594
772
  const { config } = args;
595
773
  if (config.debug) {
@@ -617,6 +795,16 @@ const jitsuAnalyticsPlugin = (pluginConfig = {}) => {
617
795
  //clear storage cache
618
796
  Object.keys(storageCache).forEach(key => delete storageCache[key]);
619
797
  },
798
+ methods: {
799
+ //analytics doesn't support group as a base method, so we need to add it manually
800
+ group(groupId, traits, options, callback) {
801
+ const analyticsInstance = this.instance;
802
+ const user = analyticsInstance.user();
803
+ const userId = (options === null || options === void 0 ? void 0 : options.userId) || (user === null || user === void 0 ? void 0 : user.userId);
804
+ const anonymousId = (options === null || options === void 0 ? void 0 : options.anonymousId) || (user === null || user === void 0 ? void 0 : user.anonymousId);
805
+ return send("group", Object.assign(Object.assign({ type: "group", groupId, traits }, (anonymousId ? { anonymousId } : {})), (userId ? { userId } : {})), instanceConfig, analyticsInstance, cachingStorageWrapper(analyticsInstance.storage));
806
+ },
807
+ },
620
808
  };
621
809
  };
622
810
  function getSeed() {
@@ -669,6 +857,7 @@ const emptyAnalytics = {
669
857
  page: () => Promise.resolve(),
670
858
  user: () => ({}),
671
859
  identify: () => Promise.resolve({}),
860
+ group: () => Promise.resolve({}),
672
861
  reset: () => Promise.resolve({}),
673
862
  };
674
863
  function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
@@ -687,7 +876,14 @@ function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
687
876
  return originalPage(...args);
688
877
  }
689
878
  };
690
- return analytics;
879
+ return Object.assign(Object.assign({}, analytics), { group(groupId, traits, options, callback) {
880
+ for (const plugin of Object.values(analytics.plugins)) {
881
+ if (plugin["group"]) {
882
+ plugin["group"](groupId, traits, options, callback);
883
+ }
884
+ }
885
+ return Promise.resolve({});
886
+ } });
691
887
  }
692
888
  function jitsuAnalytics(opts) {
693
889
  const inBrowser = isInBrowser();