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

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.cjs.js CHANGED
@@ -67,7 +67,50 @@ function analyticsLib() {
67
67
  return ke(_objectSpread2(_objectSpread2({}, defaultSettings), opts));
68
68
  }
69
69
 
70
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
70
+ function findScript(src) {
71
+ const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
72
+ return scripts.find(s => s.src === src);
73
+ }
74
+ function loadScript(src, attributes) {
75
+ const found = findScript(src);
76
+ if (found !== undefined) {
77
+ const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
78
+ if (status === "loaded") {
79
+ return Promise.resolve(found);
80
+ }
81
+ if (status === "loading") {
82
+ return new Promise((resolve, reject) => {
83
+ found.addEventListener("load", () => resolve(found));
84
+ found.addEventListener("error", err => reject(err));
85
+ });
86
+ }
87
+ }
88
+ return new Promise((resolve, reject) => {
89
+ var _a;
90
+ const script = window.document.createElement("script");
91
+ script.type = "text/javascript";
92
+ script.src = src;
93
+ script.async = true;
94
+ script.setAttribute("status", "loading");
95
+ for (const [k, v] of Object.entries(attributes !== null && attributes !== void 0 ? attributes : {})) {
96
+ script.setAttribute(k, v);
97
+ }
98
+ script.onload = () => {
99
+ script.onerror = script.onload = null;
100
+ script.setAttribute("status", "loaded");
101
+ resolve(script);
102
+ };
103
+ script.onerror = () => {
104
+ script.onerror = script.onload = null;
105
+ script.setAttribute("status", "error");
106
+ reject(new Error(`Failed to load ${src}`));
107
+ };
108
+ const tag = window.document.getElementsByTagName("script")[0];
109
+ (_a = tag.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(script, tag);
110
+ });
111
+ }
112
+
113
+ var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
71
114
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
72
115
  return new (P || (P = Promise))(function (resolve, reject) {
73
116
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -76,18 +119,10 @@ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _argu
76
119
  step((generator = generator.apply(thisArg, _arguments || [])).next());
77
120
  });
78
121
  };
79
- function satisfyFilter(filter, subject) {
80
- return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
81
- }
82
- function applyFilters(event, creds) {
83
- const { hosts = ["*"], events = ["*"] } = creds;
84
- return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
85
- !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
86
- }
87
122
  const tagPlugin = {
88
123
  id: "tag",
89
124
  handle(config, payload) {
90
- return __awaiter$1(this, void 0, void 0, function* () {
125
+ return __awaiter$3(this, void 0, void 0, function* () {
91
126
  if (!applyFilters(payload, config)) {
92
127
  return;
93
128
  }
@@ -155,53 +190,206 @@ function execJs(code, event) {
155
190
  function replaceMacro(code, event) {
156
191
  return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
157
192
  }
158
- const internalDestinationPlugins = {
159
- [tagPlugin.id]: tagPlugin,
160
- };
161
193
 
162
- function findScript(src) {
163
- const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
164
- return scripts.find(s => s.src === src);
194
+ var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
195
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
196
+ return new (P || (P = Promise))(function (resolve, reject) {
197
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
198
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
199
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
200
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
201
+ });
202
+ };
203
+ const logrocketPlugin = {
204
+ id: "logrocket",
205
+ handle(config, payload) {
206
+ return __awaiter$2(this, void 0, void 0, function* () {
207
+ if (!applyFilters(payload, config)) {
208
+ return;
209
+ }
210
+ initLogrocketIfNeeded(config.appId);
211
+ const action = logRocket => {
212
+ if (payload.type === "identify" && payload.userId) {
213
+ logRocket.identify(payload.userId, payload.traits || {});
214
+ }
215
+ };
216
+ getLogRocketQueue().push(action);
217
+ if (getLogRocketState() === "loaded") {
218
+ flushLogRocketQueue(window["LogRocket"]);
219
+ }
220
+ });
221
+ },
222
+ };
223
+ function getLogRocketState() {
224
+ return window["__jitsuLrState"] || "fresh";
165
225
  }
166
- function loadScript(src, attributes) {
167
- const found = findScript(src);
168
- if (found !== undefined) {
169
- const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
170
- if (status === "loaded") {
171
- return Promise.resolve(found);
226
+ function setLogRocketState(s) {
227
+ window["__jitsuLrState"] = s;
228
+ }
229
+ function getLogRocketQueue() {
230
+ return window["__jitsuLrQueue"] || (window["__jitsuLrQueue"] = []);
231
+ }
232
+ function flushLogRocketQueue(lr) {
233
+ const queue = getLogRocketQueue();
234
+ while (queue.length > 0) {
235
+ const method = queue.shift();
236
+ try {
237
+ const res = method(lr);
238
+ if (res) {
239
+ res.catch(e => console.warn(`Async LogRocket method failed: ${e.message}`, e));
240
+ }
172
241
  }
173
- if (status === "loading") {
174
- return new Promise((resolve, reject) => {
175
- found.addEventListener("load", () => resolve(found));
176
- found.addEventListener("error", err => reject(err));
177
- });
242
+ catch (e) {
243
+ console.warn(`LogRocket method failed: ${e.message}`, e);
178
244
  }
179
245
  }
180
- return new Promise((resolve, reject) => {
181
- var _a;
182
- const script = window.document.createElement("script");
183
- script.type = "text/javascript";
184
- script.src = src;
185
- script.async = true;
186
- script.setAttribute("status", "loading");
187
- for (const [k, v] of Object.entries(attributes !== null && attributes !== void 0 ? attributes : {})) {
188
- script.setAttribute(k, v);
246
+ }
247
+ function initLogrocketIfNeeded(appId) {
248
+ return __awaiter$2(this, void 0, void 0, function* () {
249
+ if (getLogRocketState() !== "fresh") {
250
+ return;
189
251
  }
190
- script.onload = () => {
191
- script.onerror = script.onload = null;
192
- script.setAttribute("status", "loaded");
193
- resolve(script);
194
- };
195
- script.onerror = () => {
196
- script.onerror = script.onload = null;
197
- script.setAttribute("status", "error");
198
- reject(new Error(`Failed to load ${src}`));
252
+ setLogRocketState("loading");
253
+ loadScript(`https://cdn.lr-ingest.io/LogRocket.min.js`, { crossOrigin: "anonymous" })
254
+ .then(() => {
255
+ if (window["LogRocket"]) {
256
+ try {
257
+ window["LogRocket"].init(appId);
258
+ }
259
+ catch (e) {
260
+ console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
261
+ setLogRocketState("failed");
262
+ }
263
+ setLogRocketState("loaded");
264
+ flushLogRocketQueue(window["LogRocket"]);
265
+ }
266
+ })
267
+ .catch(e => {
268
+ console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
269
+ setLogRocketState("failed");
270
+ });
271
+ });
272
+ }
273
+
274
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
275
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
276
+ return new (P || (P = Promise))(function (resolve, reject) {
277
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
278
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
279
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
280
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
281
+ });
282
+ };
283
+ const defaultScriptSrc = "https://www.googletagmanager.com/gtag/js";
284
+ const gtmPlugin = {
285
+ id: "gtm",
286
+ handle(config, payload) {
287
+ var _a, _b;
288
+ return __awaiter$1(this, void 0, void 0, function* () {
289
+ if (!applyFilters(payload, config)) {
290
+ return;
291
+ }
292
+ yield initGtmIfNeeded(config);
293
+ const dataLayer = window[config.dataLayerName || "dataLayer"];
294
+ switch (payload.type) {
295
+ case "page":
296
+ const { properties: pageProperties, context } = payload;
297
+ const pageEvent = {
298
+ event: "page_view",
299
+ url: pageProperties.url,
300
+ title: pageProperties.title,
301
+ referer: (_b = (_a = context === null || context === void 0 ? void 0 : context.page) === null || _a === void 0 ? void 0 : _a.referrer) !== null && _b !== void 0 ? _b : "",
302
+ };
303
+ if (config.debug) {
304
+ console.log("gtag push", pageEvent);
305
+ }
306
+ dataLayer.push(pageEvent);
307
+ break;
308
+ case "track":
309
+ const { properties: trackProperties } = payload;
310
+ const trackEvent = Object.assign({ event: payload.event }, trackProperties);
311
+ if (payload.userId) {
312
+ trackEvent.userId = payload.userId;
313
+ }
314
+ if (payload.anonymousId) {
315
+ trackEvent.anonymousId = payload.anonymousId;
316
+ }
317
+ if (config.debug) {
318
+ console.log("gtag push", trackEvent);
319
+ }
320
+ dataLayer.push(trackEvent);
321
+ break;
322
+ case "identify":
323
+ const { traits } = payload;
324
+ const identifyEvent = Object.assign({ event: "identify" }, traits);
325
+ if (payload.userId) {
326
+ identifyEvent.userId = payload.userId;
327
+ }
328
+ if (payload.anonymousId) {
329
+ identifyEvent.anonymousId = payload.anonymousId;
330
+ }
331
+ if (config.debug) {
332
+ console.log("gtag push", identifyEvent);
333
+ }
334
+ dataLayer.push(identifyEvent);
335
+ break;
336
+ }
337
+ });
338
+ },
339
+ };
340
+ function getGtmState() {
341
+ return window["__jitsuGtmState"] || "fresh";
342
+ }
343
+ function setGtmState(s) {
344
+ window["__jitsuGtmState"] = s;
345
+ }
346
+ function initGtmIfNeeded(config) {
347
+ return __awaiter$1(this, void 0, void 0, function* () {
348
+ if (getGtmState() !== "fresh") {
349
+ return;
350
+ }
351
+ setGtmState("loading");
352
+ const dlName = config.dataLayerName || "dataLayer";
353
+ const dlParam = dlName !== "dataLayer" ? "&l=" + dlName : "";
354
+ const previewParams = config.preview
355
+ ? `&gtm_preview=${config.preview}&gtm_auth=${config.auth}&gtm_cookies_win=x`
356
+ : "";
357
+ const scriptSrc = `${config.customScriptSrc || defaultScriptSrc}?id=${config.containerId}${dlParam}${previewParams}`;
358
+ window[dlName] = window[dlName] || [];
359
+ const gtag = function () {
360
+ window[dlName].push(arguments);
199
361
  };
200
- const tag = window.document.getElementsByTagName("script")[0];
201
- (_a = tag.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(script, tag);
362
+ // @ts-ignore
363
+ gtag("js", new Date());
364
+ // @ts-ignore
365
+ gtag("config", config.containerId);
366
+ loadScript(scriptSrc)
367
+ .then(() => {
368
+ setGtmState("loaded");
369
+ })
370
+ .catch(e => {
371
+ console.warn(`GTM (containerId=${config.containerId}) init failed: ${e.message}`, e);
372
+ setGtmState("failed");
373
+ });
202
374
  });
203
375
  }
204
376
 
377
+ function satisfyFilter(filter, subject) {
378
+ return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
379
+ }
380
+ function applyFilters(event, creds) {
381
+ const { hosts = "*", events = "*" } = creds;
382
+ const eventsArray = events.split("\n");
383
+ return (!!hosts.split("\n").find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
384
+ (!!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.type)) ||
385
+ !!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.event))));
386
+ }
387
+ const internalDestinationPlugins = {
388
+ [tagPlugin.id]: tagPlugin,
389
+ [gtmPlugin.id]: gtmPlugin,
390
+ [logrocketPlugin.id]: logrocketPlugin,
391
+ };
392
+
205
393
  /* global analytics */
206
394
  var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
207
395
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -220,6 +408,8 @@ const config = {
220
408
  debug: false,
221
409
  fetch: null,
222
410
  echoEvents: false,
411
+ cookieDomain: undefined,
412
+ runtime: undefined,
223
413
  };
224
414
  const parseQuery = (qs) => {
225
415
  if (!qs) {
@@ -443,7 +633,7 @@ function adjustPayload(payload, config, storage) {
443
633
  userAgent: runtime.userAgent(),
444
634
  locale: runtime.language(),
445
635
  screen: runtime.screen(),
446
- traits: payload.type != "identify" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
636
+ traits: payload.type != "identify" && payload.type != "group" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
447
637
  page: {
448
638
  path: properties.path || (parsedUrl && parsedUrl.pathname),
449
639
  referrer: referrer,
@@ -452,7 +642,7 @@ function adjustPayload(payload, config, storage) {
452
642
  search: properties.search || (parsedUrl && parsedUrl.search),
453
643
  title: properties.title || runtime.pageTitle(),
454
644
  url: properties.url || url,
455
- enconding: properties.enconding || runtime.documentEncoding(),
645
+ encoding: properties.encoding || runtime.documentEncoding(),
456
646
  },
457
647
  campaign: parseUtms(query),
458
648
  };
@@ -465,12 +655,12 @@ function processDestinations(destinations, method, event, debug, analyticsInstan
465
655
  return __awaiter(this, void 0, void 0, function* () {
466
656
  const promises = [];
467
657
  for (const destination of destinations) {
658
+ const credentials = Object.assign(Object.assign({}, destination.credentials), destination.options);
468
659
  if (destination.deviceOptions.type === "internal-plugin") {
469
660
  const plugin = internalDestinationPlugins[destination.deviceOptions.name];
470
661
  if (plugin) {
471
662
  try {
472
663
  //to support old versions, where credentials were stored in root
473
- const credentials = destination.credentials || destination;
474
664
  promises.push(plugin.handle(credentials, event));
475
665
  }
476
666
  catch (e) {
@@ -490,7 +680,7 @@ function processDestinations(destinations, method, event, debug, analyticsInstan
490
680
  else {
491
681
  let pluginInstance;
492
682
  try {
493
- pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(destination.credentials);
683
+ pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(credentials);
494
684
  }
495
685
  catch (e) {
496
686
  console.warn(`[JITSU] Error creating plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
@@ -560,7 +750,7 @@ function send(method, payload, jitsuConfig, instance, store) {
560
750
  }
561
751
  if (response.destinations) {
562
752
  if (jitsuConfig.debug) {
563
- console.log(`[JITSU] Processing device destianations: `, JSON.stringify(response.destinations, null, 2));
753
+ console.log(`[JITSU] Processing device destinations: `, JSON.stringify(response.destinations, null, 2));
564
754
  }
565
755
  return processDestinations(response.destinations, method, adjustedPayload, !!jitsuConfig.debug, instance);
566
756
  }
@@ -589,9 +779,10 @@ const jitsuAnalyticsPlugin = (pluginConfig = {}) => {
589
779
  persistentStorage.removeItem(key);
590
780
  },
591
781
  });
782
+ const instanceConfig = Object.assign(Object.assign({}, config), pluginConfig);
592
783
  return {
593
784
  name: "jitsu",
594
- config: Object.assign(Object.assign({}, config), pluginConfig),
785
+ config: instanceConfig,
595
786
  initialize: args => {
596
787
  const { config } = args;
597
788
  if (config.debug) {
@@ -619,6 +810,16 @@ const jitsuAnalyticsPlugin = (pluginConfig = {}) => {
619
810
  //clear storage cache
620
811
  Object.keys(storageCache).forEach(key => delete storageCache[key]);
621
812
  },
813
+ methods: {
814
+ //analytics doesn't support group as a base method, so we need to add it manually
815
+ group(groupId, traits, options, callback) {
816
+ const analyticsInstance = this.instance;
817
+ const user = analyticsInstance.user();
818
+ const userId = (options === null || options === void 0 ? void 0 : options.userId) || (user === null || user === void 0 ? void 0 : user.userId);
819
+ const anonymousId = (options === null || options === void 0 ? void 0 : options.anonymousId) || (user === null || user === void 0 ? void 0 : user.anonymousId);
820
+ return send("group", Object.assign(Object.assign({ type: "group", groupId, traits }, (anonymousId ? { anonymousId } : {})), (userId ? { userId } : {})), instanceConfig, analyticsInstance, cachingStorageWrapper(analyticsInstance.storage));
821
+ },
822
+ },
622
823
  };
623
824
  };
624
825
  function getSeed() {
@@ -671,6 +872,7 @@ const emptyAnalytics = {
671
872
  page: () => Promise.resolve(),
672
873
  user: () => ({}),
673
874
  identify: () => Promise.resolve({}),
875
+ group: () => Promise.resolve({}),
674
876
  reset: () => Promise.resolve({}),
675
877
  };
676
878
  function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
@@ -689,7 +891,14 @@ function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
689
891
  return originalPage(...args);
690
892
  }
691
893
  };
692
- return analytics;
894
+ return Object.assign(Object.assign({}, analytics), { group(groupId, traits, options, callback) {
895
+ for (const plugin of Object.values(analytics.plugins)) {
896
+ if (plugin["group"]) {
897
+ plugin["group"](groupId, traits, options, callback);
898
+ }
899
+ }
900
+ return Promise.resolve({});
901
+ } });
693
902
  }
694
903
  function jitsuAnalytics(opts) {
695
904
  const inBrowser = isInBrowser();