@jitsu/js 1.1.1 → 1.1.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/dist/web/p.js.txt CHANGED
@@ -111,7 +111,7 @@
111
111
  });
112
112
  }
113
113
 
114
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
114
+ var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
115
115
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
116
116
  return new (P || (P = Promise))(function (resolve, reject) {
117
117
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -120,18 +120,10 @@
120
120
  step((generator = generator.apply(thisArg, _arguments || [])).next());
121
121
  });
122
122
  };
123
- function satisfyFilter(filter, subject) {
124
- return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
125
- }
126
- function applyFilters(event, creds) {
127
- const { hosts = ["*"], events = ["*"] } = creds;
128
- return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
129
- !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
130
- }
131
123
  const tagPlugin = {
132
124
  id: "tag",
133
125
  handle(config, payload) {
134
- return __awaiter$1(this, void 0, void 0, function* () {
126
+ return __awaiter$3(this, void 0, void 0, function* () {
135
127
  if (!applyFilters(payload, config)) {
136
128
  return;
137
129
  }
@@ -139,6 +131,96 @@
139
131
  });
140
132
  },
141
133
  };
134
+ function insertTags(code, event, opts = {}) {
135
+ let tag;
136
+ try {
137
+ tag = JSON.parse(code);
138
+ }
139
+ catch (e) {
140
+ tag = { code, lang: "javascript" };
141
+ }
142
+ const debug = opts.debug || false;
143
+ if (isInBrowser()) {
144
+ if (tag.lang === "javascript") {
145
+ execJs(tag.code, event);
146
+ }
147
+ else {
148
+ const codeHolder = document.createElement("span");
149
+ codeHolder.innerHTML = replaceMacro(tag.code, event);
150
+ document.body.insertAdjacentElement("beforeend", codeHolder);
151
+ const scripts = codeHolder.querySelectorAll("script");
152
+ scripts.forEach(script => {
153
+ const scriptClone = document.createElement("script");
154
+ scriptClone.type = scriptClone.type || "text/javascript";
155
+ if (script.hasAttribute("src")) {
156
+ scriptClone.src = script.src;
157
+ }
158
+ scriptClone.text = script.text;
159
+ if (debug) {
160
+ console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
161
+ }
162
+ document.head.appendChild(scriptClone);
163
+ document.head.removeChild(scriptClone);
164
+ });
165
+ }
166
+ }
167
+ else {
168
+ if (debug) {
169
+ console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
170
+ }
171
+ }
172
+ }
173
+ function execJs(code, event) {
174
+ const varName = `jitsu_event_${randomId()}`;
175
+ window[varName] = event;
176
+ const iif = `(function(){
177
+ const event = ${varName};
178
+ ${code}
179
+ })()`;
180
+ try {
181
+ eval(iif);
182
+ }
183
+ catch (e) {
184
+ console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
185
+ }
186
+ finally {
187
+ delete window[varName];
188
+ }
189
+ return iif;
190
+ }
191
+ function replaceMacro(code, event) {
192
+ return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
193
+ }
194
+
195
+ var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
196
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
197
+ return new (P || (P = Promise))(function (resolve, reject) {
198
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
199
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
200
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
201
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
202
+ });
203
+ };
204
+ const logrocketPlugin = {
205
+ id: "logrocket",
206
+ handle(config, payload) {
207
+ return __awaiter$2(this, void 0, void 0, function* () {
208
+ if (!applyFilters(payload, config)) {
209
+ return;
210
+ }
211
+ initLogrocketIfNeeded(config.appId);
212
+ const action = logRocket => {
213
+ if (payload.type === "identify" && payload.userId) {
214
+ logRocket.identify(payload.userId, payload.traits || {});
215
+ }
216
+ };
217
+ getLogRocketQueue().push(action);
218
+ if (getLogRocketState() === "loaded") {
219
+ flushLogRocketQueue(window["LogRocket"]);
220
+ }
221
+ });
222
+ },
223
+ };
142
224
  function getLogRocketState() {
143
225
  return window["__jitsuLrState"] || "fresh";
144
226
  }
@@ -164,7 +246,7 @@
164
246
  }
165
247
  }
166
248
  function initLogrocketIfNeeded(appId) {
167
- return __awaiter$1(this, void 0, void 0, function* () {
249
+ return __awaiter$2(this, void 0, void 0, function* () {
168
250
  if (getLogRocketState() !== "fresh") {
169
251
  return;
170
252
  }
@@ -189,88 +271,135 @@
189
271
  });
190
272
  });
191
273
  }
192
- const logrocketPlugin = {
193
- id: "logrocket",
274
+
275
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
276
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
277
+ return new (P || (P = Promise))(function (resolve, reject) {
278
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
279
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
280
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
281
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
282
+ });
283
+ };
284
+ const defaultScriptSrc = "https://www.googletagmanager.com/gtag/js";
285
+ const gtmPlugin = {
286
+ id: "gtm",
194
287
  handle(config, payload) {
288
+ var _a, _b;
195
289
  return __awaiter$1(this, void 0, void 0, function* () {
196
290
  if (!applyFilters(payload, config)) {
197
291
  return;
198
292
  }
199
- initLogrocketIfNeeded(config.appId);
200
- const action = logRocket => {
201
- if (payload.type === "identify" && payload.userId) {
202
- logRocket.identify(payload.userId, payload.traits || {});
203
- }
204
- };
205
- getLogRocketQueue().push(action);
206
- if (getLogRocketState() === "loaded") {
207
- flushLogRocketQueue(window["LogRocket"]);
293
+ yield initGtmIfNeeded(config);
294
+ const dataLayer = window[config.dataLayerName || "dataLayer"];
295
+ switch (payload.type) {
296
+ case "page":
297
+ const { properties: pageProperties, context } = payload;
298
+ const pageEvent = {
299
+ event: "page_view",
300
+ url: pageProperties.url,
301
+ title: pageProperties.title,
302
+ 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 : "",
303
+ };
304
+ if (config.debug) {
305
+ console.log("gtag push", pageEvent);
306
+ }
307
+ dataLayer.push(pageEvent);
308
+ break;
309
+ case "track":
310
+ const { properties: trackProperties } = payload;
311
+ const trackEvent = Object.assign({ event: payload.event }, trackProperties);
312
+ if (payload.userId) {
313
+ trackEvent.userId = payload.userId;
314
+ }
315
+ if (payload.anonymousId) {
316
+ trackEvent.anonymousId = payload.anonymousId;
317
+ }
318
+ if (config.debug) {
319
+ console.log("gtag push", trackEvent);
320
+ }
321
+ dataLayer.push(trackEvent);
322
+ break;
323
+ case "identify":
324
+ const { traits } = payload;
325
+ const identifyEvent = Object.assign({ event: "identify" }, traits);
326
+ if (payload.userId) {
327
+ identifyEvent.userId = payload.userId;
328
+ }
329
+ if (payload.anonymousId) {
330
+ identifyEvent.anonymousId = payload.anonymousId;
331
+ }
332
+ if (config.debug) {
333
+ console.log("gtag push", identifyEvent);
334
+ }
335
+ dataLayer.push(identifyEvent);
336
+ break;
208
337
  }
209
338
  });
210
339
  },
211
340
  };
212
- function insertTags(code, event, opts = {}) {
213
- let tag;
214
- try {
215
- tag = JSON.parse(code);
216
- }
217
- catch (e) {
218
- tag = { code, lang: "javascript" };
219
- }
220
- const debug = opts.debug || false;
221
- if (isInBrowser()) {
222
- if (tag.lang === "javascript") {
223
- execJs(tag.code, event);
224
- }
225
- else {
226
- const codeHolder = document.createElement("span");
227
- codeHolder.innerHTML = replaceMacro(tag.code, event);
228
- document.body.insertAdjacentElement("beforeend", codeHolder);
229
- const scripts = codeHolder.querySelectorAll("script");
230
- scripts.forEach(script => {
231
- const scriptClone = document.createElement("script");
232
- scriptClone.type = scriptClone.type || "text/javascript";
233
- if (script.hasAttribute("src")) {
234
- scriptClone.src = script.src;
235
- }
236
- scriptClone.text = script.text;
237
- if (debug) {
238
- console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
239
- }
240
- document.head.appendChild(scriptClone);
241
- document.head.removeChild(scriptClone);
242
- });
243
- }
244
- }
245
- else {
246
- if (debug) {
247
- console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
341
+ function getGtmState() {
342
+ return window["__jitsuGtmState"] || "fresh";
343
+ }
344
+ function setGtmState(s) {
345
+ window["__jitsuGtmState"] = s;
346
+ }
347
+ function initGtmIfNeeded(config) {
348
+ return __awaiter$1(this, void 0, void 0, function* () {
349
+ if (getGtmState() !== "fresh") {
350
+ return;
248
351
  }
249
- }
352
+ setGtmState("loading");
353
+ const dlName = config.dataLayerName || "dataLayer";
354
+ const dlParam = dlName !== "dataLayer" ? "&l=" + dlName : "";
355
+ const previewParams = config.preview
356
+ ? `&gtm_preview=${config.preview}&gtm_auth=${config.auth}&gtm_cookies_win=x`
357
+ : "";
358
+ const scriptSrc = `${config.customScriptSrc || defaultScriptSrc}?id=${config.containerId}${dlParam}${previewParams}`;
359
+ window[dlName] = window[dlName] || [];
360
+ const gtag = function () {
361
+ window[dlName].push(arguments);
362
+ };
363
+ // @ts-ignore
364
+ gtag("js", new Date());
365
+ // @ts-ignore
366
+ gtag("config", config.containerId);
367
+ loadScript(scriptSrc)
368
+ .then(() => {
369
+ setGtmState("loaded");
370
+ })
371
+ .catch(e => {
372
+ console.warn(`GTM (containerId=${config.containerId}) init failed: ${e.message}`, e);
373
+ setGtmState("failed");
374
+ });
375
+ });
250
376
  }
251
- function execJs(code, event) {
252
- const varName = `jitsu_event_${randomId()}`;
253
- window[varName] = event;
254
- const iif = `(function(){
255
- const event = ${varName};
256
- ${code}
257
- })()`;
258
- try {
259
- eval(iif);
377
+
378
+ function satisfyFilter(filter, subject) {
379
+ return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
380
+ }
381
+ function satisfyDomainFilter(filter, subject) {
382
+ if (filter === "*") {
383
+ return true;
260
384
  }
261
- catch (e) {
262
- console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
385
+ subject = subject || "";
386
+ if (filter.startsWith("*.")) {
387
+ return subject.endsWith(filter.substring(1));
263
388
  }
264
- finally {
265
- delete window[varName];
389
+ else {
390
+ return filter === subject;
266
391
  }
267
- return iif;
268
392
  }
269
- function replaceMacro(code, event) {
270
- return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
393
+ function applyFilters(event, creds) {
394
+ const { hosts = "*", events = "*" } = creds;
395
+ const eventsArray = events.split("\n");
396
+ return (!!hosts.split("\n").find(hostFilter => { var _a; return satisfyDomainFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
397
+ (!!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.type)) ||
398
+ !!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.event))));
271
399
  }
272
400
  const internalDestinationPlugins = {
273
401
  [tagPlugin.id]: tagPlugin,
402
+ [gtmPlugin.id]: gtmPlugin,
274
403
  [logrocketPlugin.id]: logrocketPlugin,
275
404
  };
276
405
 
@@ -287,7 +416,7 @@
287
416
  step((generator = generator.apply(thisArg, _arguments || [])).next());
288
417
  });
289
418
  };
290
- const config = {
419
+ const defaultConfig = {
291
420
  /* Your segment writeKey */
292
421
  writeKey: null,
293
422
  /* Disable anonymous MTU */
@@ -594,10 +723,13 @@
594
723
  }
595
724
  });
596
725
  }
726
+ function looksLikeCuid(id) {
727
+ return id.length === 25 && id.charAt(0) === "c";
728
+ }
597
729
  function validateWriteKey(writeKey) {
598
730
  if (writeKey) {
599
731
  const [, secret] = writeKey.split(":", 2);
600
- if (!secret) {
732
+ if (!secret && !looksLikeCuid(writeKey)) {
601
733
  throw new Error(`Legacy write key detected - ${writeKey}! This format doesn't work anymore, it should be 'key:secret'. Please download a new key from Jitsu UI`);
602
734
  }
603
735
  }
@@ -618,7 +750,7 @@
618
750
  // console.log(`[JITSU] Sending event to ${url}: `, JSON.stringify(payload, null, 2));
619
751
  // }
620
752
  const adjustedPayload = adjustPayload(payload, jitsuConfig, store);
621
- const authHeader = config.writeKey ? { "X-Write-Key": validateWriteKey(config.writeKey) } : {};
753
+ const authHeader = jitsuConfig.writeKey ? { "X-Write-Key": validateWriteKey(jitsuConfig.writeKey) } : {};
622
754
  return fetch(url, {
623
755
  method: "POST",
624
756
  headers: Object.assign(Object.assign({ "Content-Type": "application/json" }, authHeader), debugHeader),
@@ -674,7 +806,7 @@
674
806
  persistentStorage.removeItem(key);
675
807
  },
676
808
  });
677
- const instanceConfig = Object.assign(Object.assign({}, config), pluginConfig);
809
+ const instanceConfig = Object.assign(Object.assign({}, defaultConfig), pluginConfig);
678
810
  return {
679
811
  name: "jitsu",
680
812
  config: instanceConfig,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jitsu/js",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "",
5
5
  "author": "Jitsu Dev Team <dev@jitsu.com>",
6
6
  "main": "dist/jitsu.cjs.js",
@@ -12,7 +12,7 @@
12
12
  "license": "MIT",
13
13
  "private": false,
14
14
  "devDependencies": {
15
- "@playwright/test": "1.30.0",
15
+ "@playwright/test": "1.31.2",
16
16
  "@rollup/plugin-commonjs": "^23.0.2",
17
17
  "@rollup/plugin-json": "^5.0.1",
18
18
  "@rollup/plugin-multi-entry": "^6.0.0",
@@ -34,7 +34,7 @@
34
34
  "rollup": "^3.2.5",
35
35
  "ts-jest": "29.0.5",
36
36
  "typescript": "^4.9.5",
37
- "@jitsu/protocols": "1.1.1"
37
+ "@jitsu/protocols": "1.1.2"
38
38
  },
39
39
  "dependencies": {
40
40
  "analytics": "^0.8.1"
@@ -8,7 +8,7 @@ import { loadScript } from "./script-loader";
8
8
  import { internalDestinationPlugins } from "./destination-plugins";
9
9
  import { jitsuLibraryName, jitsuVersion } from "./version";
10
10
 
11
- const config: Required<JitsuOptions> = {
11
+ const defaultConfig: Required<JitsuOptions> = {
12
12
  /* Your segment writeKey */
13
13
  writeKey: null,
14
14
  /* Disable anonymous MTU */
@@ -387,10 +387,14 @@ async function processDestinations(
387
387
  }
388
388
  }
389
389
 
390
+ function looksLikeCuid(id: string) {
391
+ return id.length === 25 && id.charAt(0) === "c";
392
+ }
393
+
390
394
  function validateWriteKey(writeKey?: string): string | undefined {
391
395
  if (writeKey) {
392
396
  const [, secret] = writeKey.split(":", 2);
393
- if (!secret) {
397
+ if (!secret && !looksLikeCuid(writeKey)) {
394
398
  throw new Error(
395
399
  `Legacy write key detected - ${writeKey}! This format doesn't work anymore, it should be 'key:secret'. Please download a new key from Jitsu UI`
396
400
  );
@@ -398,7 +402,6 @@ function validateWriteKey(writeKey?: string): string | undefined {
398
402
  }
399
403
  return writeKey;
400
404
  }
401
-
402
405
  function send(
403
406
  method,
404
407
  payload,
@@ -424,7 +427,9 @@ function send(
424
427
  // console.log(`[JITSU] Sending event to ${url}: `, JSON.stringify(payload, null, 2));
425
428
  // }
426
429
  const adjustedPayload = adjustPayload(payload, jitsuConfig, store);
427
- const authHeader = config.writeKey ? { "X-Write-Key": validateWriteKey(config.writeKey) } : {};
430
+
431
+ const authHeader = jitsuConfig.writeKey ? { "X-Write-Key": validateWriteKey(jitsuConfig.writeKey) } : {};
432
+
428
433
  return fetch(url, {
429
434
  method: "POST",
430
435
  headers: {
@@ -488,7 +493,7 @@ const jitsuAnalyticsPlugin = (pluginConfig: JitsuOptions = {}): AnalyticsPlugin
488
493
  },
489
494
  });
490
495
  const instanceConfig = {
491
- ...config,
496
+ ...defaultConfig,
492
497
  ...pluginConfig,
493
498
  };
494
499
  return {
@@ -1,17 +0,0 @@
1
- import { AnalyticsClientEvent } from "@jitsu/protocols/analytics";
2
- export type InternalPlugin<T> = {
3
- id: string;
4
- handle(config: T, payload: AnalyticsClientEvent): Promise<void>;
5
- };
6
- export type CommonDestinationCredentials = {
7
- hosts?: string[];
8
- events?: string[];
9
- };
10
- export type TagDestinationCredentials = {
11
- code: string;
12
- } & CommonDestinationCredentials;
13
- export type LogRocketDestinationCredentials = {
14
- appId: string;
15
- } & CommonDestinationCredentials;
16
- export type LogRocket = any;
17
- export declare const internalDestinationPlugins: Record<string, InternalPlugin<any>>;