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

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
@@ -108,7 +108,7 @@ function loadScript(src, attributes) {
108
108
  });
109
109
  }
110
110
 
111
- var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
111
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
112
112
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
113
113
  return new (P || (P = Promise))(function (resolve, reject) {
114
114
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -117,10 +117,18 @@ var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _argu
117
117
  step((generator = generator.apply(thisArg, _arguments || [])).next());
118
118
  });
119
119
  };
120
+ function satisfyFilter(filter, subject) {
121
+ return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
122
+ }
123
+ function applyFilters(event, creds) {
124
+ const { hosts = ["*"], events = ["*"] } = creds;
125
+ return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
126
+ !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
127
+ }
120
128
  const tagPlugin = {
121
129
  id: "tag",
122
130
  handle(config, payload) {
123
- return __awaiter$3(this, void 0, void 0, function* () {
131
+ return __awaiter$1(this, void 0, void 0, function* () {
124
132
  if (!applyFilters(payload, config)) {
125
133
  return;
126
134
  }
@@ -128,96 +136,6 @@ const tagPlugin = {
128
136
  });
129
137
  },
130
138
  };
131
- function insertTags(code, event, opts = {}) {
132
- let tag;
133
- try {
134
- tag = JSON.parse(code);
135
- }
136
- catch (e) {
137
- tag = { code, lang: "javascript" };
138
- }
139
- const debug = opts.debug || false;
140
- if (isInBrowser()) {
141
- if (tag.lang === "javascript") {
142
- execJs(tag.code, event);
143
- }
144
- else {
145
- const codeHolder = document.createElement("span");
146
- codeHolder.innerHTML = replaceMacro(tag.code, event);
147
- document.body.insertAdjacentElement("beforeend", codeHolder);
148
- const scripts = codeHolder.querySelectorAll("script");
149
- scripts.forEach(script => {
150
- const scriptClone = document.createElement("script");
151
- scriptClone.type = scriptClone.type || "text/javascript";
152
- if (script.hasAttribute("src")) {
153
- scriptClone.src = script.src;
154
- }
155
- scriptClone.text = script.text;
156
- if (debug) {
157
- console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
158
- }
159
- document.head.appendChild(scriptClone);
160
- document.head.removeChild(scriptClone);
161
- });
162
- }
163
- }
164
- else {
165
- if (debug) {
166
- console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
167
- }
168
- }
169
- }
170
- function execJs(code, event) {
171
- const varName = `jitsu_event_${randomId()}`;
172
- window[varName] = event;
173
- const iif = `(function(){
174
- const event = ${varName};
175
- ${code}
176
- })()`;
177
- try {
178
- eval(iif);
179
- }
180
- catch (e) {
181
- console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
182
- }
183
- finally {
184
- delete window[varName];
185
- }
186
- return iif;
187
- }
188
- function replaceMacro(code, event) {
189
- return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
190
- }
191
-
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
139
  function getLogRocketState() {
222
140
  return window["__jitsuLrState"] || "fresh";
223
141
  }
@@ -243,7 +161,7 @@ function flushLogRocketQueue(lr) {
243
161
  }
244
162
  }
245
163
  function initLogrocketIfNeeded(appId) {
246
- return __awaiter$2(this, void 0, void 0, function* () {
164
+ return __awaiter$1(this, void 0, void 0, function* () {
247
165
  if (getLogRocketState() !== "fresh") {
248
166
  return;
249
167
  }
@@ -268,126 +186,94 @@ function initLogrocketIfNeeded(appId) {
268
186
  });
269
187
  });
270
188
  }
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",
189
+ const logrocketPlugin = {
190
+ id: "logrocket",
284
191
  handle(config, payload) {
285
- var _a, _b;
286
192
  return __awaiter$1(this, void 0, void 0, function* () {
287
193
  if (!applyFilters(payload, config)) {
288
194
  return;
289
195
  }
290
- yield initGtmIfNeeded(config);
291
- const dataLayer = window[config.dataLayerName || "dataLayer"];
292
- switch (payload.type) {
293
- case "page":
294
- const { properties: pageProperties, context } = payload;
295
- const pageEvent = {
296
- event: "page_view",
297
- url: pageProperties.url,
298
- title: pageProperties.title,
299
- 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 : "",
300
- };
301
- if (config.debug) {
302
- console.log("gtag push", pageEvent);
303
- }
304
- dataLayer.push(pageEvent);
305
- break;
306
- case "track":
307
- const { properties: trackProperties } = payload;
308
- const trackEvent = Object.assign({ event: payload.event }, trackProperties);
309
- if (payload.userId) {
310
- trackEvent.userId = payload.userId;
311
- }
312
- if (payload.anonymousId) {
313
- trackEvent.anonymousId = payload.anonymousId;
314
- }
315
- if (config.debug) {
316
- console.log("gtag push", trackEvent);
317
- }
318
- dataLayer.push(trackEvent);
319
- break;
320
- case "identify":
321
- const { traits } = payload;
322
- const identifyEvent = Object.assign({ event: "identify" }, traits);
323
- if (payload.userId) {
324
- identifyEvent.userId = payload.userId;
325
- }
326
- if (payload.anonymousId) {
327
- identifyEvent.anonymousId = payload.anonymousId;
328
- }
329
- if (config.debug) {
330
- console.log("gtag push", identifyEvent);
331
- }
332
- dataLayer.push(identifyEvent);
333
- break;
196
+ initLogrocketIfNeeded(config.appId);
197
+ const action = logRocket => {
198
+ if (payload.type === "identify" && payload.userId) {
199
+ logRocket.identify(payload.userId, payload.traits || {});
200
+ }
201
+ };
202
+ getLogRocketQueue().push(action);
203
+ if (getLogRocketState() === "loaded") {
204
+ flushLogRocketQueue(window["LogRocket"]);
334
205
  }
335
206
  });
336
207
  },
337
208
  };
338
- function getGtmState() {
339
- return window["__jitsuGtmState"] || "fresh";
340
- }
341
- function setGtmState(s) {
342
- window["__jitsuGtmState"] = s;
343
- }
344
- function initGtmIfNeeded(config) {
345
- return __awaiter$1(this, void 0, void 0, function* () {
346
- if (getGtmState() !== "fresh") {
347
- return;
209
+ function insertTags(code, event, opts = {}) {
210
+ let tag;
211
+ try {
212
+ tag = JSON.parse(code);
213
+ }
214
+ catch (e) {
215
+ tag = { code, lang: "javascript" };
216
+ }
217
+ const debug = opts.debug || false;
218
+ if (isInBrowser()) {
219
+ if (tag.lang === "javascript") {
220
+ execJs(tag.code, event);
348
221
  }
349
- setGtmState("loading");
350
- const dlName = config.dataLayerName || "dataLayer";
351
- const dlParam = dlName !== "dataLayer" ? "&l=" + dlName : "";
352
- const previewParams = config.preview
353
- ? `&gtm_preview=${config.preview}&gtm_auth=${config.auth}&gtm_cookies_win=x`
354
- : "";
355
- const scriptSrc = `${config.customScriptSrc || defaultScriptSrc}?id=${config.containerId}${dlParam}${previewParams}`;
356
- window[dlName] = window[dlName] || [];
357
- const gtag = function () {
358
- window[dlName].push(arguments);
359
- };
360
- // @ts-ignore
361
- gtag("js", new Date());
362
- // @ts-ignore
363
- gtag("config", config.containerId);
364
- loadScript(scriptSrc)
365
- .then(() => {
366
- setGtmState("loaded");
367
- })
368
- .catch(e => {
369
- console.warn(`GTM (containerId=${config.containerId}) init failed: ${e.message}`, e);
370
- setGtmState("failed");
371
- });
372
- });
222
+ else {
223
+ const codeHolder = document.createElement("span");
224
+ codeHolder.innerHTML = replaceMacro(tag.code, event);
225
+ document.body.insertAdjacentElement("beforeend", codeHolder);
226
+ const scripts = codeHolder.querySelectorAll("script");
227
+ scripts.forEach(script => {
228
+ const scriptClone = document.createElement("script");
229
+ scriptClone.type = scriptClone.type || "text/javascript";
230
+ if (script.hasAttribute("src")) {
231
+ scriptClone.src = script.src;
232
+ }
233
+ scriptClone.text = script.text;
234
+ if (debug) {
235
+ console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
236
+ }
237
+ document.head.appendChild(scriptClone);
238
+ document.head.removeChild(scriptClone);
239
+ });
240
+ }
241
+ }
242
+ else {
243
+ if (debug) {
244
+ console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
245
+ }
246
+ }
373
247
  }
374
-
375
- function satisfyFilter(filter, subject) {
376
- return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
248
+ function execJs(code, event) {
249
+ const varName = `jitsu_event_${randomId()}`;
250
+ window[varName] = event;
251
+ const iif = `(function(){
252
+ const event = ${varName};
253
+ ${code}
254
+ })()`;
255
+ try {
256
+ eval(iif);
257
+ }
258
+ catch (e) {
259
+ console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
260
+ }
261
+ finally {
262
+ delete window[varName];
263
+ }
264
+ return iif;
377
265
  }
378
- function applyFilters(event, creds) {
379
- const { hosts = "*", events = "*" } = creds;
380
- const eventsArray = events.split("\n");
381
- return (!!hosts.split("\n").find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
382
- (!!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.type)) ||
383
- !!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.event))));
266
+ function replaceMacro(code, event) {
267
+ return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
384
268
  }
385
269
  const internalDestinationPlugins = {
386
270
  [tagPlugin.id]: tagPlugin,
387
- [gtmPlugin.id]: gtmPlugin,
388
271
  [logrocketPlugin.id]: logrocketPlugin,
389
272
  };
390
273
 
274
+ var name = "@jitsu/js";
275
+ var version = "0.0.0";
276
+
391
277
  /* global analytics */
392
278
  var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
393
279
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -625,8 +511,8 @@ function adjustPayload(payload, config, storage) {
625
511
  const referrer = runtime.referrer();
626
512
  const context = {
627
513
  library: {
628
- name: "jitsu-js",
629
- version: "1.0.0",
514
+ name: name,
515
+ version: version,
630
516
  },
631
517
  userAgent: runtime.userAgent(),
632
518
  locale: runtime.language(),
@@ -644,7 +530,7 @@ function adjustPayload(payload, config, storage) {
644
530
  },
645
531
  campaign: parseUtms(query),
646
532
  };
647
- const withContext = Object.assign(Object.assign({}, payload), { timestamp: new Date().toISOString(), sentAt: new Date().toISOString(), messageId: randomId(properties.path || (parsedUrl && parsedUrl.pathname)), writeKey: config.writeKey, context: deepMerge(context, customContext) });
533
+ const withContext = Object.assign(Object.assign({}, payload), { timestamp: new Date().toISOString(), sentAt: new Date().toISOString(), messageId: randomId(properties.path || (parsedUrl && parsedUrl.pathname)), writeKey: validateWriteKey(config.writeKey), context: deepMerge(context, customContext) });
648
534
  delete withContext.meta;
649
535
  delete withContext.options;
650
536
  return withContext;
@@ -658,7 +544,6 @@ function processDestinations(destinations, method, event, debug, analyticsInstan
658
544
  const plugin = internalDestinationPlugins[destination.deviceOptions.name];
659
545
  if (plugin) {
660
546
  try {
661
- //to support old versions, where credentials were stored in root
662
547
  promises.push(plugin.handle(credentials, event));
663
548
  }
664
549
  catch (e) {
@@ -706,6 +591,15 @@ function processDestinations(destinations, method, event, debug, analyticsInstan
706
591
  }
707
592
  });
708
593
  }
594
+ function validateWriteKey(writeKey) {
595
+ if (writeKey) {
596
+ const [, secret] = writeKey.split(":", 2);
597
+ if (!secret) {
598
+ 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`);
599
+ }
600
+ }
601
+ return writeKey;
602
+ }
709
603
  function send(method, payload, jitsuConfig, instance, store) {
710
604
  if (jitsuConfig.echoEvents) {
711
605
  console.log(`[JITSU] sending '${method}' event:`, payload);
@@ -721,7 +615,7 @@ function send(method, payload, jitsuConfig, instance, store) {
721
615
  // console.log(`[JITSU] Sending event to ${url}: `, JSON.stringify(payload, null, 2));
722
616
  // }
723
617
  const adjustedPayload = adjustPayload(payload, jitsuConfig, store);
724
- const authHeader = adjustedPayload.writeKey ? { "X-Write-Key": adjustedPayload.writeKey } : {};
618
+ const authHeader = config.writeKey ? { "X-Write-Key": validateWriteKey(config.writeKey) } : {};
725
619
  return fetch(url, {
726
620
  method: "POST",
727
621
  headers: Object.assign(Object.assign({ "Content-Type": "application/json" }, authHeader), debugHeader),
@@ -0,0 +1,2 @@
1
+ import { name as jitsuLibraryName, version as jitsuVersion } from "../package.json";
2
+ export { jitsuVersion, jitsuLibraryName };