core-outline 1.1.21 → 1.1.23

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/index.es.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import React, { useState, useRef, useEffect } from 'react';
2
2
  import { v4 } from 'uuid';
3
- import { parse, installTimerFunctions, Socket as Socket$1, nextTick } from 'engine.io-client';
4
3
 
5
4
  function _arrayLikeToArray(r, a) {
6
5
  (null == a || a > r.length) && (a = r.length);
@@ -38,6 +37,14 @@ function _asyncToGenerator(n) {
38
37
  });
39
38
  };
40
39
  }
40
+ function _defineProperty(e, r, t) {
41
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
42
+ value: t,
43
+ enumerable: !0,
44
+ configurable: !0,
45
+ writable: !0
46
+ }) : e[r] = t, e;
47
+ }
41
48
  function _iterableToArray(r) {
42
49
  if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
43
50
  }
@@ -74,6 +81,27 @@ function _nonIterableRest() {
74
81
  function _nonIterableSpread() {
75
82
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
76
83
  }
84
+ function ownKeys(e, r) {
85
+ var t = Object.keys(e);
86
+ if (Object.getOwnPropertySymbols) {
87
+ var o = Object.getOwnPropertySymbols(e);
88
+ r && (o = o.filter(function (r) {
89
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
90
+ })), t.push.apply(t, o);
91
+ }
92
+ return t;
93
+ }
94
+ function _objectSpread2(e) {
95
+ for (var r = 1; r < arguments.length; r++) {
96
+ var t = null != arguments[r] ? arguments[r] : {};
97
+ r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
98
+ _defineProperty(e, r, t[r]);
99
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
100
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
101
+ });
102
+ }
103
+ return e;
104
+ }
77
105
  function _regeneratorRuntime() {
78
106
  _regeneratorRuntime = function () {
79
107
  return e;
@@ -381,6 +409,20 @@ function _slicedToArray(r, e) {
381
409
  function _toConsumableArray(r) {
382
410
  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
383
411
  }
412
+ function _toPrimitive(t, r) {
413
+ if ("object" != typeof t || !t) return t;
414
+ var e = t[Symbol.toPrimitive];
415
+ if (void 0 !== e) {
416
+ var i = e.call(t, r || "default");
417
+ if ("object" != typeof i) return i;
418
+ throw new TypeError("@@toPrimitive must return a primitive value.");
419
+ }
420
+ return ("string" === r ? String : Number)(t);
421
+ }
422
+ function _toPropertyKey(t) {
423
+ var i = _toPrimitive(t, "string");
424
+ return "symbol" == typeof i ? i : i + "";
425
+ }
384
426
  function _unsupportedIterableToArray(r, a) {
385
427
  if (r) {
386
428
  if ("string" == typeof r) return _arrayLikeToArray(r, a);
@@ -1411,7 +1453,7 @@ function snapshot(n, options) {
1411
1453
  });
1412
1454
  }
1413
1455
 
1414
- function on$1(type, fn, target = document) {
1456
+ function on(type, fn, target = document) {
1415
1457
  const options = { capture: true, passive: true };
1416
1458
  target.addEventListener(type, fn, options);
1417
1459
  return () => target.removeEventListener(type, fn, options);
@@ -2314,9 +2356,9 @@ function initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {
2314
2356
  trailing: false,
2315
2357
  });
2316
2358
  const handlers = [
2317
- on$1('mousemove', updatePosition, doc),
2318
- on$1('touchmove', updatePosition, doc),
2319
- on$1('drag', updatePosition, doc),
2359
+ on('mousemove', updatePosition, doc),
2360
+ on('touchmove', updatePosition, doc),
2361
+ on('drag', updatePosition, doc),
2320
2362
  ];
2321
2363
  return () => {
2322
2364
  handlers.forEach((h) => h());
@@ -2359,7 +2401,7 @@ function initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockCl
2359
2401
  .forEach((eventKey) => {
2360
2402
  const eventName = eventKey.toLowerCase();
2361
2403
  const handler = getHandler(eventKey);
2362
- handlers.push(on$1(eventName, handler, doc));
2404
+ handlers.push(on(eventName, handler, doc));
2363
2405
  });
2364
2406
  return () => {
2365
2407
  handlers.forEach((h) => h());
@@ -2388,7 +2430,7 @@ function initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector,
2388
2430
  });
2389
2431
  }
2390
2432
  }, sampling.scroll || 100);
2391
- return on$1('scroll', updatePosition, doc);
2433
+ return on('scroll', updatePosition, doc);
2392
2434
  }
2393
2435
  function initViewportResizeObserver({ viewportResizeCb, }) {
2394
2436
  let lastH = -1;
@@ -2405,7 +2447,7 @@ function initViewportResizeObserver({ viewportResizeCb, }) {
2405
2447
  lastW = width;
2406
2448
  }
2407
2449
  }, 200);
2408
- return on$1('resize', updateDimension, window);
2450
+ return on('resize', updateDimension, window);
2409
2451
  }
2410
2452
  function wrapEventWithUserTriggeredFlag(v, enable) {
2411
2453
  const value = Object.assign({}, v);
@@ -2473,7 +2515,7 @@ function initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, ig
2473
2515
  }
2474
2516
  }
2475
2517
  const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];
2476
- const handlers = events.map((eventName) => on$1(eventName, eventHandler, doc));
2518
+ const handlers = events.map((eventName) => on(eventName, eventHandler, doc));
2477
2519
  const currentWindow = doc.defaultView;
2478
2520
  if (!currentWindow) {
2479
2521
  return () => {
@@ -2767,11 +2809,11 @@ function initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSel
2767
2809
  });
2768
2810
  }, sampling.media || 500);
2769
2811
  const handlers = [
2770
- on$1('play', handler(0)),
2771
- on$1('pause', handler(1)),
2772
- on$1('seeked', handler(2)),
2773
- on$1('volumechange', handler(3)),
2774
- on$1('ratechange', handler(4)),
2812
+ on('play', handler(0)),
2813
+ on('pause', handler(1)),
2814
+ on('seeked', handler(2)),
2815
+ on('volumechange', handler(3)),
2816
+ on('ratechange', handler(4)),
2775
2817
  ];
2776
2818
  return () => {
2777
2819
  handlers.forEach((h) => h());
@@ -2845,7 +2887,7 @@ function initSelectionObserver(param) {
2845
2887
  selectionCb({ ranges });
2846
2888
  };
2847
2889
  updateSelection();
2848
- return on$1('selectionchange', updateSelection);
2890
+ return on('selectionchange', updateSelection);
2849
2891
  }
2850
2892
  function mergeHooks(o, hooks) {
2851
2893
  const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, selectionCb, } = o;
@@ -3321,9 +3363,9 @@ function __awaiter(thisArg, _arguments, P, generator) {
3321
3363
  */
3322
3364
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
3323
3365
  // Use a lookup table to find the index.
3324
- var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
3366
+ var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
3325
3367
  for (var i = 0; i < chars.length; i++) {
3326
- lookup$1[chars.charCodeAt(i)] = i;
3368
+ lookup[chars.charCodeAt(i)] = i;
3327
3369
  }
3328
3370
  var encode = function (arraybuffer) {
3329
3371
  var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
@@ -4166,7 +4208,7 @@ function record(options = {}) {
4166
4208
  };
4167
4209
  try {
4168
4210
  const handlers = [];
4169
- handlers.push(on$1('DOMContentLoaded', () => {
4211
+ handlers.push(on('DOMContentLoaded', () => {
4170
4212
  wrappedEmit(wrapEvent({
4171
4213
  type: EventType.DomContentLoaded,
4172
4214
  data: {},
@@ -4269,7 +4311,7 @@ function record(options = {}) {
4269
4311
  init();
4270
4312
  }
4271
4313
  else {
4272
- handlers.push(on$1('load', () => {
4314
+ handlers.push(on('load', () => {
4273
4315
  wrappedEmit(wrapEvent({
4274
4316
  type: EventType.Load,
4275
4317
  data: {},
@@ -4309,2250 +4351,334 @@ record.takeFullSnapshot = (isCheckout) => {
4309
4351
  };
4310
4352
  record.mirror = mirror;
4311
4353
 
4312
- /**
4313
- * URL parser.
4314
- *
4315
- * @param uri - url
4316
- * @param path - the request path of the connection
4317
- * @param loc - An object meant to mimic window.location.
4318
- * Defaults to window.location.
4319
- * @public
4320
- */
4321
- function url(uri, path = "", loc) {
4322
- let obj = uri;
4323
- // default to window.location
4324
- loc = loc || (typeof location !== "undefined" && location);
4325
- if (null == uri)
4326
- uri = loc.protocol + "//" + loc.host;
4327
- // relative path support
4328
- if (typeof uri === "string") {
4329
- if ("/" === uri.charAt(0)) {
4330
- if ("/" === uri.charAt(1)) {
4331
- uri = loc.protocol + uri;
4332
- }
4333
- else {
4334
- uri = loc.host + uri;
4335
- }
4336
- }
4337
- if (!/^(https?|wss?):\/\//.test(uri)) {
4338
- if ("undefined" !== typeof loc) {
4339
- uri = loc.protocol + "//" + uri;
4340
- }
4341
- else {
4342
- uri = "https://" + uri;
4343
- }
4344
- }
4345
- // parse
4346
- obj = parse(uri);
4347
- }
4348
- // make sure we treat `localhost:80` and `localhost` equally
4349
- if (!obj.port) {
4350
- if (/^(http|ws)$/.test(obj.protocol)) {
4351
- obj.port = "80";
4352
- }
4353
- else if (/^(http|ws)s$/.test(obj.protocol)) {
4354
- obj.port = "443";
4355
- }
4356
- }
4357
- obj.path = obj.path || "/";
4358
- const ipv6 = obj.host.indexOf(":") !== -1;
4359
- const host = ipv6 ? "[" + obj.host + "]" : obj.host;
4360
- // define unique id
4361
- obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
4362
- // define href
4363
- obj.href =
4364
- obj.protocol +
4365
- "://" +
4366
- host +
4367
- (loc && loc.port === obj.port ? "" : ":" + obj.port);
4368
- return obj;
4369
- }
4370
-
4371
- /**
4372
- * Initialize a new `Emitter`.
4373
- *
4374
- * @api public
4375
- */
4376
-
4377
- function Emitter(obj) {
4378
- if (obj) return mixin(obj);
4379
- }
4380
-
4381
- /**
4382
- * Mixin the emitter properties.
4383
- *
4384
- * @param {Object} obj
4385
- * @return {Object}
4386
- * @api private
4387
- */
4388
-
4389
- function mixin(obj) {
4390
- for (var key in Emitter.prototype) {
4391
- obj[key] = Emitter.prototype[key];
4354
+ var ANON_ID_KEY = 'co_anon_id';
4355
+ var SESSION_ID_KEY = 'co_session_id';
4356
+ function getAnonymousId() {
4357
+ var id = localStorage.getItem(ANON_ID_KEY);
4358
+ if (!id) {
4359
+ id = v4();
4360
+ localStorage.setItem(ANON_ID_KEY, id);
4392
4361
  }
4393
- return obj;
4362
+ return id;
4394
4363
  }
4395
-
4396
- /**
4397
- * Listen on the given `event` with `fn`.
4398
- *
4399
- * @param {String} event
4400
- * @param {Function} fn
4401
- * @return {Emitter}
4402
- * @api public
4403
- */
4404
-
4405
- Emitter.prototype.on =
4406
- Emitter.prototype.addEventListener = function(event, fn){
4407
- this._callbacks = this._callbacks || {};
4408
- (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
4409
- .push(fn);
4410
- return this;
4411
- };
4412
-
4413
- /**
4414
- * Adds an `event` listener that will be invoked a single
4415
- * time then automatically removed.
4416
- *
4417
- * @param {String} event
4418
- * @param {Function} fn
4419
- * @return {Emitter}
4420
- * @api public
4421
- */
4422
-
4423
- Emitter.prototype.once = function(event, fn){
4424
- function on() {
4425
- this.off(event, on);
4426
- fn.apply(this, arguments);
4364
+ function getSessionId() {
4365
+ var id = sessionStorage.getItem(SESSION_ID_KEY);
4366
+ if (!id) {
4367
+ id = v4();
4368
+ sessionStorage.setItem(SESSION_ID_KEY, id);
4427
4369
  }
4428
-
4429
- on.fn = fn;
4430
- this.on(event, on);
4431
- return this;
4432
- };
4433
-
4434
- /**
4435
- * Remove the given callback for `event` or all
4436
- * registered callbacks.
4437
- *
4438
- * @param {String} event
4439
- * @param {Function} fn
4440
- * @return {Emitter}
4441
- * @api public
4442
- */
4443
-
4444
- Emitter.prototype.off =
4445
- Emitter.prototype.removeListener =
4446
- Emitter.prototype.removeAllListeners =
4447
- Emitter.prototype.removeEventListener = function(event, fn){
4448
- this._callbacks = this._callbacks || {};
4449
-
4450
- // all
4451
- if (0 == arguments.length) {
4452
- this._callbacks = {};
4453
- return this;
4454
- }
4455
-
4456
- // specific event
4457
- var callbacks = this._callbacks['$' + event];
4458
- if (!callbacks) return this;
4459
-
4460
- // remove all handlers
4461
- if (1 == arguments.length) {
4462
- delete this._callbacks['$' + event];
4463
- return this;
4464
- }
4465
-
4466
- // remove specific handler
4467
- var cb;
4468
- for (var i = 0; i < callbacks.length; i++) {
4469
- cb = callbacks[i];
4470
- if (cb === fn || cb.fn === fn) {
4471
- callbacks.splice(i, 1);
4472
- break;
4473
- }
4474
- }
4475
-
4476
- // Remove event specific arrays for event types that no
4477
- // one is subscribed for to avoid memory leak.
4478
- if (callbacks.length === 0) {
4479
- delete this._callbacks['$' + event];
4480
- }
4481
-
4482
- return this;
4483
- };
4484
-
4485
- /**
4486
- * Emit `event` with the given args.
4487
- *
4488
- * @param {String} event
4489
- * @param {Mixed} ...
4490
- * @return {Emitter}
4491
- */
4492
-
4493
- Emitter.prototype.emit = function(event){
4494
- this._callbacks = this._callbacks || {};
4495
-
4496
- var args = new Array(arguments.length - 1)
4497
- , callbacks = this._callbacks['$' + event];
4498
-
4499
- for (var i = 1; i < arguments.length; i++) {
4500
- args[i - 1] = arguments[i];
4501
- }
4502
-
4503
- if (callbacks) {
4504
- callbacks = callbacks.slice(0);
4505
- for (var i = 0, len = callbacks.length; i < len; ++i) {
4506
- callbacks[i].apply(this, args);
4507
- }
4508
- }
4509
-
4510
- return this;
4511
- };
4512
-
4513
- // alias used for reserved events (protected method)
4514
- Emitter.prototype.emitReserved = Emitter.prototype.emit;
4515
-
4516
- /**
4517
- * Return array of callbacks for `event`.
4518
- *
4519
- * @param {String} event
4520
- * @return {Array}
4521
- * @api public
4522
- */
4523
-
4524
- Emitter.prototype.listeners = function(event){
4525
- this._callbacks = this._callbacks || {};
4526
- return this._callbacks['$' + event] || [];
4527
- };
4528
-
4529
- /**
4530
- * Check if this emitter has `event` handlers.
4531
- *
4532
- * @param {String} event
4533
- * @return {Boolean}
4534
- * @api public
4535
- */
4536
-
4537
- Emitter.prototype.hasListeners = function(event){
4538
- return !! this.listeners(event).length;
4539
- };
4540
-
4541
- const withNativeArrayBuffer = typeof ArrayBuffer === "function";
4542
- const isView = (obj) => {
4543
- return typeof ArrayBuffer.isView === "function"
4544
- ? ArrayBuffer.isView(obj)
4545
- : obj.buffer instanceof ArrayBuffer;
4546
- };
4547
- const toString = Object.prototype.toString;
4548
- const withNativeBlob = typeof Blob === "function" ||
4549
- (typeof Blob !== "undefined" &&
4550
- toString.call(Blob) === "[object BlobConstructor]");
4551
- const withNativeFile = typeof File === "function" ||
4552
- (typeof File !== "undefined" &&
4553
- toString.call(File) === "[object FileConstructor]");
4554
- /**
4555
- * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
4556
- *
4557
- * @private
4558
- */
4559
- function isBinary(obj) {
4560
- return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||
4561
- (withNativeBlob && obj instanceof Blob) ||
4562
- (withNativeFile && obj instanceof File));
4370
+ return id;
4563
4371
  }
4564
- function hasBinary(obj, toJSON) {
4565
- if (!obj || typeof obj !== "object") {
4566
- return false;
4567
- }
4568
- if (Array.isArray(obj)) {
4569
- for (let i = 0, l = obj.length; i < l; i++) {
4570
- if (hasBinary(obj[i])) {
4571
- return true;
4572
- }
4573
- }
4574
- return false;
4575
- }
4576
- if (isBinary(obj)) {
4577
- return true;
4578
- }
4579
- if (obj.toJSON &&
4580
- typeof obj.toJSON === "function" &&
4581
- arguments.length === 1) {
4582
- return hasBinary(obj.toJSON(), true);
4583
- }
4584
- for (const key in obj) {
4585
- if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
4586
- return true;
4587
- }
4588
- }
4589
- return false;
4372
+ function getUtmParams() {
4373
+ var params = new URLSearchParams(window.location.search);
4374
+ return {
4375
+ utm_source: params.get('utm_source') || undefined,
4376
+ utm_medium: params.get('utm_medium') || undefined,
4377
+ utm_campaign: params.get('utm_campaign') || undefined,
4378
+ utm_term: params.get('utm_term') || undefined,
4379
+ utm_content: params.get('utm_content') || undefined
4380
+ };
4590
4381
  }
4591
-
4592
- /**
4593
- * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
4594
- *
4595
- * @param {Object} packet - socket.io event packet
4596
- * @return {Object} with deconstructed packet and list of buffers
4597
- * @public
4598
- */
4599
- function deconstructPacket(packet) {
4600
- const buffers = [];
4601
- const packetData = packet.data;
4602
- const pack = packet;
4603
- pack.data = _deconstructPacket(packetData, buffers);
4604
- pack.attachments = buffers.length; // number of binary 'attachments'
4605
- return { packet: pack, buffers: buffers };
4382
+ function detectDeviceType() {
4383
+ var ua = navigator.userAgent;
4384
+ if (/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua)) {
4385
+ if (/iPad|Tablet/i.test(ua)) return 'tablet';
4386
+ return 'mobile';
4387
+ }
4388
+ return 'desktop';
4606
4389
  }
4607
- function _deconstructPacket(data, buffers) {
4608
- if (!data)
4609
- return data;
4610
- if (isBinary(data)) {
4611
- const placeholder = { _placeholder: true, num: buffers.length };
4612
- buffers.push(data);
4613
- return placeholder;
4614
- }
4615
- else if (Array.isArray(data)) {
4616
- const newData = new Array(data.length);
4617
- for (let i = 0; i < data.length; i++) {
4618
- newData[i] = _deconstructPacket(data[i], buffers);
4619
- }
4620
- return newData;
4621
- }
4622
- else if (typeof data === "object" && !(data instanceof Date)) {
4623
- const newData = {};
4624
- for (const key in data) {
4625
- if (Object.prototype.hasOwnProperty.call(data, key)) {
4626
- newData[key] = _deconstructPacket(data[key], buffers);
4627
- }
4628
- }
4629
- return newData;
4630
- }
4631
- return data;
4390
+ function detectOS() {
4391
+ var ua = navigator.userAgent;
4392
+ if (/iPhone|iPad|iPod/i.test(ua)) return 'iOS';
4393
+ if (/Android/i.test(ua)) return 'Android';
4394
+ if (/Win/i.test(ua)) return 'Windows';
4395
+ if (/Mac/i.test(ua)) return 'macOS';
4396
+ if (/Linux/i.test(ua)) return 'Linux';
4397
+ return 'Other';
4632
4398
  }
4633
- /**
4634
- * Reconstructs a binary packet from its placeholder packet and buffers
4635
- *
4636
- * @param {Object} packet - event packet with placeholders
4637
- * @param {Array} buffers - binary buffers to put in placeholder positions
4638
- * @return {Object} reconstructed packet
4639
- * @public
4640
- */
4641
- function reconstructPacket(packet, buffers) {
4642
- packet.data = _reconstructPacket(packet.data, buffers);
4643
- delete packet.attachments; // no longer useful
4644
- return packet;
4399
+ function getBrowserName() {
4400
+ var ua = navigator.userAgent;
4401
+ if (ua.indexOf('Firefox') > -1) return 'Firefox';
4402
+ if (ua.indexOf('Opera') > -1 || ua.indexOf('OPR') > -1) return 'Opera';
4403
+ if (ua.indexOf('Chrome') > -1) return 'Chrome';
4404
+ if (ua.indexOf('Safari') > -1) return 'Safari';
4405
+ if (ua.indexOf('MSIE') > -1 || ua.indexOf('Trident/') > -1) return 'IE';
4406
+ return 'Unknown';
4645
4407
  }
4646
- function _reconstructPacket(data, buffers) {
4647
- if (!data)
4648
- return data;
4649
- if (data && data._placeholder === true) {
4650
- const isIndexValid = typeof data.num === "number" &&
4651
- data.num >= 0 &&
4652
- data.num < buffers.length;
4653
- if (isIndexValid) {
4654
- return buffers[data.num]; // appropriate buffer (should be natural order anyway)
4655
- }
4656
- else {
4657
- throw new Error("illegal attachments");
4658
- }
4659
- }
4660
- else if (Array.isArray(data)) {
4661
- for (let i = 0; i < data.length; i++) {
4662
- data[i] = _reconstructPacket(data[i], buffers);
4663
- }
4664
- }
4665
- else if (typeof data === "object") {
4666
- for (const key in data) {
4667
- if (Object.prototype.hasOwnProperty.call(data, key)) {
4668
- data[key] = _reconstructPacket(data[key], buffers);
4669
- }
4670
- }
4671
- }
4672
- return data;
4408
+ function getPagePath() {
4409
+ return window.location.pathname;
4673
4410
  }
4674
4411
 
4675
- /**
4676
- * These strings must not be used as event names, as they have a special meaning.
4677
- */
4678
- const RESERVED_EVENTS$1 = [
4679
- "connect",
4680
- "connect_error",
4681
- "disconnect",
4682
- "disconnecting",
4683
- "newListener",
4684
- "removeListener", // used by the Node.js EventEmitter
4685
- ];
4686
- /**
4687
- * Protocol version.
4688
- *
4689
- * @public
4690
- */
4691
- const protocol = 5;
4692
- var PacketType;
4693
- (function (PacketType) {
4694
- PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
4695
- PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
4696
- PacketType[PacketType["EVENT"] = 2] = "EVENT";
4697
- PacketType[PacketType["ACK"] = 3] = "ACK";
4698
- PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
4699
- PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
4700
- PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
4701
- })(PacketType || (PacketType = {}));
4702
- /**
4703
- * A socket.io Encoder instance
4704
- */
4705
- class Encoder {
4706
- /**
4707
- * Encoder constructor
4708
- *
4709
- * @param {function} replacer - custom replacer to pass down to JSON.parse
4710
- */
4711
- constructor(replacer) {
4712
- this.replacer = replacer;
4713
- }
4714
- /**
4715
- * Encode a packet as a single string if non-binary, or as a
4716
- * buffer sequence, depending on packet type.
4717
- *
4718
- * @param {Object} obj - packet object
4719
- */
4720
- encode(obj) {
4721
- if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
4722
- if (hasBinary(obj)) {
4723
- return this.encodeAsBinary({
4724
- type: obj.type === PacketType.EVENT
4725
- ? PacketType.BINARY_EVENT
4726
- : PacketType.BINARY_ACK,
4727
- nsp: obj.nsp,
4728
- data: obj.data,
4729
- id: obj.id,
4730
- });
4731
- }
4732
- }
4733
- return [this.encodeAsString(obj)];
4734
- }
4735
- /**
4736
- * Encode packet as string.
4737
- */
4738
- encodeAsString(obj) {
4739
- // first is type
4740
- let str = "" + obj.type;
4741
- // attachments if we have them
4742
- if (obj.type === PacketType.BINARY_EVENT ||
4743
- obj.type === PacketType.BINARY_ACK) {
4744
- str += obj.attachments + "-";
4745
- }
4746
- // if we have a namespace other than `/`
4747
- // we append it followed by a comma `,`
4748
- if (obj.nsp && "/" !== obj.nsp) {
4749
- str += obj.nsp + ",";
4750
- }
4751
- // immediately followed by the id
4752
- if (null != obj.id) {
4753
- str += obj.id;
4754
- }
4755
- // json data
4756
- if (null != obj.data) {
4757
- str += JSON.stringify(obj.data, this.replacer);
4758
- }
4759
- return str;
4760
- }
4761
- /**
4762
- * Encode packet as 'buffer sequence' by removing blobs, and
4763
- * deconstructing packet into object with placeholders and
4764
- * a list of buffers.
4765
- */
4766
- encodeAsBinary(obj) {
4767
- const deconstruction = deconstructPacket(obj);
4768
- const pack = this.encodeAsString(deconstruction.packet);
4769
- const buffers = deconstruction.buffers;
4770
- buffers.unshift(pack); // add packet info to beginning of data list
4771
- return buffers; // write all the buffers
4772
- }
4773
- }
4774
- // see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
4775
- function isObject(value) {
4776
- return Object.prototype.toString.call(value) === "[object Object]";
4777
- }
4778
- /**
4779
- * A socket.io Decoder instance
4780
- *
4781
- * @return {Object} decoder
4782
- */
4783
- class Decoder extends Emitter {
4784
- /**
4785
- * Decoder constructor
4786
- *
4787
- * @param {function} reviver - custom reviver to pass down to JSON.stringify
4788
- */
4789
- constructor(reviver) {
4790
- super();
4791
- this.reviver = reviver;
4792
- }
4793
- /**
4794
- * Decodes an encoded packet string into packet JSON.
4795
- *
4796
- * @param {String} obj - encoded packet
4797
- */
4798
- add(obj) {
4799
- let packet;
4800
- if (typeof obj === "string") {
4801
- if (this.reconstructor) {
4802
- throw new Error("got plaintext data when reconstructing a packet");
4803
- }
4804
- packet = this.decodeString(obj);
4805
- const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
4806
- if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
4807
- packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
4808
- // binary packet's json
4809
- this.reconstructor = new BinaryReconstructor(packet);
4810
- // no attachments, labeled binary but no binary data to follow
4811
- if (packet.attachments === 0) {
4812
- super.emitReserved("decoded", packet);
4813
- }
4814
- }
4815
- else {
4816
- // non-binary full packet
4817
- super.emitReserved("decoded", packet);
4818
- }
4819
- }
4820
- else if (isBinary(obj) || obj.base64) {
4821
- // raw binary data
4822
- if (!this.reconstructor) {
4823
- throw new Error("got binary data when not reconstructing a packet");
4824
- }
4825
- else {
4826
- packet = this.reconstructor.takeBinaryData(obj);
4827
- if (packet) {
4828
- // received final buffer
4829
- this.reconstructor = null;
4830
- super.emitReserved("decoded", packet);
4831
- }
4832
- }
4833
- }
4834
- else {
4835
- throw new Error("Unknown type: " + obj);
4836
- }
4837
- }
4838
- /**
4839
- * Decode a packet String (JSON data)
4840
- *
4841
- * @param {String} str
4842
- * @return {Object} packet
4843
- */
4844
- decodeString(str) {
4845
- let i = 0;
4846
- // look up type
4847
- const p = {
4848
- type: Number(str.charAt(0)),
4849
- };
4850
- if (PacketType[p.type] === undefined) {
4851
- throw new Error("unknown packet type " + p.type);
4852
- }
4853
- // look up attachments if type binary
4854
- if (p.type === PacketType.BINARY_EVENT ||
4855
- p.type === PacketType.BINARY_ACK) {
4856
- const start = i + 1;
4857
- while (str.charAt(++i) !== "-" && i != str.length) { }
4858
- const buf = str.substring(start, i);
4859
- if (buf != Number(buf) || str.charAt(i) !== "-") {
4860
- throw new Error("Illegal attachments");
4861
- }
4862
- p.attachments = Number(buf);
4863
- }
4864
- // look up namespace (if any)
4865
- if ("/" === str.charAt(i + 1)) {
4866
- const start = i + 1;
4867
- while (++i) {
4868
- const c = str.charAt(i);
4869
- if ("," === c)
4870
- break;
4871
- if (i === str.length)
4872
- break;
4873
- }
4874
- p.nsp = str.substring(start, i);
4875
- }
4876
- else {
4877
- p.nsp = "/";
4878
- }
4879
- // look up id
4880
- const next = str.charAt(i + 1);
4881
- if ("" !== next && Number(next) == next) {
4882
- const start = i + 1;
4883
- while (++i) {
4884
- const c = str.charAt(i);
4885
- if (null == c || Number(c) != c) {
4886
- --i;
4887
- break;
4888
- }
4889
- if (i === str.length)
4890
- break;
4891
- }
4892
- p.id = Number(str.substring(start, i + 1));
4893
- }
4894
- // look up json data
4895
- if (str.charAt(++i)) {
4896
- const payload = this.tryParse(str.substr(i));
4897
- if (Decoder.isPayloadValid(p.type, payload)) {
4898
- p.data = payload;
4899
- }
4900
- else {
4901
- throw new Error("invalid payload");
4902
- }
4903
- }
4904
- return p;
4905
- }
4906
- tryParse(str) {
4907
- try {
4908
- return JSON.parse(str, this.reviver);
4909
- }
4910
- catch (e) {
4911
- return false;
4912
- }
4913
- }
4914
- static isPayloadValid(type, payload) {
4915
- switch (type) {
4916
- case PacketType.CONNECT:
4917
- return isObject(payload);
4918
- case PacketType.DISCONNECT:
4919
- return payload === undefined;
4920
- case PacketType.CONNECT_ERROR:
4921
- return typeof payload === "string" || isObject(payload);
4922
- case PacketType.EVENT:
4923
- case PacketType.BINARY_EVENT:
4924
- return (Array.isArray(payload) &&
4925
- (typeof payload[0] === "number" ||
4926
- (typeof payload[0] === "string" &&
4927
- RESERVED_EVENTS$1.indexOf(payload[0]) === -1)));
4928
- case PacketType.ACK:
4929
- case PacketType.BINARY_ACK:
4930
- return Array.isArray(payload);
4931
- }
4932
- }
4933
- /**
4934
- * Deallocates a parser's resources
4935
- */
4936
- destroy() {
4937
- if (this.reconstructor) {
4938
- this.reconstructor.finishedReconstruction();
4939
- this.reconstructor = null;
4940
- }
4941
- }
4412
+ var INGEST_BASE = 'https://atlas-orchestrator.atlas.coreoutline.com';
4413
+ var FLUSH_INTERVAL_MS = 5000;
4414
+ var _token = null;
4415
+ var _warehouseId = null;
4416
+ var _organizationId = null;
4417
+ var _dataSourceId = null;
4418
+ var _buffer = [];
4419
+ var _flushInterval = null;
4420
+ function initIngest(_x, _x2, _x3) {
4421
+ return _initIngest.apply(this, arguments);
4942
4422
  }
4943
- /**
4944
- * A manager of a binary event's 'buffer sequence'. Should
4945
- * be constructed whenever a packet of type BINARY_EVENT is
4946
- * decoded.
4947
- *
4948
- * @param {Object} packet
4949
- * @return {BinaryReconstructor} initialized reconstructor
4950
- */
4951
- class BinaryReconstructor {
4952
- constructor(packet) {
4953
- this.packet = packet;
4954
- this.buffers = [];
4955
- this.reconPack = packet;
4956
- }
4957
- /**
4958
- * Method to be called when binary data received from connection
4959
- * after a BINARY_EVENT packet.
4960
- *
4961
- * @param {Buffer | ArrayBuffer} binData - the raw binary data received
4962
- * @return {null | Object} returns null if more binary data is expected or
4963
- * a reconstructed packet object if all buffers have been received.
4964
- */
4965
- takeBinaryData(binData) {
4966
- this.buffers.push(binData);
4967
- if (this.buffers.length === this.reconPack.attachments) {
4968
- // done with buffer list
4969
- const packet = reconstructPacket(this.reconPack, this.buffers);
4970
- this.finishedReconstruction();
4971
- return packet;
4972
- }
4973
- return null;
4974
- }
4975
- /**
4976
- * Cleans up binary packet reconstruction variables.
4977
- */
4978
- finishedReconstruction() {
4979
- this.reconPack = null;
4980
- this.buffers = [];
4981
- }
4423
+ function _initIngest() {
4424
+ _initIngest = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(warehouseId, dataSourceId, dataSourceSecret) {
4425
+ var res, data;
4426
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
4427
+ while (1) switch (_context.prev = _context.next) {
4428
+ case 0:
4429
+ _warehouseId = warehouseId;
4430
+ _dataSourceId = dataSourceId;
4431
+ _context.prev = 2;
4432
+ _context.next = 5;
4433
+ return fetch("".concat(INGEST_BASE, "/api/ingest/authorize"), {
4434
+ method: 'POST',
4435
+ headers: {
4436
+ 'Content-Type': 'application/json'
4437
+ },
4438
+ body: JSON.stringify({
4439
+ warehouse_id: warehouseId,
4440
+ data_source_id: dataSourceId,
4441
+ data_source_secret: dataSourceSecret
4442
+ })
4443
+ });
4444
+ case 5:
4445
+ res = _context.sent;
4446
+ if (res.ok) {
4447
+ _context.next = 9;
4448
+ break;
4449
+ }
4450
+ console.error('[CoreOutline] Authorization failed:', res.status);
4451
+ return _context.abrupt("return", false);
4452
+ case 9:
4453
+ _context.next = 11;
4454
+ return res.json();
4455
+ case 11:
4456
+ data = _context.sent;
4457
+ _token = data.access_token;
4458
+ _organizationId = data.organization_id;
4459
+ return _context.abrupt("return", true);
4460
+ case 17:
4461
+ _context.prev = 17;
4462
+ _context.t0 = _context["catch"](2);
4463
+ console.error('[CoreOutline] Authorization error:', _context.t0);
4464
+ return _context.abrupt("return", false);
4465
+ case 21:
4466
+ case "end":
4467
+ return _context.stop();
4468
+ }
4469
+ }, _callee, null, [[2, 17]]);
4470
+ }));
4471
+ return _initIngest.apply(this, arguments);
4982
4472
  }
4983
-
4984
- var parser = /*#__PURE__*/Object.freeze({
4985
- __proto__: null,
4986
- protocol: protocol,
4987
- get PacketType () { return PacketType; },
4988
- Encoder: Encoder,
4989
- Decoder: Decoder
4990
- });
4991
-
4992
- function on(obj, ev, fn) {
4993
- obj.on(ev, fn);
4994
- return function subDestroy() {
4995
- obj.off(ev, fn);
4996
- };
4473
+ function trackEvent(eventType, payload) {
4474
+ if (!_token) return;
4475
+ var event = _objectSpread2({
4476
+ event_id: v4(),
4477
+ event_type: eventType,
4478
+ event_ts: new Date().toISOString()
4479
+ }, payload);
4480
+ _buffer.push(event);
4481
+ if (!_flushInterval) {
4482
+ _flushInterval = setInterval(flush, FLUSH_INTERVAL_MS);
4483
+ }
4997
4484
  }
4998
-
4999
- /**
5000
- * Internal events.
5001
- * These events can't be emitted by the user.
5002
- */
5003
- const RESERVED_EVENTS = Object.freeze({
5004
- connect: 1,
5005
- connect_error: 1,
5006
- disconnect: 1,
5007
- disconnecting: 1,
5008
- // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
5009
- newListener: 1,
5010
- removeListener: 1,
5011
- });
5012
- /**
5013
- * A Socket is the fundamental class for interacting with the server.
5014
- *
5015
- * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
5016
- *
5017
- * @example
5018
- * const socket = io();
5019
- *
5020
- * socket.on("connect", () => {
5021
- * console.log("connected");
5022
- * });
5023
- *
5024
- * // send an event to the server
5025
- * socket.emit("foo", "bar");
5026
- *
5027
- * socket.on("foobar", () => {
5028
- * // an event was received from the server
5029
- * });
5030
- *
5031
- * // upon disconnection
5032
- * socket.on("disconnect", (reason) => {
5033
- * console.log(`disconnected due to ${reason}`);
5034
- * });
5035
- */
5036
- class Socket extends Emitter {
5037
- /**
5038
- * `Socket` constructor.
5039
- */
5040
- constructor(io, nsp, opts) {
5041
- super();
5042
- /**
5043
- * Whether the socket is currently connected to the server.
5044
- *
5045
- * @example
5046
- * const socket = io();
5047
- *
5048
- * socket.on("connect", () => {
5049
- * console.log(socket.connected); // true
5050
- * });
5051
- *
5052
- * socket.on("disconnect", () => {
5053
- * console.log(socket.connected); // false
5054
- * });
5055
- */
5056
- this.connected = false;
5057
- /**
5058
- * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
5059
- * be transmitted by the server.
5060
- */
5061
- this.recovered = false;
5062
- /**
5063
- * Buffer for packets received before the CONNECT packet
5064
- */
5065
- this.receiveBuffer = [];
5066
- /**
5067
- * Buffer for packets that will be sent once the socket is connected
5068
- */
5069
- this.sendBuffer = [];
5070
- /**
5071
- * The queue of packets to be sent with retry in case of failure.
5072
- *
5073
- * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
5074
- * @private
5075
- */
5076
- this._queue = [];
5077
- /**
5078
- * A sequence to generate the ID of the {@link QueuedPacket}.
5079
- * @private
5080
- */
5081
- this._queueSeq = 0;
5082
- this.ids = 0;
5083
- /**
5084
- * A map containing acknowledgement handlers.
5085
- *
5086
- * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
5087
- *
5088
- * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
5089
- * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
5090
- * - `const value = await socket.emitWithAck("test")`
5091
- *
5092
- * From those that don't:
5093
- *
5094
- * - `socket.emit("test", (value) => { ... });`
5095
- *
5096
- * In the first case, the handlers will be called with an error when:
5097
- *
5098
- * - the timeout is reached
5099
- * - the socket gets disconnected
5100
- *
5101
- * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
5102
- * an acknowledgement from the server.
5103
- *
5104
- * @private
5105
- */
5106
- this.acks = {};
5107
- this.flags = {};
5108
- this.io = io;
5109
- this.nsp = nsp;
5110
- if (opts && opts.auth) {
5111
- this.auth = opts.auth;
5112
- }
5113
- this._opts = Object.assign({}, opts);
5114
- if (this.io._autoConnect)
5115
- this.open();
5116
- }
5117
- /**
5118
- * Whether the socket is currently disconnected
5119
- *
5120
- * @example
5121
- * const socket = io();
5122
- *
5123
- * socket.on("connect", () => {
5124
- * console.log(socket.disconnected); // false
5125
- * });
5126
- *
5127
- * socket.on("disconnect", () => {
5128
- * console.log(socket.disconnected); // true
5129
- * });
5130
- */
5131
- get disconnected() {
5132
- return !this.connected;
5133
- }
5134
- /**
5135
- * Subscribe to open, close and packet events
5136
- *
5137
- * @private
5138
- */
5139
- subEvents() {
5140
- if (this.subs)
5141
- return;
5142
- const io = this.io;
5143
- this.subs = [
5144
- on(io, "open", this.onopen.bind(this)),
5145
- on(io, "packet", this.onpacket.bind(this)),
5146
- on(io, "error", this.onerror.bind(this)),
5147
- on(io, "close", this.onclose.bind(this)),
5148
- ];
5149
- }
5150
- /**
5151
- * Whether the Socket will try to reconnect when its Manager connects or reconnects.
5152
- *
5153
- * @example
5154
- * const socket = io();
5155
- *
5156
- * console.log(socket.active); // true
5157
- *
5158
- * socket.on("disconnect", (reason) => {
5159
- * if (reason === "io server disconnect") {
5160
- * // the disconnection was initiated by the server, you need to manually reconnect
5161
- * console.log(socket.active); // false
5162
- * }
5163
- * // else the socket will automatically try to reconnect
5164
- * console.log(socket.active); // true
5165
- * });
5166
- */
5167
- get active() {
5168
- return !!this.subs;
5169
- }
5170
- /**
5171
- * "Opens" the socket.
5172
- *
5173
- * @example
5174
- * const socket = io({
5175
- * autoConnect: false
5176
- * });
5177
- *
5178
- * socket.connect();
5179
- */
5180
- connect() {
5181
- if (this.connected)
5182
- return this;
5183
- this.subEvents();
5184
- if (!this.io["_reconnecting"])
5185
- this.io.open(); // ensure open
5186
- if ("open" === this.io._readyState)
5187
- this.onopen();
5188
- return this;
5189
- }
5190
- /**
5191
- * Alias for {@link connect()}.
5192
- */
5193
- open() {
5194
- return this.connect();
5195
- }
5196
- /**
5197
- * Sends a `message` event.
5198
- *
5199
- * This method mimics the WebSocket.send() method.
5200
- *
5201
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
5202
- *
5203
- * @example
5204
- * socket.send("hello");
5205
- *
5206
- * // this is equivalent to
5207
- * socket.emit("message", "hello");
5208
- *
5209
- * @return self
5210
- */
5211
- send(...args) {
5212
- args.unshift("message");
5213
- this.emit.apply(this, args);
5214
- return this;
5215
- }
5216
- /**
5217
- * Override `emit`.
5218
- * If the event is in `events`, it's emitted normally.
5219
- *
5220
- * @example
5221
- * socket.emit("hello", "world");
5222
- *
5223
- * // all serializable datastructures are supported (no need to call JSON.stringify)
5224
- * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
5225
- *
5226
- * // with an acknowledgement from the server
5227
- * socket.emit("hello", "world", (val) => {
5228
- * // ...
5229
- * });
5230
- *
5231
- * @return self
5232
- */
5233
- emit(ev, ...args) {
5234
- var _a, _b, _c;
5235
- if (RESERVED_EVENTS.hasOwnProperty(ev)) {
5236
- throw new Error('"' + ev.toString() + '" is a reserved event name');
5237
- }
5238
- args.unshift(ev);
5239
- if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
5240
- this._addToQueue(args);
5241
- return this;
5242
- }
5243
- const packet = {
5244
- type: PacketType.EVENT,
5245
- data: args,
5246
- };
5247
- packet.options = {};
5248
- packet.options.compress = this.flags.compress !== false;
5249
- // event ack callback
5250
- if ("function" === typeof args[args.length - 1]) {
5251
- const id = this.ids++;
5252
- const ack = args.pop();
5253
- this._registerAckCallback(id, ack);
5254
- packet.id = id;
5255
- }
5256
- const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
5257
- const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
5258
- const discardPacket = this.flags.volatile && !isTransportWritable;
5259
- if (discardPacket) ;
5260
- else if (isConnected) {
5261
- this.notifyOutgoingListeners(packet);
5262
- this.packet(packet);
5263
- }
5264
- else {
5265
- this.sendBuffer.push(packet);
5266
- }
5267
- this.flags = {};
5268
- return this;
5269
- }
5270
- /**
5271
- * @private
5272
- */
5273
- _registerAckCallback(id, ack) {
5274
- var _a;
5275
- const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
5276
- if (timeout === undefined) {
5277
- this.acks[id] = ack;
5278
- return;
5279
- }
5280
- // @ts-ignore
5281
- const timer = this.io.setTimeoutFn(() => {
5282
- delete this.acks[id];
5283
- for (let i = 0; i < this.sendBuffer.length; i++) {
5284
- if (this.sendBuffer[i].id === id) {
5285
- this.sendBuffer.splice(i, 1);
5286
- }
5287
- }
5288
- ack.call(this, new Error("operation has timed out"));
5289
- }, timeout);
5290
- const fn = (...args) => {
5291
- // @ts-ignore
5292
- this.io.clearTimeoutFn(timer);
5293
- ack.apply(this, args);
5294
- };
5295
- fn.withError = true;
5296
- this.acks[id] = fn;
5297
- }
5298
- /**
5299
- * Emits an event and waits for an acknowledgement
5300
- *
5301
- * @example
5302
- * // without timeout
5303
- * const response = await socket.emitWithAck("hello", "world");
5304
- *
5305
- * // with a specific timeout
5306
- * try {
5307
- * const response = await socket.timeout(1000).emitWithAck("hello", "world");
5308
- * } catch (err) {
5309
- * // the server did not acknowledge the event in the given delay
5310
- * }
5311
- *
5312
- * @return a Promise that will be fulfilled when the server acknowledges the event
5313
- */
5314
- emitWithAck(ev, ...args) {
5315
- return new Promise((resolve, reject) => {
5316
- const fn = (arg1, arg2) => {
5317
- return arg1 ? reject(arg1) : resolve(arg2);
5318
- };
5319
- fn.withError = true;
5320
- args.push(fn);
5321
- this.emit(ev, ...args);
5322
- });
5323
- }
5324
- /**
5325
- * Add the packet to the queue.
5326
- * @param args
5327
- * @private
5328
- */
5329
- _addToQueue(args) {
5330
- let ack;
5331
- if (typeof args[args.length - 1] === "function") {
5332
- ack = args.pop();
5333
- }
5334
- const packet = {
5335
- id: this._queueSeq++,
5336
- tryCount: 0,
5337
- pending: false,
5338
- args,
5339
- flags: Object.assign({ fromQueue: true }, this.flags),
5340
- };
5341
- args.push((err, ...responseArgs) => {
5342
- if (packet !== this._queue[0]) {
5343
- // the packet has already been acknowledged
5344
- return;
5345
- }
5346
- const hasError = err !== null;
5347
- if (hasError) {
5348
- if (packet.tryCount > this._opts.retries) {
5349
- this._queue.shift();
5350
- if (ack) {
5351
- ack(err);
5352
- }
5353
- }
5354
- }
5355
- else {
5356
- this._queue.shift();
5357
- if (ack) {
5358
- ack(null, ...responseArgs);
5359
- }
5360
- }
5361
- packet.pending = false;
5362
- return this._drainQueue();
5363
- });
5364
- this._queue.push(packet);
5365
- this._drainQueue();
5366
- }
5367
- /**
5368
- * Send the first packet of the queue, and wait for an acknowledgement from the server.
5369
- * @param force - whether to resend a packet that has not been acknowledged yet
5370
- *
5371
- * @private
5372
- */
5373
- _drainQueue(force = false) {
5374
- if (!this.connected || this._queue.length === 0) {
5375
- return;
5376
- }
5377
- const packet = this._queue[0];
5378
- if (packet.pending && !force) {
5379
- return;
5380
- }
5381
- packet.pending = true;
5382
- packet.tryCount++;
5383
- this.flags = packet.flags;
5384
- this.emit.apply(this, packet.args);
5385
- }
5386
- /**
5387
- * Sends a packet.
5388
- *
5389
- * @param packet
5390
- * @private
5391
- */
5392
- packet(packet) {
5393
- packet.nsp = this.nsp;
5394
- this.io._packet(packet);
5395
- }
5396
- /**
5397
- * Called upon engine `open`.
5398
- *
5399
- * @private
5400
- */
5401
- onopen() {
5402
- if (typeof this.auth == "function") {
5403
- this.auth((data) => {
5404
- this._sendConnectPacket(data);
5405
- });
5406
- }
5407
- else {
5408
- this._sendConnectPacket(this.auth);
5409
- }
5410
- }
5411
- /**
5412
- * Sends a CONNECT packet to initiate the Socket.IO session.
5413
- *
5414
- * @param data
5415
- * @private
5416
- */
5417
- _sendConnectPacket(data) {
5418
- this.packet({
5419
- type: PacketType.CONNECT,
5420
- data: this._pid
5421
- ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
5422
- : data,
5423
- });
5424
- }
5425
- /**
5426
- * Called upon engine or manager `error`.
5427
- *
5428
- * @param err
5429
- * @private
5430
- */
5431
- onerror(err) {
5432
- if (!this.connected) {
5433
- this.emitReserved("connect_error", err);
5434
- }
5435
- }
5436
- /**
5437
- * Called upon engine `close`.
5438
- *
5439
- * @param reason
5440
- * @param description
5441
- * @private
5442
- */
5443
- onclose(reason, description) {
5444
- this.connected = false;
5445
- delete this.id;
5446
- this.emitReserved("disconnect", reason, description);
5447
- this._clearAcks();
5448
- }
5449
- /**
5450
- * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
5451
- * the server.
5452
- *
5453
- * @private
5454
- */
5455
- _clearAcks() {
5456
- Object.keys(this.acks).forEach((id) => {
5457
- const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
5458
- if (!isBuffered) {
5459
- // note: handlers that do not accept an error as first argument are ignored here
5460
- const ack = this.acks[id];
5461
- delete this.acks[id];
5462
- if (ack.withError) {
5463
- ack.call(this, new Error("socket has been disconnected"));
5464
- }
5465
- }
5466
- });
5467
- }
5468
- /**
5469
- * Called with socket packet.
5470
- *
5471
- * @param packet
5472
- * @private
5473
- */
5474
- onpacket(packet) {
5475
- const sameNamespace = packet.nsp === this.nsp;
5476
- if (!sameNamespace)
5477
- return;
5478
- switch (packet.type) {
5479
- case PacketType.CONNECT:
5480
- if (packet.data && packet.data.sid) {
5481
- this.onconnect(packet.data.sid, packet.data.pid);
5482
- }
5483
- else {
5484
- this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
5485
- }
5486
- break;
5487
- case PacketType.EVENT:
5488
- case PacketType.BINARY_EVENT:
5489
- this.onevent(packet);
5490
- break;
5491
- case PacketType.ACK:
5492
- case PacketType.BINARY_ACK:
5493
- this.onack(packet);
5494
- break;
5495
- case PacketType.DISCONNECT:
5496
- this.ondisconnect();
5497
- break;
5498
- case PacketType.CONNECT_ERROR:
5499
- this.destroy();
5500
- const err = new Error(packet.data.message);
5501
- // @ts-ignore
5502
- err.data = packet.data.data;
5503
- this.emitReserved("connect_error", err);
5504
- break;
5505
- }
5506
- }
5507
- /**
5508
- * Called upon a server event.
5509
- *
5510
- * @param packet
5511
- * @private
5512
- */
5513
- onevent(packet) {
5514
- const args = packet.data || [];
5515
- if (null != packet.id) {
5516
- args.push(this.ack(packet.id));
5517
- }
5518
- if (this.connected) {
5519
- this.emitEvent(args);
5520
- }
5521
- else {
5522
- this.receiveBuffer.push(Object.freeze(args));
5523
- }
5524
- }
5525
- emitEvent(args) {
5526
- if (this._anyListeners && this._anyListeners.length) {
5527
- const listeners = this._anyListeners.slice();
5528
- for (const listener of listeners) {
5529
- listener.apply(this, args);
5530
- }
5531
- }
5532
- super.emit.apply(this, args);
5533
- if (this._pid && args.length && typeof args[args.length - 1] === "string") {
5534
- this._lastOffset = args[args.length - 1];
5535
- }
5536
- }
5537
- /**
5538
- * Produces an ack callback to emit with an event.
5539
- *
5540
- * @private
5541
- */
5542
- ack(id) {
5543
- const self = this;
5544
- let sent = false;
5545
- return function (...args) {
5546
- // prevent double callbacks
5547
- if (sent)
5548
- return;
5549
- sent = true;
5550
- self.packet({
5551
- type: PacketType.ACK,
5552
- id: id,
5553
- data: args,
5554
- });
5555
- };
5556
- }
5557
- /**
5558
- * Called upon a server acknowledgement.
5559
- *
5560
- * @param packet
5561
- * @private
5562
- */
5563
- onack(packet) {
5564
- const ack = this.acks[packet.id];
5565
- if (typeof ack !== "function") {
5566
- return;
5567
- }
5568
- delete this.acks[packet.id];
5569
- // @ts-ignore FIXME ack is incorrectly inferred as 'never'
5570
- if (ack.withError) {
5571
- packet.data.unshift(null);
5572
- }
5573
- // @ts-ignore
5574
- ack.apply(this, packet.data);
5575
- }
5576
- /**
5577
- * Called upon server connect.
5578
- *
5579
- * @private
5580
- */
5581
- onconnect(id, pid) {
5582
- this.id = id;
5583
- this.recovered = pid && this._pid === pid;
5584
- this._pid = pid; // defined only if connection state recovery is enabled
5585
- this.connected = true;
5586
- this.emitBuffered();
5587
- this.emitReserved("connect");
5588
- this._drainQueue(true);
5589
- }
5590
- /**
5591
- * Emit buffered events (received and emitted).
5592
- *
5593
- * @private
5594
- */
5595
- emitBuffered() {
5596
- this.receiveBuffer.forEach((args) => this.emitEvent(args));
5597
- this.receiveBuffer = [];
5598
- this.sendBuffer.forEach((packet) => {
5599
- this.notifyOutgoingListeners(packet);
5600
- this.packet(packet);
5601
- });
5602
- this.sendBuffer = [];
5603
- }
5604
- /**
5605
- * Called upon server disconnect.
5606
- *
5607
- * @private
5608
- */
5609
- ondisconnect() {
5610
- this.destroy();
5611
- this.onclose("io server disconnect");
5612
- }
5613
- /**
5614
- * Called upon forced client/server side disconnections,
5615
- * this method ensures the manager stops tracking us and
5616
- * that reconnections don't get triggered for this.
5617
- *
5618
- * @private
5619
- */
5620
- destroy() {
5621
- if (this.subs) {
5622
- // clean subscriptions to avoid reconnections
5623
- this.subs.forEach((subDestroy) => subDestroy());
5624
- this.subs = undefined;
5625
- }
5626
- this.io["_destroy"](this);
5627
- }
5628
- /**
5629
- * Disconnects the socket manually. In that case, the socket will not try to reconnect.
5630
- *
5631
- * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
5632
- *
5633
- * @example
5634
- * const socket = io();
5635
- *
5636
- * socket.on("disconnect", (reason) => {
5637
- * // console.log(reason); prints "io client disconnect"
5638
- * });
5639
- *
5640
- * socket.disconnect();
5641
- *
5642
- * @return self
5643
- */
5644
- disconnect() {
5645
- if (this.connected) {
5646
- this.packet({ type: PacketType.DISCONNECT });
5647
- }
5648
- // remove socket from pool
5649
- this.destroy();
5650
- if (this.connected) {
5651
- // fire events
5652
- this.onclose("io client disconnect");
5653
- }
5654
- return this;
5655
- }
5656
- /**
5657
- * Alias for {@link disconnect()}.
5658
- *
5659
- * @return self
5660
- */
5661
- close() {
5662
- return this.disconnect();
5663
- }
5664
- /**
5665
- * Sets the compress flag.
5666
- *
5667
- * @example
5668
- * socket.compress(false).emit("hello");
5669
- *
5670
- * @param compress - if `true`, compresses the sending data
5671
- * @return self
5672
- */
5673
- compress(compress) {
5674
- this.flags.compress = compress;
5675
- return this;
5676
- }
5677
- /**
5678
- * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
5679
- * ready to send messages.
5680
- *
5681
- * @example
5682
- * socket.volatile.emit("hello"); // the server may or may not receive it
5683
- *
5684
- * @returns self
5685
- */
5686
- get volatile() {
5687
- this.flags.volatile = true;
5688
- return this;
5689
- }
5690
- /**
5691
- * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
5692
- * given number of milliseconds have elapsed without an acknowledgement from the server:
5693
- *
5694
- * @example
5695
- * socket.timeout(5000).emit("my-event", (err) => {
5696
- * if (err) {
5697
- * // the server did not acknowledge the event in the given delay
5698
- * }
5699
- * });
5700
- *
5701
- * @returns self
5702
- */
5703
- timeout(timeout) {
5704
- this.flags.timeout = timeout;
5705
- return this;
5706
- }
5707
- /**
5708
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
5709
- * callback.
5710
- *
5711
- * @example
5712
- * socket.onAny((event, ...args) => {
5713
- * console.log(`got ${event}`);
5714
- * });
5715
- *
5716
- * @param listener
5717
- */
5718
- onAny(listener) {
5719
- this._anyListeners = this._anyListeners || [];
5720
- this._anyListeners.push(listener);
5721
- return this;
5722
- }
5723
- /**
5724
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
5725
- * callback. The listener is added to the beginning of the listeners array.
5726
- *
5727
- * @example
5728
- * socket.prependAny((event, ...args) => {
5729
- * console.log(`got event ${event}`);
5730
- * });
5731
- *
5732
- * @param listener
5733
- */
5734
- prependAny(listener) {
5735
- this._anyListeners = this._anyListeners || [];
5736
- this._anyListeners.unshift(listener);
5737
- return this;
5738
- }
5739
- /**
5740
- * Removes the listener that will be fired when any event is emitted.
5741
- *
5742
- * @example
5743
- * const catchAllListener = (event, ...args) => {
5744
- * console.log(`got event ${event}`);
5745
- * }
5746
- *
5747
- * socket.onAny(catchAllListener);
5748
- *
5749
- * // remove a specific listener
5750
- * socket.offAny(catchAllListener);
5751
- *
5752
- * // or remove all listeners
5753
- * socket.offAny();
5754
- *
5755
- * @param listener
5756
- */
5757
- offAny(listener) {
5758
- if (!this._anyListeners) {
5759
- return this;
5760
- }
5761
- if (listener) {
5762
- const listeners = this._anyListeners;
5763
- for (let i = 0; i < listeners.length; i++) {
5764
- if (listener === listeners[i]) {
5765
- listeners.splice(i, 1);
5766
- return this;
5767
- }
5768
- }
5769
- }
5770
- else {
5771
- this._anyListeners = [];
5772
- }
5773
- return this;
5774
- }
5775
- /**
5776
- * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
5777
- * e.g. to remove listeners.
5778
- */
5779
- listenersAny() {
5780
- return this._anyListeners || [];
5781
- }
5782
- /**
5783
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
5784
- * callback.
5785
- *
5786
- * Note: acknowledgements sent to the server are not included.
5787
- *
5788
- * @example
5789
- * socket.onAnyOutgoing((event, ...args) => {
5790
- * console.log(`sent event ${event}`);
5791
- * });
5792
- *
5793
- * @param listener
5794
- */
5795
- onAnyOutgoing(listener) {
5796
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
5797
- this._anyOutgoingListeners.push(listener);
5798
- return this;
5799
- }
5800
- /**
5801
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
5802
- * callback. The listener is added to the beginning of the listeners array.
5803
- *
5804
- * Note: acknowledgements sent to the server are not included.
5805
- *
5806
- * @example
5807
- * socket.prependAnyOutgoing((event, ...args) => {
5808
- * console.log(`sent event ${event}`);
5809
- * });
5810
- *
5811
- * @param listener
5812
- */
5813
- prependAnyOutgoing(listener) {
5814
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
5815
- this._anyOutgoingListeners.unshift(listener);
5816
- return this;
5817
- }
5818
- /**
5819
- * Removes the listener that will be fired when any event is emitted.
5820
- *
5821
- * @example
5822
- * const catchAllListener = (event, ...args) => {
5823
- * console.log(`sent event ${event}`);
5824
- * }
5825
- *
5826
- * socket.onAnyOutgoing(catchAllListener);
5827
- *
5828
- * // remove a specific listener
5829
- * socket.offAnyOutgoing(catchAllListener);
5830
- *
5831
- * // or remove all listeners
5832
- * socket.offAnyOutgoing();
5833
- *
5834
- * @param [listener] - the catch-all listener (optional)
5835
- */
5836
- offAnyOutgoing(listener) {
5837
- if (!this._anyOutgoingListeners) {
5838
- return this;
5839
- }
5840
- if (listener) {
5841
- const listeners = this._anyOutgoingListeners;
5842
- for (let i = 0; i < listeners.length; i++) {
5843
- if (listener === listeners[i]) {
5844
- listeners.splice(i, 1);
5845
- return this;
5846
- }
5847
- }
5848
- }
5849
- else {
5850
- this._anyOutgoingListeners = [];
5851
- }
5852
- return this;
5853
- }
5854
- /**
5855
- * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
5856
- * e.g. to remove listeners.
5857
- */
5858
- listenersAnyOutgoing() {
5859
- return this._anyOutgoingListeners || [];
5860
- }
5861
- /**
5862
- * Notify the listeners for each packet sent
5863
- *
5864
- * @param packet
5865
- *
5866
- * @private
5867
- */
5868
- notifyOutgoingListeners(packet) {
5869
- if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
5870
- const listeners = this._anyOutgoingListeners.slice();
5871
- for (const listener of listeners) {
5872
- listener.apply(this, packet.data);
5873
- }
5874
- }
5875
- }
4485
+ function flush() {
4486
+ if (!_token || _buffer.length === 0) return;
4487
+ var events = _buffer.splice(0, _buffer.length);
4488
+ var body = JSON.stringify({
4489
+ warehouse_id: _warehouseId,
4490
+ organization_id: _organizationId,
4491
+ events: events
4492
+ });
4493
+ var headers = {
4494
+ 'Content-Type': 'application/json',
4495
+ Authorization: "Bearer ".concat(_token)
4496
+ };
4497
+ if (navigator.sendBeacon) {
4498
+ var blob = new Blob([body], {
4499
+ type: 'application/json'
4500
+ });
4501
+ navigator.sendBeacon("".concat(INGEST_BASE, "/api/ingest/events"), blob);
4502
+ } else {
4503
+ fetch("".concat(INGEST_BASE, "/api/ingest/events"), {
4504
+ method: 'POST',
4505
+ headers: headers,
4506
+ body: body,
4507
+ keepalive: true
4508
+ })["catch"](function (err) {
4509
+ return console.error('[CoreOutline] Flush error:', err);
4510
+ });
4511
+ }
5876
4512
  }
5877
-
5878
- /**
5879
- * Initialize backoff timer with `opts`.
5880
- *
5881
- * - `min` initial timeout in milliseconds [100]
5882
- * - `max` max timeout [10000]
5883
- * - `jitter` [0]
5884
- * - `factor` [2]
5885
- *
5886
- * @param {Object} opts
5887
- * @api public
5888
- */
5889
- function Backoff(opts) {
5890
- opts = opts || {};
5891
- this.ms = opts.min || 100;
5892
- this.max = opts.max || 10000;
5893
- this.factor = opts.factor || 2;
5894
- this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
5895
- this.attempts = 0;
4513
+ function sendRrwebBatch(_x4, _x5) {
4514
+ return _sendRrwebBatch.apply(this, arguments);
5896
4515
  }
5897
- /**
5898
- * Return the backoff duration.
5899
- *
5900
- * @return {Number}
5901
- * @api public
5902
- */
5903
- Backoff.prototype.duration = function () {
5904
- var ms = this.ms * Math.pow(this.factor, this.attempts++);
5905
- if (this.jitter) {
5906
- var rand = Math.random();
5907
- var deviation = Math.floor(rand * this.jitter * ms);
5908
- ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
5909
- }
5910
- return Math.min(ms, this.max) | 0;
5911
- };
5912
- /**
5913
- * Reset the number of attempts.
5914
- *
5915
- * @api public
5916
- */
5917
- Backoff.prototype.reset = function () {
5918
- this.attempts = 0;
5919
- };
5920
- /**
5921
- * Set the minimum duration
5922
- *
5923
- * @api public
5924
- */
5925
- Backoff.prototype.setMin = function (min) {
5926
- this.ms = min;
5927
- };
5928
- /**
5929
- * Set the maximum duration
5930
- *
5931
- * @api public
5932
- */
5933
- Backoff.prototype.setMax = function (max) {
5934
- this.max = max;
5935
- };
5936
- /**
5937
- * Set the jitter
5938
- *
5939
- * @api public
5940
- */
5941
- Backoff.prototype.setJitter = function (jitter) {
5942
- this.jitter = jitter;
5943
- };
5944
-
5945
- class Manager extends Emitter {
5946
- constructor(uri, opts) {
5947
- var _a;
5948
- super();
5949
- this.nsps = {};
5950
- this.subs = [];
5951
- if (uri && "object" === typeof uri) {
5952
- opts = uri;
5953
- uri = undefined;
5954
- }
5955
- opts = opts || {};
5956
- opts.path = opts.path || "/socket.io";
5957
- this.opts = opts;
5958
- installTimerFunctions(this, opts);
5959
- this.reconnection(opts.reconnection !== false);
5960
- this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
5961
- this.reconnectionDelay(opts.reconnectionDelay || 1000);
5962
- this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
5963
- this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
5964
- this.backoff = new Backoff({
5965
- min: this.reconnectionDelay(),
5966
- max: this.reconnectionDelayMax(),
5967
- jitter: this.randomizationFactor(),
5968
- });
5969
- this.timeout(null == opts.timeout ? 20000 : opts.timeout);
5970
- this._readyState = "closed";
5971
- this.uri = uri;
5972
- const _parser = opts.parser || parser;
5973
- this.encoder = new _parser.Encoder();
5974
- this.decoder = new _parser.Decoder();
5975
- this._autoConnect = opts.autoConnect !== false;
5976
- if (this._autoConnect)
5977
- this.open();
5978
- }
5979
- reconnection(v) {
5980
- if (!arguments.length)
5981
- return this._reconnection;
5982
- this._reconnection = !!v;
5983
- if (!v) {
5984
- this.skipReconnect = true;
5985
- }
5986
- return this;
5987
- }
5988
- reconnectionAttempts(v) {
5989
- if (v === undefined)
5990
- return this._reconnectionAttempts;
5991
- this._reconnectionAttempts = v;
5992
- return this;
5993
- }
5994
- reconnectionDelay(v) {
5995
- var _a;
5996
- if (v === undefined)
5997
- return this._reconnectionDelay;
5998
- this._reconnectionDelay = v;
5999
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
6000
- return this;
6001
- }
6002
- randomizationFactor(v) {
6003
- var _a;
6004
- if (v === undefined)
6005
- return this._randomizationFactor;
6006
- this._randomizationFactor = v;
6007
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
6008
- return this;
6009
- }
6010
- reconnectionDelayMax(v) {
6011
- var _a;
6012
- if (v === undefined)
6013
- return this._reconnectionDelayMax;
6014
- this._reconnectionDelayMax = v;
6015
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
6016
- return this;
6017
- }
6018
- timeout(v) {
6019
- if (!arguments.length)
6020
- return this._timeout;
6021
- this._timeout = v;
6022
- return this;
6023
- }
6024
- /**
6025
- * Starts trying to reconnect if reconnection is enabled and we have not
6026
- * started reconnecting yet
6027
- *
6028
- * @private
6029
- */
6030
- maybeReconnectOnOpen() {
6031
- // Only try to reconnect if it's the first time we're connecting
6032
- if (!this._reconnecting &&
6033
- this._reconnection &&
6034
- this.backoff.attempts === 0) {
6035
- // keeps reconnection from firing twice for the same reconnection loop
6036
- this.reconnect();
6037
- }
6038
- }
6039
- /**
6040
- * Sets the current transport `socket`.
6041
- *
6042
- * @param {Function} fn - optional, callback
6043
- * @return self
6044
- * @public
6045
- */
6046
- open(fn) {
6047
- if (~this._readyState.indexOf("open"))
6048
- return this;
6049
- this.engine = new Socket$1(this.uri, this.opts);
6050
- const socket = this.engine;
6051
- const self = this;
6052
- this._readyState = "opening";
6053
- this.skipReconnect = false;
6054
- // emit `open`
6055
- const openSubDestroy = on(socket, "open", function () {
6056
- self.onopen();
6057
- fn && fn();
6058
- });
6059
- const onError = (err) => {
6060
- this.cleanup();
6061
- this._readyState = "closed";
6062
- this.emitReserved("error", err);
6063
- if (fn) {
6064
- fn(err);
6065
- }
6066
- else {
6067
- // Only do this if there is no fn to handle the error
6068
- this.maybeReconnectOnOpen();
6069
- }
6070
- };
6071
- // emit `error`
6072
- const errorSub = on(socket, "error", onError);
6073
- if (false !== this._timeout) {
6074
- const timeout = this._timeout;
6075
- // set timer
6076
- const timer = this.setTimeoutFn(() => {
6077
- openSubDestroy();
6078
- onError(new Error("timeout"));
6079
- socket.close();
6080
- }, timeout);
6081
- if (this.opts.autoUnref) {
6082
- timer.unref();
6083
- }
6084
- this.subs.push(() => {
6085
- this.clearTimeoutFn(timer);
6086
- });
6087
- }
6088
- this.subs.push(openSubDestroy);
6089
- this.subs.push(errorSub);
6090
- return this;
6091
- }
6092
- /**
6093
- * Alias for open()
6094
- *
6095
- * @return self
6096
- * @public
6097
- */
6098
- connect(fn) {
6099
- return this.open(fn);
6100
- }
6101
- /**
6102
- * Called upon transport open.
6103
- *
6104
- * @private
6105
- */
6106
- onopen() {
6107
- // clear old subs
6108
- this.cleanup();
6109
- // mark as open
6110
- this._readyState = "open";
6111
- this.emitReserved("open");
6112
- // add new subs
6113
- const socket = this.engine;
6114
- this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)),
6115
- // @ts-ignore
6116
- on(this.decoder, "decoded", this.ondecoded.bind(this)));
6117
- }
6118
- /**
6119
- * Called upon a ping.
6120
- *
6121
- * @private
6122
- */
6123
- onping() {
6124
- this.emitReserved("ping");
6125
- }
6126
- /**
6127
- * Called with data.
6128
- *
6129
- * @private
6130
- */
6131
- ondata(data) {
6132
- try {
6133
- this.decoder.add(data);
6134
- }
6135
- catch (e) {
6136
- this.onclose("parse error", e);
6137
- }
6138
- }
6139
- /**
6140
- * Called when parser fully decodes a packet.
6141
- *
6142
- * @private
6143
- */
6144
- ondecoded(packet) {
6145
- // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
6146
- nextTick(() => {
6147
- this.emitReserved("packet", packet);
6148
- }, this.setTimeoutFn);
6149
- }
6150
- /**
6151
- * Called upon socket error.
6152
- *
6153
- * @private
6154
- */
6155
- onerror(err) {
6156
- this.emitReserved("error", err);
6157
- }
6158
- /**
6159
- * Creates a new socket for the given `nsp`.
6160
- *
6161
- * @return {Socket}
6162
- * @public
6163
- */
6164
- socket(nsp, opts) {
6165
- let socket = this.nsps[nsp];
6166
- if (!socket) {
6167
- socket = new Socket(this, nsp, opts);
6168
- this.nsps[nsp] = socket;
6169
- }
6170
- else if (this._autoConnect && !socket.active) {
6171
- socket.connect();
6172
- }
6173
- return socket;
6174
- }
6175
- /**
6176
- * Called upon a socket close.
6177
- *
6178
- * @param socket
6179
- * @private
6180
- */
6181
- _destroy(socket) {
6182
- const nsps = Object.keys(this.nsps);
6183
- for (const nsp of nsps) {
6184
- const socket = this.nsps[nsp];
6185
- if (socket.active) {
6186
- return;
6187
- }
6188
- }
6189
- this._close();
6190
- }
6191
- /**
6192
- * Writes a packet.
6193
- *
6194
- * @param packet
6195
- * @private
6196
- */
6197
- _packet(packet) {
6198
- const encodedPackets = this.encoder.encode(packet);
6199
- for (let i = 0; i < encodedPackets.length; i++) {
6200
- this.engine.write(encodedPackets[i], packet.options);
6201
- }
6202
- }
6203
- /**
6204
- * Clean up transport subscriptions and packet buffer.
6205
- *
6206
- * @private
6207
- */
6208
- cleanup() {
6209
- this.subs.forEach((subDestroy) => subDestroy());
6210
- this.subs.length = 0;
6211
- this.decoder.destroy();
6212
- }
6213
- /**
6214
- * Close the current socket.
6215
- *
6216
- * @private
6217
- */
6218
- _close() {
6219
- this.skipReconnect = true;
6220
- this._reconnecting = false;
6221
- this.onclose("forced close");
6222
- }
6223
- /**
6224
- * Alias for close()
6225
- *
6226
- * @private
6227
- */
6228
- disconnect() {
6229
- return this._close();
6230
- }
6231
- /**
6232
- * Called when:
6233
- *
6234
- * - the low-level engine is closed
6235
- * - the parser encountered a badly formatted packet
6236
- * - all sockets are disconnected
6237
- *
6238
- * @private
6239
- */
6240
- onclose(reason, description) {
6241
- var _a;
6242
- this.cleanup();
6243
- (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
6244
- this.backoff.reset();
6245
- this._readyState = "closed";
6246
- this.emitReserved("close", reason, description);
6247
- if (this._reconnection && !this.skipReconnect) {
6248
- this.reconnect();
6249
- }
6250
- }
6251
- /**
6252
- * Attempt a reconnection.
6253
- *
6254
- * @private
6255
- */
6256
- reconnect() {
6257
- if (this._reconnecting || this.skipReconnect)
6258
- return this;
6259
- const self = this;
6260
- if (this.backoff.attempts >= this._reconnectionAttempts) {
6261
- this.backoff.reset();
6262
- this.emitReserved("reconnect_failed");
6263
- this._reconnecting = false;
6264
- }
6265
- else {
6266
- const delay = this.backoff.duration();
6267
- this._reconnecting = true;
6268
- const timer = this.setTimeoutFn(() => {
6269
- if (self.skipReconnect)
6270
- return;
6271
- this.emitReserved("reconnect_attempt", self.backoff.attempts);
6272
- // check again for the case socket closed in above events
6273
- if (self.skipReconnect)
6274
- return;
6275
- self.open((err) => {
6276
- if (err) {
6277
- self._reconnecting = false;
6278
- self.reconnect();
6279
- this.emitReserved("reconnect_error", err);
6280
- }
6281
- else {
6282
- self.onreconnect();
6283
- }
6284
- });
6285
- }, delay);
6286
- if (this.opts.autoUnref) {
6287
- timer.unref();
6288
- }
6289
- this.subs.push(() => {
6290
- this.clearTimeoutFn(timer);
6291
- });
6292
- }
6293
- }
6294
- /**
6295
- * Called upon successful reconnect.
6296
- *
6297
- * @private
6298
- */
6299
- onreconnect() {
6300
- const attempt = this.backoff.attempts;
6301
- this._reconnecting = false;
6302
- this.backoff.reset();
6303
- this.emitReserved("reconnect", attempt);
6304
- }
4516
+ function _sendRrwebBatch() {
4517
+ _sendRrwebBatch = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(chunks, sessionId) {
4518
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
4519
+ while (1) switch (_context2.prev = _context2.next) {
4520
+ case 0:
4521
+ if (!(!_token || !chunks || chunks.length === 0)) {
4522
+ _context2.next = 2;
4523
+ break;
4524
+ }
4525
+ return _context2.abrupt("return");
4526
+ case 2:
4527
+ _context2.prev = 2;
4528
+ _context2.next = 5;
4529
+ return fetch("".concat(INGEST_BASE, "/api/ingest/rrweb"), {
4530
+ method: 'POST',
4531
+ headers: {
4532
+ 'Content-Type': 'application/json',
4533
+ Authorization: "Bearer ".concat(_token)
4534
+ },
4535
+ body: JSON.stringify({
4536
+ warehouse_id: _warehouseId,
4537
+ organization_id: _organizationId,
4538
+ session_id: sessionId,
4539
+ data_source_id: _dataSourceId,
4540
+ chunks: chunks
4541
+ }),
4542
+ keepalive: true
4543
+ });
4544
+ case 5:
4545
+ _context2.next = 10;
4546
+ break;
4547
+ case 7:
4548
+ _context2.prev = 7;
4549
+ _context2.t0 = _context2["catch"](2);
4550
+ console.error('[CoreOutline] rrweb upload error:', _context2.t0);
4551
+ case 10:
4552
+ case "end":
4553
+ return _context2.stop();
4554
+ }
4555
+ }, _callee2, null, [[2, 7]]);
4556
+ }));
4557
+ return _sendRrwebBatch.apply(this, arguments);
6305
4558
  }
6306
-
6307
- /**
6308
- * Managers cache.
6309
- */
6310
- const cache = {};
6311
- function lookup(uri, opts) {
6312
- if (typeof uri === "object") {
6313
- opts = uri;
6314
- uri = undefined;
6315
- }
6316
- opts = opts || {};
6317
- const parsed = url(uri, opts.path || "/socket.io");
6318
- const source = parsed.source;
6319
- const id = parsed.id;
6320
- const path = parsed.path;
6321
- const sameNamespace = cache[id] && path in cache[id]["nsps"];
6322
- const newConnection = opts.forceNew ||
6323
- opts["force new connection"] ||
6324
- false === opts.multiplex ||
6325
- sameNamespace;
6326
- let io;
6327
- if (newConnection) {
6328
- io = new Manager(source, opts);
6329
- }
6330
- else {
6331
- if (!cache[id]) {
6332
- cache[id] = new Manager(source, opts);
6333
- }
6334
- io = cache[id];
6335
- }
6336
- if (parsed.query && !opts.query) {
6337
- opts.query = parsed.queryKey;
6338
- }
6339
- return io.socket(parsed.path, opts);
4559
+ function stopFlushInterval() {
4560
+ if (_flushInterval) {
4561
+ clearInterval(_flushInterval);
4562
+ _flushInterval = null;
4563
+ }
6340
4564
  }
6341
- // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
6342
- // namespace (e.g. `io.connect(...)`), for backward compatibility
6343
- Object.assign(lookup, {
6344
- Manager,
6345
- Socket,
6346
- io: lookup,
6347
- connect: lookup,
6348
- });
6349
-
6350
- var socket = lookup('http://streams.coreoutline.com');
6351
4565
 
6352
4566
  var CoreOutline = function CoreOutline(_ref) {
6353
4567
  var children = _ref.children,
6354
4568
  data_source_id = _ref.data_source_id,
6355
- data_source_secret = _ref.data_source_secret;
4569
+ data_source_secret = _ref.data_source_secret,
4570
+ warehouse_id = _ref.warehouse_id;
6356
4571
  var _useState = useState([]),
6357
4572
  _useState2 = _slicedToArray(_useState, 2),
6358
- events = _useState2[0],
6359
- setEvents = _useState2[1];
6360
- var _useState3 = useState([]),
6361
- _useState4 = _slicedToArray(_useState3, 2),
6362
- replayEvents = _useState4[0],
6363
- setReplayEvents = _useState4[1];
4573
+ replayEvents = _useState2[0],
4574
+ setReplayEvents = _useState2[1];
6364
4575
  var recorderActive = useRef(false);
6365
- var _useState5 = useState(window.location.href),
6366
- _useState6 = _slicedToArray(_useState5, 2),
6367
- currentPage = _useState6[0],
6368
- setCurrentPage = _useState6[1];
6369
- var _useState7 = useState({
6370
- latitude: null,
6371
- longitude: null
6372
- }),
6373
- _useState8 = _slicedToArray(_useState7, 2),
6374
- location = _useState8[0],
6375
- setLocation = _useState8[1];
6376
- var _useState9 = useState(getBrowserInfo()),
6377
- _useState10 = _slicedToArray(_useState9, 2),
6378
- browser = _useState10[0];
6379
- _useState10[1];
6380
- var _useState11 = useState(''),
6381
- _useState12 = _slicedToArray(_useState11, 2);
6382
- _useState12[0];
6383
- var setAppToken = _useState12[1];
6384
- var _useState13 = useState(v4()),
6385
- _useState14 = _slicedToArray(_useState13, 2),
6386
- sessionId = _useState14[0];
6387
- _useState14[1];
6388
- function authorizeApp(_x, _x2) {
6389
- return _authorizeApp.apply(this, arguments);
6390
- }
6391
- function _authorizeApp() {
6392
- _authorizeApp = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(data_source_id, data_source_secret) {
6393
- var requestOptions, response;
6394
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
6395
- while (1) switch (_context2.prev = _context2.next) {
6396
- case 0:
6397
- requestOptions = {
6398
- method: 'POST',
6399
- headers: {
6400
- 'Content-Type': 'application/json'
6401
- },
6402
- body: JSON.stringify({
6403
- data_source_id: data_source_id,
6404
- data_source_secret: data_source_secret
6405
- })
6406
- };
6407
- response = fetch("http://api.coreoutline.com/data-source/authorize", requestOptions).then(function (response) {
6408
- return response.json();
6409
- }).then(function (data) {
6410
- setAppToken(data.app_token);
6411
- return data;
6412
- })["catch"](function (error) {
6413
- console.error('Error:', error);
6414
- return error;
6415
- });
6416
- return _context2.abrupt("return", response);
6417
- case 3:
6418
- case "end":
6419
- return _context2.stop();
6420
- }
6421
- }, _callee2);
6422
- }));
6423
- return _authorizeApp.apply(this, arguments);
6424
- }
6425
- var offLoadFunctionality = function offLoadFunctionality() {
6426
- var formattedEvents = events;
6427
- var rawEvents = replayEvents;
6428
- var data = JSON.stringify({
6429
- data_source_id: data_source_id,
6430
- sessionId: sessionId,
6431
- formatted_events: formattedEvents,
6432
- raw_events: rawEvents
6433
- });
6434
- socket.send({
6435
- topic: 'session-data',
6436
- data_source_id: data_source_id,
6437
- session_id: localStorage.getItem('coreOutlineSessionId'),
6438
- start_date: new Date().toLocaleString(),
6439
- latitude: location.latitude,
6440
- longitude: location.longitude,
6441
- browser: browser,
6442
- event_id: 'SESSION_END'
6443
- });
6444
- if (navigator.sendBeacon) {
6445
- navigator.sendBeacon("http://data.coreoutline.com/upload-events", data);
6446
- } else {
6447
- fetch("http://data.coreoutline.com/upload-events", {
6448
- method: 'POST',
6449
- body: data,
6450
- keepalive: true,
6451
- headers: {
6452
- 'Content-Type': 'application/json'
6453
- }
6454
- })["catch"](function (err) {
6455
- return console.error('Upload failed:', err);
6456
- });
6457
- }
6458
- };
6459
- useEffect(function () {}, [events, replayEvents]);
6460
- useEffect(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
6461
- var handleBeforeUnload, handleVisibilityChange;
6462
- return _regeneratorRuntime().wrap(function _callee$(_context) {
6463
- while (1) switch (_context.prev = _context.next) {
6464
- case 0:
6465
- handleBeforeUnload = function handleBeforeUnload() {
6466
- offLoadFunctionality();
6467
- };
6468
- handleVisibilityChange = function handleVisibilityChange() {
6469
- if (document.visibilityState === 'hidden') {
6470
- offLoadFunctionality();
6471
- }
6472
- };
6473
- window.addEventListener('beforeunload', handleBeforeUnload);
6474
- document.addEventListener('visibilitychange', handleVisibilityChange);
6475
- _context.next = 6;
6476
- return authorizeApp(data_source_id, data_source_secret);
6477
- case 6:
6478
- localStorage.setItem('coreOutlineSessionId', sessionId);
6479
- localStorage.setItem('coreOutlineDataSourceIdId', data_source_id);
6480
- console.log('Session', sessionId);
6481
- socket.send({
6482
- topic: 'session-data',
6483
- data_source_id: data_source_id,
6484
- session_id: localStorage.getItem('coreOutlineSessionId'),
6485
- start_date: new Date().toLocaleString(),
6486
- latitude: location.latitude,
6487
- longitude: location.longitude,
6488
- browser: browser,
6489
- event_id: 'SESSION_START'
6490
- });
6491
- return _context.abrupt("return", function () {
6492
- offLoadFunctionality();
6493
- window.removeEventListener('beforeunload', handleBeforeUnload);
6494
- document.removeEventListener('visibilitychange', handleVisibilityChange);
6495
- socket.send({
6496
- topic: 'session-data',
6497
- data_source_id: data_source_id,
6498
- session_id: localStorage.getItem('coreOutlineSessionId'),
6499
- start_date: new Date().toLocaleString(),
6500
- latitude: location.latitude,
6501
- longitude: location.longitude,
6502
- browser: browser,
6503
- event_id: 'SESSION_END'
6504
- });
6505
- });
6506
- case 11:
6507
- case "end":
6508
- return _context.stop();
6509
- }
6510
- }, _callee);
6511
- })), []);
4576
+ var _useState3 = useState(window.location.href),
4577
+ _useState4 = _slicedToArray(_useState3, 2),
4578
+ currentPage = _useState4[0],
4579
+ setCurrentPage = _useState4[1];
4580
+ var pageviewCountRef = useRef(0);
4581
+ var eventCountRef = useRef(0);
4582
+ var sessionStartRef = useRef(Date.now());
4583
+ var sessionId = getSessionId();
4584
+ var anonymousId = getAnonymousId();
6512
4585
  useEffect(function () {
6513
- var navigationEvent = {
6514
- type: 4,
6515
- data: {
6516
- href: window.location.href,
6517
- width: 1536,
6518
- height: 730
6519
- },
6520
- timestamp: Date.now()
4586
+ var utmParams = getUtmParams();
4587
+ var deviceType = detectDeviceType();
4588
+ var os = detectOS();
4589
+ var browser = getBrowserName();
4590
+ var referrer = document.referrer || 'direct';
4591
+ var basePayload = _objectSpread2({
4592
+ session_id: sessionId,
4593
+ anonymous_id: anonymousId,
4594
+ account_id: data_source_id,
4595
+ platform: 'web',
4596
+ device_type: deviceType,
4597
+ os: os,
4598
+ browser: browser,
4599
+ referrer: referrer,
4600
+ page_url: window.location.href,
4601
+ page_path: getPagePath()
4602
+ }, utmParams);
4603
+ var initialized = false;
4604
+ var init = /*#__PURE__*/function () {
4605
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
4606
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
4607
+ while (1) switch (_context.prev = _context.next) {
4608
+ case 0:
4609
+ _context.next = 2;
4610
+ return initIngest(warehouse_id, data_source_id, data_source_secret);
4611
+ case 2:
4612
+ initialized = _context.sent;
4613
+ if (initialized) {
4614
+ _context.next = 5;
4615
+ break;
4616
+ }
4617
+ return _context.abrupt("return");
4618
+ case 5:
4619
+ pageviewCountRef.current += 1;
4620
+ trackEvent('pageview', _objectSpread2(_objectSpread2({}, basePayload), {}, {
4621
+ event_name: 'pageview',
4622
+ event_category: 'navigation'
4623
+ }));
4624
+ trackEvent('session_start', _objectSpread2(_objectSpread2({}, basePayload), {}, {
4625
+ event_name: 'session_start',
4626
+ event_category: 'session',
4627
+ session_start_ts: new Date().toISOString()
4628
+ }));
4629
+ case 8:
4630
+ case "end":
4631
+ return _context.stop();
4632
+ }
4633
+ }, _callee);
4634
+ }));
4635
+ return function init() {
4636
+ return _ref2.apply(this, arguments);
4637
+ };
4638
+ }();
4639
+ init();
4640
+ var handleSessionEnd = function handleSessionEnd() {
4641
+ if (!initialized) return;
4642
+ var durationMs = Date.now() - sessionStartRef.current;
4643
+ trackEvent('session_end', _objectSpread2(_objectSpread2({}, basePayload), {}, {
4644
+ event_name: 'session_end',
4645
+ event_category: 'session',
4646
+ session_end_ts: new Date().toISOString(),
4647
+ pageviews: pageviewCountRef.current,
4648
+ events_count: eventCountRef.current,
4649
+ duration_ms: durationMs
4650
+ }));
4651
+ flush();
4652
+ stopFlushInterval();
4653
+ sendRrwebBatch(replayEvents, sessionId);
6521
4654
  };
6522
- var startTime = performance.now();
6523
- var observer = new MutationObserver(function () {
6524
- var endTime = performance.now();
6525
- var loadTime = endTime - startTime;
6526
- navigationEvent.data.loadTime = loadTime;
6527
- var hours = Math.floor(loadTime / 3600000);
6528
- var minutes = Math.floor(loadTime % 3600000 / 60000);
6529
- var seconds = Math.floor(loadTime % 60000 / 1000);
6530
- navigationEvent.data.loadTimeFormatted = "".concat(hours, " hours ").concat(minutes, " minutes ").concat(seconds, " seconds");
6531
- observer.disconnect();
6532
- });
6533
- observer.observe(document, {
6534
- childList: true,
6535
- subtree: true
6536
- });
6537
- setEvents(function (prevEvents) {
6538
- return [].concat(_toConsumableArray(prevEvents), [navigationEvent]);
6539
- });
6540
- localStorage.setItem('coreoutlineFormattedEvents', JSON.stringify(function (prevEvents) {
6541
- return [].concat(_toConsumableArray(prevEvents), [navigationEvent]);
6542
- }));
4655
+ var handleVisibilityChange = function handleVisibilityChange() {
4656
+ if (document.visibilityState === 'hidden') handleSessionEnd();
4657
+ };
4658
+ window.addEventListener('beforeunload', handleSessionEnd);
4659
+ document.addEventListener('visibilitychange', handleVisibilityChange);
4660
+ return function () {
4661
+ handleSessionEnd();
4662
+ window.removeEventListener('beforeunload', handleSessionEnd);
4663
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
4664
+ };
4665
+ }, []);
4666
+ useEffect(function () {
4667
+ var utmParams = getUtmParams();
6543
4668
  var handleNavigation = function handleNavigation() {
6544
4669
  setCurrentPage(window.location.href);
6545
- socket.send({
6546
- topic: 'session-data',
6547
- data_source_id: data_source_id,
6548
- session_id: localStorage.getItem('coreOutlineSessionId'),
6549
- start_date: new Date().toLocaleString(),
6550
- latitude: location.latitude,
6551
- longitude: location.longitude,
6552
- browser: browser,
6553
- page_name: window.location.href,
6554
- event_id: 'PAGE_NAVIGATION'
6555
- });
4670
+ pageviewCountRef.current += 1;
4671
+ trackEvent('pageview', _objectSpread2({
4672
+ session_id: sessionId,
4673
+ anonymous_id: anonymousId,
4674
+ account_id: data_source_id,
4675
+ platform: 'web',
4676
+ page_url: window.location.href,
4677
+ page_path: getPagePath(),
4678
+ referrer: document.referrer || 'direct',
4679
+ event_name: 'pageview',
4680
+ event_category: 'navigation'
4681
+ }, utmParams));
6556
4682
  };
6557
4683
  window.addEventListener('popstate', handleNavigation);
6558
4684
  var originalPushState = window.history.pushState;
@@ -6568,61 +4694,14 @@ var CoreOutline = function CoreOutline(_ref) {
6568
4694
  window.history.pushState = originalPushState;
6569
4695
  };
6570
4696
  }, [currentPage]);
6571
- useEffect(function () {
6572
- console.log('Location', location);
6573
- getLocation();
6574
- }, []);
6575
4697
  useEffect(function () {
6576
4698
  var stopFn;
6577
4699
  if (!recorderActive.current) {
6578
4700
  stopFn = record({
6579
4701
  emit: function emit(event) {
6580
- setReplayEvents(function (prevEvents) {
6581
- return [].concat(_toConsumableArray(prevEvents), [event]);
4702
+ setReplayEvents(function (prev) {
4703
+ return [].concat(_toConsumableArray(prev), [event]);
6582
4704
  });
6583
- localStorage.setItem('coreoutlineRawEvents', JSON.stringify(function (prevEvents) {
6584
- return [].concat(_toConsumableArray(replayEvents), [event]);
6585
- }));
6586
- },
6587
- maskAllInputs: false,
6588
- maskTextSelector: null
6589
- });
6590
- recorderActive.current = true;
6591
- }
6592
- return function () {
6593
- if (stopFn) {
6594
- stopFn();
6595
- recorderActive.current = false;
6596
- }
6597
- };
6598
- }, []);
6599
- useEffect(function () {
6600
- var stopFn;
6601
- if (!recorderActive.current) {
6602
- stopFn = record({
6603
- emit: function emit(event) {
6604
- console.log('Event:', event);
6605
- if (event.type == 3 && event.data.type == 2) {
6606
- return;
6607
- }
6608
- if (event.type == 4) {
6609
- return;
6610
- }
6611
- if (event.type == 3 && event.data.source == 0) {
6612
- return;
6613
- }
6614
- if (event.type == 3 && event.data.source == 1) {
6615
- return;
6616
- }
6617
- if (event.type == 3 && event.data.type == 3) {
6618
- console.log('Contextmenu Event:', event);
6619
- }
6620
- setEvents(function (prevEvents) {
6621
- return [].concat(_toConsumableArray(prevEvents), [event]);
6622
- });
6623
- localStorage.setItem('coreoutlineFormattedEvents', JSON.stringify(function (prevEvents) {
6624
- return [].concat(_toConsumableArray(prevEvents), [event]);
6625
- }));
6626
4705
  },
6627
4706
  maskAllInputs: false,
6628
4707
  maskTextSelector: null
@@ -6638,122 +4717,45 @@ var CoreOutline = function CoreOutline(_ref) {
6638
4717
  }, []);
6639
4718
  useEffect(function () {
6640
4719
  var handleClick = function handleClick(event) {
6641
- console.log('Inner text:', event.target.innerText);
6642
- var clickEvent = {
6643
- type: EventType.IncrementalSnapshot,
6644
- data: {
6645
- source: IncrementalSource.MouseInteraction,
6646
- type: MouseInteractions.Click,
6647
- id: event.target.id,
6648
- x: event.clientX,
6649
- y: event.clientY
6650
- },
6651
- timestamp: Date.now()
6652
- };
6653
- var clickedElement = document.elementFromPoint(clickEvent.data.x, clickEvent.data.y);
6654
- if (clickedElement) {
6655
- clickEvent.data.metadata = {
6656
- label: clickedElement.getAttribute('data-label') || clickedElement.innerText || null,
6657
- value: clickedElement.getAttribute('value') || clickedElement.innerText || null,
6658
- id: clickedElement.getAttribute('id') || clickedElement.innerText || null,
6659
- name: clickedElement.getAttribute('name') || clickedElement.innerText || null,
6660
- "class": clickedElement.getAttribute('class') || clickedElement.innerText || null,
6661
- tag: clickedElement.tagName,
6662
- html: String(clickedElement.getHTML()),
6663
- innerText: event.target.innerText
6664
- };
6665
- }
6666
- setEvents(function (prevEvents) {
6667
- return [].concat(_toConsumableArray(prevEvents), [clickEvent]);
6668
- });
6669
- localStorage.setItem('coreoutlineFormattedEvents', JSON.stringify(function (prevEvents) {
6670
- return [].concat(_toConsumableArray(prevEvents), [clickEvent]);
6671
- }));
6672
- socket.send({
6673
- topic: 'session-data',
6674
- data_source_id: data_source_id,
6675
- session_id: localStorage.getItem('coreOutlineSessionId'),
6676
- start_date: new Date().toLocaleString(),
6677
- latitude: location.latitude,
6678
- longitude: location.longitude,
6679
- browser: browser,
6680
- event_id: 'ITEM_CLICKED'
6681
- // item_clicked: event.target,
4720
+ var clickedElement = document.elementFromPoint(event.clientX, event.clientY);
4721
+ var metadata = clickedElement ? {
4722
+ label: clickedElement.getAttribute('data-label') || clickedElement.innerText || null,
4723
+ value: clickedElement.getAttribute('value') || clickedElement.innerText || null,
4724
+ id: clickedElement.getAttribute('id') || null,
4725
+ name: clickedElement.getAttribute('name') || null,
4726
+ "class": clickedElement.getAttribute('class') || null,
4727
+ tag: clickedElement.tagName,
4728
+ inner_text: event.target.innerText || null
4729
+ } : {};
4730
+ eventCountRef.current += 1;
4731
+ trackEvent('item_clicked', {
4732
+ session_id: sessionId,
4733
+ anonymous_id: anonymousId,
4734
+ account_id: data_source_id,
4735
+ platform: 'web',
4736
+ page_url: window.location.href,
4737
+ page_path: getPagePath(),
4738
+ event_name: 'item_clicked',
4739
+ event_category: 'interaction',
4740
+ properties_json: JSON.stringify(metadata)
6682
4741
  });
6683
4742
  };
6684
4743
  document.addEventListener('click', handleClick);
6685
4744
  return function () {
6686
- document.removeEventListener('click', handleClick);
4745
+ return document.removeEventListener('click', handleClick);
6687
4746
  };
6688
4747
  }, []);
6689
- function saveEventsLocally() {
6690
- var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'formatted' ;
6691
- var blob = '';
6692
- if (type === 'formatted') {
6693
- blob = new Blob([JSON.stringify(events, null, 2)], {
6694
- type: 'application/json'
6695
- });
6696
- } else if (type === 'raw') {
6697
- blob = new Blob([JSON.stringify(replayEvents, null, 2)], {
6698
- type: 'application/json'
6699
- });
6700
- }
6701
- var url = URL.createObjectURL(blob);
6702
- var a = document.createElement('a');
6703
- a.href = url;
6704
- a.download = "".concat(type, "_events.json");
6705
- a.click();
6706
- URL.revokeObjectURL(url);
6707
- }
6708
- function getBrowserInfo() {
6709
- var userAgent = navigator.userAgent;
6710
- var browserName = 'Unknown';
6711
- if (userAgent.indexOf('Firefox') > -1) {
6712
- browserName = 'Firefox';
6713
- } else if (userAgent.indexOf('Opera') > -1 || userAgent.indexOf('OPR') > -1) {
6714
- browserName = 'Opera';
6715
- } else if (userAgent.indexOf('Chrome') > -1) {
6716
- browserName = 'Chrome';
6717
- } else if (userAgent.indexOf('Safari') > -1) {
6718
- browserName = 'Safari';
6719
- } else if (userAgent.indexOf('MSIE') > -1 || userAgent.indexOf('Trident/') > -1) {
6720
- browserName = 'Internet Explorer';
6721
- }
6722
- return browserName;
6723
- }
6724
- function getLocation() {
6725
- if (navigator.geolocation) {
6726
- navigator.geolocation.getCurrentPosition(function (position) {
6727
- setLocation({
6728
- latitude: position.coords.latitude,
6729
- longitude: position.coords.longitude
6730
- });
6731
- }, function (error) {
6732
- console.error('Error getting location:', error);
6733
- });
6734
- } else {
6735
- console.error('Geolocation is not supported by this browser.');
6736
- }
6737
- }
6738
- return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("button", {
6739
- onClick: function onClick() {
6740
- saveEventsLocally('formatted');
6741
- saveEventsLocally('raw');
6742
- }
6743
- }, "Save Events Locally"), children);
4748
+ return /*#__PURE__*/React.createElement(React.Fragment, null, children);
6744
4749
  };
6745
4750
  var flag_item_clicked = function flag_item_clicked(item_id) {
6746
- var sessionId = localStorage.getItem('coreOutlineSessionId');
6747
- var dataSourceId = localStorage.getItem('coreOutlineDataSourceIdId');
6748
- console.log('Session', sessionId);
6749
- console.log('Data Source', dataSourceId);
6750
- socket.send({
6751
- topic: 'session-data',
6752
- data_source_id: dataSourceId,
6753
- session_id: localStorage.getItem('coreOutlineSessionId'),
6754
- start_date: new Date().toLocaleString(),
6755
- event_id: 'PRODUCT_CLICKED',
6756
- item_clicked: item_id
4751
+ var sessionId = sessionStorage.getItem('co_session_id') || '';
4752
+ var anonymousId = localStorage.getItem('co_anon_id') || '';
4753
+ trackEvent('product_clicked', {
4754
+ session_id: sessionId,
4755
+ anonymous_id: anonymousId,
4756
+ event_name: 'product_clicked',
4757
+ event_category: 'commerce',
4758
+ feature_key: item_id
6757
4759
  });
6758
4760
  return {
6759
4761
  status: 'success',
@@ -6761,17 +4763,16 @@ var flag_item_clicked = function flag_item_clicked(item_id) {
6761
4763
  };
6762
4764
  };
6763
4765
  var flag_item_purchased = function flag_item_purchased(item_id) {
6764
- var sessionId = localStorage.getItem('coreOutlineSessionId');
6765
- var dataSourceId = localStorage.getItem('coreOutlineDataSourceIdId');
6766
- console.log('Session', sessionId);
6767
- console.log('Data Source', dataSourceId);
6768
- socket.send({
6769
- topic: 'session-data',
6770
- data_source_id: dataSourceId,
6771
- session_id: localStorage.getItem('coreOutlineSessionId'),
6772
- start_date: new Date().toLocaleString(),
6773
- event_id: 'PRODUCT_PURCHASED',
6774
- item_clicked: item_id
4766
+ var price = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
4767
+ var sessionId = sessionStorage.getItem('co_session_id') || '';
4768
+ var anonymousId = localStorage.getItem('co_anon_id') || '';
4769
+ trackEvent('product_purchased', {
4770
+ session_id: sessionId,
4771
+ anonymous_id: anonymousId,
4772
+ event_name: 'product_purchased',
4773
+ event_category: 'commerce',
4774
+ feature_key: item_id,
4775
+ value_num: price != null ? Number(price) : null
6775
4776
  });
6776
4777
  return {
6777
4778
  status: 'success',