@jitsu/js 1.1.0-canary.227.20230222142636 → 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.
@@ -1,4 +1,4 @@
1
- @jitsu/js:build: cache hit, replaying output ba40be9de835fbde
1
+ @jitsu/js:build: cache hit, replaying output 9d604bcd7bdc50ac
2
2
  @jitsu/js:build: 
3
3
  @jitsu/js:build: > @jitsu/js@0.0.0 build /Users/ildarnurislamov/Projects/onetag/libs/jitsu-js
4
4
  @jitsu/js:build: > tsc -p . && rollup -c && cp compiled/src/*.d.ts dist
@@ -6,7 +6,7 @@
6
6
  @jitsu/js:build: 
7
7
  @jitsu/js:build: ./compiled/src/browser.js → dist/web/p.js.txt...
8
8
  @jitsu/js:build: (!) "this" has been rewritten to "undefined"
9
- @jitsu/js:build: https://rollupjs.org/guide/en/#error-this-is-undefined
9
+ @jitsu/js:build: https://rollupjs.org/troubleshooting/#error-this-is-undefined
10
10
  @jitsu/js:build: compiled/src/analytics-plugin.js
11
11
  @jitsu/js:build: 1: /* global analytics */
12
12
  @jitsu/js:build: 2: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
@@ -14,7 +14,19 @@
14
14
  @jitsu/js:build: 3: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
15
  @jitsu/js:build: 4: return new (P || (P = Promise))(function (resolve, reject) {
16
16
  @jitsu/js:build: ...and 1 other occurrence
17
- @jitsu/js:build: compiled/src/destination-plugins.js
17
+ @jitsu/js:build: compiled/src/destination-plugins/logrocket.js
18
+ @jitsu/js:build: 1: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
+ @jitsu/js:build:  ^
20
+ @jitsu/js:build: 2: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
21
+ @jitsu/js:build: 3: return new (P || (P = Promise))(function (resolve, reject) {
22
+ @jitsu/js:build: ...and 1 other occurrence
23
+ @jitsu/js:build: compiled/src/destination-plugins/tag.js
24
+ @jitsu/js:build: 1: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
25
+ @jitsu/js:build:  ^
26
+ @jitsu/js:build: 2: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ @jitsu/js:build: 3: return new (P || (P = Promise))(function (resolve, reject) {
28
+ @jitsu/js:build: ...and 1 other occurrence
29
+ @jitsu/js:build: compiled/src/destination-plugins/gtm.js
18
30
  @jitsu/js:build: 1: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
31
  @jitsu/js:build:  ^
20
32
  @jitsu/js:build: 2: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -22,21 +34,24 @@
22
34
  @jitsu/js:build: ...and 1 other occurrence
23
35
  @jitsu/js:build: (!) Circular dependencies
24
36
  @jitsu/js:build: compiled/src/index.js -> compiled/src/analytics-plugin.js -> compiled/src/index.js
25
- @jitsu/js:build: compiled/src/analytics-plugin.js -> compiled/src/destination-plugins.js -> compiled/src/analytics-plugin.js
37
+ @jitsu/js:build: compiled/src/destination-plugins/index.js -> compiled/src/destination-plugins/tag.js -> compiled/src/destination-plugins/index.js
38
+ @jitsu/js:build: compiled/src/analytics-plugin.js -> compiled/src/destination-plugins/index.js -> compiled/src/destination-plugins/tag.js -> compiled/src/analytics-plugin.js
39
+ @jitsu/js:build: compiled/src/destination-plugins/index.js -> compiled/src/destination-plugins/logrocket.js -> compiled/src/destination-plugins/index.js
40
+ @jitsu/js:build: compiled/src/destination-plugins/index.js -> compiled/src/destination-plugins/gtm.js -> compiled/src/destination-plugins/index.js
26
41
  @jitsu/js:build: (!) Use of eval is strongly discouraged
27
- @jitsu/js:build: https://rollupjs.org/guide/en/#avoiding-eval
28
- @jitsu/js:build: compiled/src/destination-plugins.js
29
- @jitsu/js:build: 75: })()`;
30
- @jitsu/js:build: 76: try {
31
- @jitsu/js:build: 77: eval(iif);
42
+ @jitsu/js:build: https://rollupjs.org/troubleshooting/#avoiding-eval
43
+ @jitsu/js:build: compiled/src/destination-plugins/tag.js
44
+ @jitsu/js:build: 68: })()`;
45
+ @jitsu/js:build: 69: try {
46
+ @jitsu/js:build: 70: eval(iif);
32
47
  @jitsu/js:build:  ^
33
- @jitsu/js:build: 78: }
34
- @jitsu/js:build: 79: catch (e) {
35
- @jitsu/js:build: created dist/web/p.js.txt in 388ms
48
+ @jitsu/js:build: 71: }
49
+ @jitsu/js:build: 72: catch (e) {
50
+ @jitsu/js:build: created dist/web/p.js.txt in 216ms
36
51
  @jitsu/js:build: 
37
52
  @jitsu/js:build: ./compiled/src/index.js, ./compiled/src/jitsu.js, ./compiled/src/analytics-plugin.js → dist/jitsu.es.js, dist/jitsu.cjs.js...
38
53
  @jitsu/js:build: (!) "this" has been rewritten to "undefined"
39
- @jitsu/js:build: https://rollupjs.org/guide/en/#error-this-is-undefined
54
+ @jitsu/js:build: https://rollupjs.org/troubleshooting/#error-this-is-undefined
40
55
  @jitsu/js:build: compiled/src/analytics-plugin.js
41
56
  @jitsu/js:build: 1: /* global analytics */
42
57
  @jitsu/js:build: 2: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
@@ -44,7 +59,19 @@
44
59
  @jitsu/js:build: 3: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
45
60
  @jitsu/js:build: 4: return new (P || (P = Promise))(function (resolve, reject) {
46
61
  @jitsu/js:build: ...and 1 other occurrence
47
- @jitsu/js:build: compiled/src/destination-plugins.js
62
+ @jitsu/js:build: compiled/src/destination-plugins/gtm.js
63
+ @jitsu/js:build: 1: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
64
+ @jitsu/js:build:  ^
65
+ @jitsu/js:build: 2: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
66
+ @jitsu/js:build: 3: return new (P || (P = Promise))(function (resolve, reject) {
67
+ @jitsu/js:build: ...and 1 other occurrence
68
+ @jitsu/js:build: compiled/src/destination-plugins/logrocket.js
69
+ @jitsu/js:build: 1: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
70
+ @jitsu/js:build:  ^
71
+ @jitsu/js:build: 2: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
72
+ @jitsu/js:build: 3: return new (P || (P = Promise))(function (resolve, reject) {
73
+ @jitsu/js:build: ...and 1 other occurrence
74
+ @jitsu/js:build: compiled/src/destination-plugins/tag.js
48
75
  @jitsu/js:build: 1: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
49
76
  @jitsu/js:build:  ^
50
77
  @jitsu/js:build: 2: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -52,14 +79,17 @@
52
79
  @jitsu/js:build: ...and 1 other occurrence
53
80
  @jitsu/js:build: (!) Circular dependencies
54
81
  @jitsu/js:build: compiled/src/index.js -> compiled/src/analytics-plugin.js -> compiled/src/index.js
55
- @jitsu/js:build: compiled/src/analytics-plugin.js -> compiled/src/destination-plugins.js -> compiled/src/analytics-plugin.js
82
+ @jitsu/js:build: compiled/src/destination-plugins/index.js -> compiled/src/destination-plugins/tag.js -> compiled/src/destination-plugins/index.js
83
+ @jitsu/js:build: compiled/src/analytics-plugin.js -> compiled/src/destination-plugins/index.js -> compiled/src/destination-plugins/tag.js -> compiled/src/analytics-plugin.js
84
+ @jitsu/js:build: compiled/src/destination-plugins/index.js -> compiled/src/destination-plugins/logrocket.js -> compiled/src/destination-plugins/index.js
85
+ @jitsu/js:build: compiled/src/destination-plugins/index.js -> compiled/src/destination-plugins/gtm.js -> compiled/src/destination-plugins/index.js
56
86
  @jitsu/js:build: (!) Use of eval is strongly discouraged
57
- @jitsu/js:build: https://rollupjs.org/guide/en/#avoiding-eval
58
- @jitsu/js:build: compiled/src/destination-plugins.js
59
- @jitsu/js:build: 75: })()`;
60
- @jitsu/js:build: 76: try {
61
- @jitsu/js:build: 77: eval(iif);
87
+ @jitsu/js:build: https://rollupjs.org/troubleshooting/#avoiding-eval
88
+ @jitsu/js:build: compiled/src/destination-plugins/tag.js
89
+ @jitsu/js:build: 68: })()`;
90
+ @jitsu/js:build: 69: try {
91
+ @jitsu/js:build: 70: eval(iif);
62
92
  @jitsu/js:build:  ^
63
- @jitsu/js:build: 78: }
64
- @jitsu/js:build: 79: catch (e) {
65
- @jitsu/js:build: created dist/jitsu.es.js, dist/jitsu.cjs.js in 231ms
93
+ @jitsu/js:build: 71: }
94
+ @jitsu/js:build: 72: catch (e) {
95
+ @jitsu/js:build: created dist/jitsu.es.js, dist/jitsu.cjs.js in 151ms
@@ -1,4 +1,4 @@
1
- @jitsu/js:clean: cache hit, replaying output 8fcc48ba2013f124
1
+ @jitsu/js:clean: cache hit, replaying output 6f082eb620c44280
2
2
  @jitsu/js:clean: 
3
3
  @jitsu/js:clean: > @jitsu/js@0.0.0 clean /Users/ildarnurislamov/Projects/onetag/libs/jitsu-js
4
4
  @jitsu/js:clean: > rm -rf ./dist
@@ -1,7 +1,4 @@
1
- import fs from "fs";
2
- import path from "path";
3
1
  import { createServer, SimpleSyrup } from "../simple-syrup";
4
- import process from "process";
5
2
  import { AnalyticsClientEvent, AnalyticsInterface } from "@jitsu/protocols/analytics";
6
3
 
7
4
  const jitsuAnalytics = require("../../dist/jitsu.cjs.js").jitsuAnalytics;
@@ -49,6 +46,10 @@ describe("Test Jitsu NodeJS client", () => {
49
46
  email: "test@test.com",
50
47
  });
51
48
 
49
+ await jitsu.group("testGroup", {
50
+ name: "Test Group",
51
+ });
52
+
52
53
  await jitsu.page({
53
54
  name: "test",
54
55
  environment: "nodejs",
@@ -59,14 +60,16 @@ describe("Test Jitsu NodeJS client", () => {
59
60
  },
60
61
  });
61
62
  await new Promise(resolve => setTimeout(resolve, 1000));
62
- expect(requestLog.length).toBe(3);
63
+ expect(requestLog.length).toBe(4);
63
64
  expect(requestLog[0].type).toBe("track");
64
65
  expect(requestLog[1].type).toBe("identify");
65
- expect(requestLog[2].type).toBe("page");
66
+ expect(requestLog[2].type).toBe("group");
67
+ expect(requestLog[3].type).toBe("page");
66
68
 
67
69
  const track = requestLog[0].body as AnalyticsClientEvent;
68
70
  const identify = requestLog[1].body as AnalyticsClientEvent;
69
- const page = requestLog[2].body as AnalyticsClientEvent;
71
+ const group = requestLog[2].body as AnalyticsClientEvent;
72
+ const page = requestLog[3].body as AnalyticsClientEvent;
70
73
 
71
74
  //expect(track.userId).toBe(undefined);
72
75
  expect(page.properties.name).toBe("test");
@@ -75,6 +78,11 @@ describe("Test Jitsu NodeJS client", () => {
75
78
  expect(page.userId).toBe("testUser");
76
79
  expect(identify.traits.email).toBe("test@test.com");
77
80
  expect(identify.anonymousId).toBe(page.anonymousId);
81
+ expect(group.traits.name).toBe("Test Group");
82
+ expect(group.anonymousId).toBe(page.anonymousId);
83
+ expect(group.userId).toBe("testUser");
84
+ expect(group.groupId).toBe("testGroup");
85
+
78
86
  const pagePayload = requestLog[0].body;
79
87
  console.log("pagePayload", pagePayload);
80
88
  } finally {
@@ -7,8 +7,6 @@ import ejs from "ejs";
7
7
  import * as process from "process";
8
8
  import * as console from "console";
9
9
  import { AnalyticsClientEvent, AnalyticsInterface } from "@jitsu/protocols/analytics.d";
10
- import type { AnalyticsCore } from "@segment/analytics-next/src/core/analytics/interfaces";
11
- import { response } from "express";
12
10
 
13
11
  test.use({
14
12
  ignoreHTTPSErrors: true,
@@ -116,6 +114,7 @@ const generateTestEvents = async () => {
116
114
  await analytics.identify("userId2", { email: "john.doe2@gmail.com", caseName: "basic-identify" });
117
115
  // jitsu must extract traits even from 'id' object
118
116
  await analytics.identify({ email: "john.doe3@gmail.com", caseName: "identify-without-user-id" });
117
+ await analytics.group("group1", { name: "Group 1", caseName: "basic-group" });
119
118
  await analytics.page({ caseName: "page-without-name", context: { page: { title: "Synthetic Title" } } });
120
119
  await analytics.page("test-page", { caseName: "page-with-name" });
121
120
  await analytics.track("testEvent", { caseName: "track-with-name" });
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export declare const emptyAnalytics: {
5
5
  page: () => Promise<void>;
6
6
  user: () => {};
7
7
  identify: () => Promise<{}>;
8
+ group: () => Promise<{}>;
8
9
  reset: () => Promise<{}>;
9
10
  };
10
11
  export declare function jitsuAnalytics(opts: JitsuOptions): AnalyticsInterface;
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,193 @@ 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
+ return __awaiter$1(this, void 0, void 0, function* () {
288
+ if (!applyFilters(payload, config)) {
289
+ return;
290
+ }
291
+ yield initGtmIfNeeded(config);
292
+ const dataLayer = window[config.dataLayerName || "dataLayer"];
293
+ switch (payload.type) {
294
+ case "page":
295
+ const { properties: pageProperties } = payload;
296
+ const pageEvent = Object.assign({ event: "page_view" }, pageProperties);
297
+ if (config.debug) {
298
+ console.log("gtag push", pageEvent);
299
+ }
300
+ dataLayer.push(pageEvent);
301
+ break;
302
+ case "track":
303
+ const { properties: trackProperties } = payload;
304
+ const trackEvent = Object.assign({ event: payload.event }, trackProperties);
305
+ if (config.debug) {
306
+ console.log("gtag push", trackEvent);
307
+ }
308
+ dataLayer.push(trackEvent);
309
+ break;
310
+ case "identify":
311
+ const { anonymousId, userId, traits } = payload;
312
+ const user = traits;
313
+ if (userId) {
314
+ user.userId = userId;
315
+ }
316
+ if (anonymousId) {
317
+ user.anonymousId = anonymousId;
318
+ }
319
+ const identifyEvent = { event: "identify", user: user };
320
+ if (config.debug) {
321
+ console.log("gtag push", identifyEvent);
322
+ }
323
+ dataLayer.push(identifyEvent);
324
+ break;
325
+ }
326
+ });
327
+ },
328
+ };
329
+ function getGtmState() {
330
+ return window["__jitsuGtmState"] || "fresh";
331
+ }
332
+ function setGtmState(s) {
333
+ window["__jitsuGtmState"] = s;
334
+ }
335
+ function initGtmIfNeeded(config) {
336
+ return __awaiter$1(this, void 0, void 0, function* () {
337
+ if (getGtmState() !== "fresh") {
338
+ return;
339
+ }
340
+ setGtmState("loading");
341
+ const dlName = config.dataLayerName || "dataLayer";
342
+ const dlParam = dlName !== "dataLayer" ? "&l=" + dlName : "";
343
+ const previewParams = config.preview
344
+ ? `&gtm_preview=${config.preview}&gtm_auth=${config.auth}&gtm_cookies_win=x`
345
+ : "";
346
+ const scriptSrc = `${config.customScriptSrc || defaultScriptSrc}?id=${config.containerId}${dlParam}${previewParams}`;
347
+ window[dlName] = window[dlName] || [];
348
+ const gtag = function () {
349
+ window[dlName].push(arguments);
199
350
  };
200
- const tag = window.document.getElementsByTagName("script")[0];
201
- (_a = tag.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(script, tag);
351
+ // @ts-ignore
352
+ gtag("js", new Date());
353
+ // @ts-ignore
354
+ gtag("config", config.containerId);
355
+ loadScript(scriptSrc)
356
+ .then(() => {
357
+ setGtmState("loaded");
358
+ })
359
+ .catch(e => {
360
+ console.warn(`GTM (containerId=${config.containerId}) init failed: ${e.message}`, e);
361
+ setGtmState("failed");
362
+ });
202
363
  });
203
364
  }
204
365
 
366
+ function satisfyFilter(filter, subject) {
367
+ return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
368
+ }
369
+ function applyFilters(event, creds) {
370
+ const { hosts = ["*"], events = ["*"] } = creds;
371
+ return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
372
+ !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
373
+ }
374
+ const internalDestinationPlugins = {
375
+ [tagPlugin.id]: tagPlugin,
376
+ [gtmPlugin.id]: gtmPlugin,
377
+ [logrocketPlugin.id]: logrocketPlugin,
378
+ };
379
+
205
380
  /* global analytics */
206
381
  var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
207
382
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -220,6 +395,8 @@ const config = {
220
395
  debug: false,
221
396
  fetch: null,
222
397
  echoEvents: false,
398
+ cookieDomain: undefined,
399
+ runtime: undefined,
223
400
  };
224
401
  const parseQuery = (qs) => {
225
402
  if (!qs) {
@@ -443,7 +620,7 @@ function adjustPayload(payload, config, storage) {
443
620
  userAgent: runtime.userAgent(),
444
621
  locale: runtime.language(),
445
622
  screen: runtime.screen(),
446
- traits: payload.type != "identify" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
623
+ traits: payload.type != "identify" && payload.type != "group" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
447
624
  page: {
448
625
  path: properties.path || (parsedUrl && parsedUrl.pathname),
449
626
  referrer: referrer,
@@ -452,7 +629,7 @@ function adjustPayload(payload, config, storage) {
452
629
  search: properties.search || (parsedUrl && parsedUrl.search),
453
630
  title: properties.title || runtime.pageTitle(),
454
631
  url: properties.url || url,
455
- enconding: properties.enconding || runtime.documentEncoding(),
632
+ encoding: properties.encoding || runtime.documentEncoding(),
456
633
  },
457
634
  campaign: parseUtms(query),
458
635
  };
@@ -528,12 +705,12 @@ function send(method, payload, jitsuConfig, instance, store) {
528
705
  if (!fetch) {
529
706
  throw new Error("Please specify fetch function in jitsu plugin initialization, fetch isn't available in global scope");
530
707
  }
531
- const authHeader = {};
532
708
  const debugHeader = jitsuConfig.debug ? { "X-Enable-Debug": "true" } : {};
533
709
  // if (jitsuConfig.debug) {
534
710
  // console.log(`[JITSU] Sending event to ${url}: `, JSON.stringify(payload, null, 2));
535
711
  // }
536
712
  const adjustedPayload = adjustPayload(payload, jitsuConfig, store);
713
+ const authHeader = adjustedPayload.writeKey ? { "X-Write-Key": adjustedPayload.writeKey } : {};
537
714
  return fetch(url, {
538
715
  method: "POST",
539
716
  headers: Object.assign(Object.assign({ "Content-Type": "application/json" }, authHeader), debugHeader),
@@ -560,7 +737,7 @@ function send(method, payload, jitsuConfig, instance, store) {
560
737
  }
561
738
  if (response.destinations) {
562
739
  if (jitsuConfig.debug) {
563
- console.log(`[JITSU] Processing device destianations: `, JSON.stringify(response.destinations, null, 2));
740
+ console.log(`[JITSU] Processing device destinations: `, JSON.stringify(response.destinations, null, 2));
564
741
  }
565
742
  return processDestinations(response.destinations, method, adjustedPayload, !!jitsuConfig.debug, instance);
566
743
  }
@@ -589,9 +766,10 @@ const jitsuAnalyticsPlugin = (pluginConfig = {}) => {
589
766
  persistentStorage.removeItem(key);
590
767
  },
591
768
  });
769
+ const instanceConfig = Object.assign(Object.assign({}, config), pluginConfig);
592
770
  return {
593
771
  name: "jitsu",
594
- config: Object.assign(Object.assign({}, config), pluginConfig),
772
+ config: instanceConfig,
595
773
  initialize: args => {
596
774
  const { config } = args;
597
775
  if (config.debug) {
@@ -619,6 +797,16 @@ const jitsuAnalyticsPlugin = (pluginConfig = {}) => {
619
797
  //clear storage cache
620
798
  Object.keys(storageCache).forEach(key => delete storageCache[key]);
621
799
  },
800
+ methods: {
801
+ //analytics doesn't support group as a base method, so we need to add it manually
802
+ group(groupId, traits, options, callback) {
803
+ const analyticsInstance = this.instance;
804
+ const user = analyticsInstance.user();
805
+ const userId = (options === null || options === void 0 ? void 0 : options.userId) || (user === null || user === void 0 ? void 0 : user.userId);
806
+ const anonymousId = (options === null || options === void 0 ? void 0 : options.anonymousId) || (user === null || user === void 0 ? void 0 : user.anonymousId);
807
+ return send("group", Object.assign(Object.assign({ type: "group", groupId, traits }, (anonymousId ? { anonymousId } : {})), (userId ? { userId } : {})), instanceConfig, analyticsInstance, cachingStorageWrapper(analyticsInstance.storage));
808
+ },
809
+ },
622
810
  };
623
811
  };
624
812
  function getSeed() {
@@ -671,6 +859,7 @@ const emptyAnalytics = {
671
859
  page: () => Promise.resolve(),
672
860
  user: () => ({}),
673
861
  identify: () => Promise.resolve({}),
862
+ group: () => Promise.resolve({}),
674
863
  reset: () => Promise.resolve({}),
675
864
  };
676
865
  function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
@@ -689,7 +878,14 @@ function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
689
878
  return originalPage(...args);
690
879
  }
691
880
  };
692
- return analytics;
881
+ return Object.assign(Object.assign({}, analytics), { group(groupId, traits, options, callback) {
882
+ for (const plugin of Object.values(analytics.plugins)) {
883
+ if (plugin["group"]) {
884
+ plugin["group"](groupId, traits, options, callback);
885
+ }
886
+ }
887
+ return Promise.resolve({});
888
+ } });
693
889
  }
694
890
  function jitsuAnalytics(opts) {
695
891
  const inBrowser = isInBrowser();
package/dist/jitsu.d.ts CHANGED
@@ -15,7 +15,7 @@ type JitsuOptions = {
15
15
  */
16
16
  debug?: boolean;
17
17
  /**
18
- * Explicitely specify cookie domain. If not set, cookie domain will be set to top level
18
+ * Explicitly specify cookie domain. If not set, cookie domain will be set to top level
19
19
  * of the current domain. Example: if JS lives on "app.example.com", cookie domain will be
20
20
  * set to ".example.com". If it lives on "example.com", cookie domain will be set to ".example.com" too
21
21
  */