@newrelic/browser-agent 1.267.0 → 1.269.0

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.
Files changed (104) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +2 -1
  3. package/dist/cjs/common/config/init.js +3 -0
  4. package/dist/cjs/common/constants/env.cdn.js +1 -1
  5. package/dist/cjs/common/constants/env.npm.js +1 -1
  6. package/dist/cjs/common/dom/iframe.js +10 -0
  7. package/dist/cjs/common/dom/selector-path.js +48 -0
  8. package/dist/cjs/common/event-listener/event-listener-opts.js +4 -26
  9. package/dist/cjs/common/timing/time-keeper.js +9 -0
  10. package/dist/cjs/common/util/stringify.js +1 -1
  11. package/dist/cjs/features/generic_events/aggregate/index.js +80 -9
  12. package/dist/cjs/features/generic_events/aggregate/user-actions/aggregated-user-action.js +39 -0
  13. package/dist/cjs/features/generic_events/aggregate/user-actions/user-actions-aggregator.js +77 -0
  14. package/dist/cjs/features/generic_events/constants.js +6 -2
  15. package/dist/cjs/features/generic_events/instrument/index.js +12 -1
  16. package/dist/cjs/features/jserrors/aggregate/index.js +23 -3
  17. package/dist/cjs/features/jserrors/aggregate/internal-errors.js +42 -0
  18. package/dist/cjs/features/logging/aggregate/index.js +10 -2
  19. package/dist/cjs/features/metrics/aggregate/index.js +2 -1
  20. package/dist/cjs/features/page_view_event/aggregate/index.js +1 -1
  21. package/dist/cjs/features/session_replay/aggregate/index.js +5 -3
  22. package/dist/cjs/features/session_trace/aggregate/index.js +11 -9
  23. package/dist/cjs/features/spa/instrument/index.js +4 -0
  24. package/dist/cjs/loaders/agent-base.js +1 -0
  25. package/dist/cjs/loaders/micro-agent.js +1 -1
  26. package/dist/esm/common/config/init.js +3 -0
  27. package/dist/esm/common/constants/env.cdn.js +1 -1
  28. package/dist/esm/common/constants/env.npm.js +1 -1
  29. package/dist/esm/common/dom/iframe.js +4 -0
  30. package/dist/esm/common/dom/selector-path.js +41 -0
  31. package/dist/esm/common/event-listener/event-listener-opts.js +4 -27
  32. package/dist/esm/common/timing/time-keeper.js +9 -0
  33. package/dist/esm/common/util/stringify.js +1 -1
  34. package/dist/esm/features/generic_events/aggregate/index.js +82 -11
  35. package/dist/esm/features/generic_events/aggregate/user-actions/aggregated-user-action.js +32 -0
  36. package/dist/esm/features/generic_events/aggregate/user-actions/user-actions-aggregator.js +70 -0
  37. package/dist/esm/features/generic_events/constants.js +5 -1
  38. package/dist/esm/features/generic_events/instrument/index.js +14 -3
  39. package/dist/esm/features/jserrors/aggregate/index.js +23 -3
  40. package/dist/esm/features/jserrors/aggregate/internal-errors.js +36 -0
  41. package/dist/esm/features/logging/aggregate/index.js +10 -2
  42. package/dist/esm/features/metrics/aggregate/index.js +2 -1
  43. package/dist/esm/features/page_view_event/aggregate/index.js +1 -1
  44. package/dist/esm/features/session_replay/aggregate/index.js +5 -3
  45. package/dist/esm/features/session_trace/aggregate/index.js +11 -9
  46. package/dist/esm/features/spa/instrument/index.js +4 -0
  47. package/dist/esm/loaders/agent-base.js +1 -0
  48. package/dist/esm/loaders/micro-agent.js +1 -1
  49. package/dist/types/common/config/init.d.ts.map +1 -1
  50. package/dist/types/common/dom/iframe.d.ts +2 -0
  51. package/dist/types/common/dom/iframe.d.ts.map +1 -0
  52. package/dist/types/common/dom/selector-path.d.ts +2 -0
  53. package/dist/types/common/dom/selector-path.d.ts.map +1 -0
  54. package/dist/types/common/event-listener/event-listener-opts.d.ts +2 -2
  55. package/dist/types/common/event-listener/event-listener-opts.d.ts.map +1 -1
  56. package/dist/types/common/timing/time-keeper.d.ts +6 -0
  57. package/dist/types/common/timing/time-keeper.d.ts.map +1 -1
  58. package/dist/types/features/generic_events/aggregate/index.d.ts +16 -1
  59. package/dist/types/features/generic_events/aggregate/index.d.ts.map +1 -1
  60. package/dist/types/features/generic_events/aggregate/user-actions/aggregated-user-action.d.ts +22 -0
  61. package/dist/types/features/generic_events/aggregate/user-actions/aggregated-user-action.d.ts.map +1 -0
  62. package/dist/types/features/generic_events/aggregate/user-actions/user-actions-aggregator.d.ts +12 -0
  63. package/dist/types/features/generic_events/aggregate/user-actions/user-actions-aggregator.d.ts.map +1 -0
  64. package/dist/types/features/generic_events/constants.d.ts +4 -0
  65. package/dist/types/features/generic_events/constants.d.ts.map +1 -1
  66. package/dist/types/features/generic_events/instrument/index.d.ts.map +1 -1
  67. package/dist/types/features/jserrors/aggregate/index.d.ts +10 -1
  68. package/dist/types/features/jserrors/aggregate/index.d.ts.map +1 -1
  69. package/dist/types/features/jserrors/aggregate/internal-errors.d.ts +7 -0
  70. package/dist/types/features/jserrors/aggregate/internal-errors.d.ts.map +1 -0
  71. package/dist/types/features/logging/aggregate/index.d.ts +3 -0
  72. package/dist/types/features/logging/aggregate/index.d.ts.map +1 -1
  73. package/dist/types/features/metrics/aggregate/index.d.ts.map +1 -1
  74. package/dist/types/features/page_view_event/aggregate/index.d.ts.map +1 -1
  75. package/dist/types/features/session_replay/aggregate/index.d.ts.map +1 -1
  76. package/dist/types/features/session_trace/aggregate/index.d.ts.map +1 -1
  77. package/dist/types/features/spa/instrument/index.d.ts +3 -0
  78. package/dist/types/features/spa/instrument/index.d.ts.map +1 -1
  79. package/dist/types/loaders/agent-base.d.ts +1 -0
  80. package/dist/types/loaders/agent-base.d.ts.map +1 -1
  81. package/dist/types/loaders/micro-agent.d.ts.map +1 -1
  82. package/package.json +1 -1
  83. package/src/common/config/init.js +1 -0
  84. package/src/common/dom/iframe.js +4 -0
  85. package/src/common/dom/selector-path.js +45 -0
  86. package/src/common/event-listener/event-listener-opts.js +5 -30
  87. package/src/common/timing/__mocks__/time-keeper.js +1 -0
  88. package/src/common/timing/time-keeper.js +9 -0
  89. package/src/common/util/stringify.js +1 -1
  90. package/src/features/generic_events/aggregate/index.js +74 -14
  91. package/src/features/generic_events/aggregate/user-actions/aggregated-user-action.js +33 -0
  92. package/src/features/generic_events/aggregate/user-actions/user-actions-aggregator.js +73 -0
  93. package/src/features/generic_events/constants.js +6 -0
  94. package/src/features/generic_events/instrument/index.js +19 -3
  95. package/src/features/jserrors/aggregate/index.js +21 -7
  96. package/src/features/jserrors/aggregate/internal-errors.js +33 -0
  97. package/src/features/logging/aggregate/index.js +9 -4
  98. package/src/features/metrics/aggregate/index.js +2 -1
  99. package/src/features/page_view_event/aggregate/index.js +1 -3
  100. package/src/features/session_replay/aggregate/index.js +5 -7
  101. package/src/features/session_trace/aggregate/index.js +12 -16
  102. package/src/features/spa/instrument/index.js +3 -0
  103. package/src/loaders/agent-base.js +1 -0
  104. package/src/loaders/micro-agent.js +2 -1
@@ -16,6 +16,7 @@ var _eventListenerOpts = require("../../../common/event-listener/event-listener-
16
16
  var _runtime2 = require("../../../common/constants/runtime");
17
17
  var _aggregateBase = require("../../utils/aggregate-base");
18
18
  var _drain = require("../../../common/drain/drain");
19
+ var _iframe = require("../../../common/dom/iframe");
19
20
  // import { WEBSOCKET_TAG } from '../../../common/wrap/wrap-websocket'
20
21
  // import { handleWebsocketEvents } from './websocket-detection'
21
22
 
@@ -111,7 +112,7 @@ class Aggregate extends _aggregateBase.AggregateBase {
111
112
  if (proxy.assets) this.storeSupportabilityMetrics('Config/AssetsUrl/Changed');
112
113
  if (proxy.beacon) this.storeSupportabilityMetrics('Config/BeaconUrl/Changed');
113
114
  if (_runtime2.isBrowserScope && window.MutationObserver) {
114
- if (window.self !== window.top) {
115
+ if ((0, _iframe.isIFrameWindow)(window)) {
115
116
  this.storeSupportabilityMetrics('Generic/Runtime/IFrame/Detected');
116
117
  }
117
118
  const preExistingVideos = window.document.querySelectorAll('video').length;
@@ -118,7 +118,7 @@ class Aggregate extends _aggregateBase.AggregateBase {
118
118
  queryParameters.fp = _firstPaint.firstPaint.current.value;
119
119
  queryParameters.fcp = _firstContentfulPaint.firstContentfulPaint.current.value;
120
120
  if (this.timeKeeper?.ready) {
121
- queryParameters.timestamp = Math.floor(this.timeKeeper.correctAbsoluteTimestamp(this.timeKeeper.convertRelativeTimestamp((0, _now.now)())));
121
+ queryParameters.timestamp = Math.floor(this.timeKeeper.correctRelativeTimestamp((0, _now.now)()));
122
122
  }
123
123
  const rumStartTime = (0, _now.now)();
124
124
  harvester.send({
@@ -26,6 +26,7 @@ var _drain = require("../../../common/drain/drain");
26
26
  var _now = require("../../../common/timing/now");
27
27
  var _utils = require("../shared/utils");
28
28
  var _agentConstants = require("../../../common/constants/agent-constants");
29
+ var _cleanUrl = require("../../../common/url/clean-url");
29
30
  function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
30
31
  function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } /*
31
32
  * Copyright 2023 New Relic Corporation. All rights reserved.
@@ -343,8 +344,8 @@ class Aggregate extends _aggregateBase.AggregateBase {
343
344
  const firstEventTimestamp = this.getCorrectedTimestamp(events[0]); // from rrweb node
344
345
  const lastEventTimestamp = this.getCorrectedTimestamp(events[events.length - 1]); // from rrweb node
345
346
  // from rrweb node || from when the harvest cycle started
346
- const firstTimestamp = firstEventTimestamp || Math.floor(this.timeKeeper.correctAbsoluteTimestamp(this.timeKeeper.correctAbsoluteTimestamp(recorderEvents.cycleTimestamp)));
347
- const lastTimestamp = lastEventTimestamp || Math.floor(this.timeKeeper.correctAbsoluteTimestamp(this.timeKeeper.convertRelativeTimestamp(relativeNow)));
347
+ const firstTimestamp = firstEventTimestamp || Math.floor(this.timeKeeper.correctAbsoluteTimestamp(recorderEvents.cycleTimestamp));
348
+ const lastTimestamp = lastEventTimestamp || Math.floor(this.timeKeeper.correctRelativeTimestamp(relativeNow));
348
349
  const agentMetadata = agentRuntime.appMetadata?.agents?.[0] || {};
349
350
  return {
350
351
  qs: {
@@ -382,7 +383,8 @@ class Aggregate extends _aggregateBase.AggregateBase {
382
383
  // customer-defined data should go last so that if it exceeds the query param padding limit it will be truncated instead of important attrs
383
384
  ...(endUserId && {
384
385
  'enduser.id': this.obfuscator.obfuscateString(endUserId)
385
- })
386
+ }),
387
+ currentUrl: this.obfuscator.obfuscateString((0, _cleanUrl.cleanURL)('' + location))
386
388
  // The Query Param is being arbitrarily limited in length here. It is also applied when estimating the size of the payload in getPayloadSize()
387
389
  }, _constants.QUERY_PARAM_PADDING).substring(1) // remove the leading '&'
388
390
  },
@@ -17,6 +17,7 @@ var _drain = require("../../../common/drain/drain");
17
17
  var _runtime2 = require("../../../common/constants/runtime");
18
18
  var _constants2 = require("../../../common/session/constants");
19
19
  var _traverse = require("../../../common/util/traverse");
20
+ var _cleanUrl = require("../../../common/url/clean-url");
20
21
  const ERROR_MODE_SECONDS_WINDOW = 30 * 1000; // sliding window of nodes to track when simply monitoring (but not harvesting) in error mode
21
22
  /** Reserved room for query param attrs */
22
23
  const QUERY_PARAM_PADDING = 5000;
@@ -65,6 +66,11 @@ class Aggregate extends _aggregateBase.AggregateBase {
65
66
  // if another page's session entity has expired, or another page has transitioned to off and this one hasn't... we can just abort straight away here
66
67
  if (this.sessionId !== sessionState.value || eventType === 'cross-tab' && this.scheduler?.started && sessionState.sessionTraceMode === _constants2.MODE.OFF) this.abort(2);
67
68
  });
69
+ if (typeof PerformanceNavigationTiming !== 'undefined') {
70
+ this.traceStorage.storeTiming(_runtime2.globalScope.performance?.getEntriesByType?.('navigation')[0]);
71
+ } else {
72
+ this.traceStorage.storeTiming(_runtime2.globalScope.performance?.timing, true);
73
+ }
68
74
  }
69
75
 
70
76
  /** ST/SR sampling flow in BCS - https://drive.google.com/file/d/19hwt2oft-8Hh4RrjpLqEXfpP_9wYBLcq/view?usp=sharing */
@@ -90,11 +96,6 @@ class Aggregate extends _aggregateBase.AggregateBase {
90
96
  (0, _registerHandler.registerHandler)('bstApi', (...args) => this.traceStorage.storeSTN(...args), this.featureName, this.ee);
91
97
  (0, _registerHandler.registerHandler)('trace-jserror', (...args) => this.traceStorage.storeErrorAgg(...args), this.featureName, this.ee);
92
98
  (0, _registerHandler.registerHandler)('pvtAdded', (...args) => this.traceStorage.processPVT(...args), this.featureName, this.ee);
93
- if (typeof PerformanceNavigationTiming !== 'undefined') {
94
- this.traceStorage.storeTiming(_runtime2.globalScope.performance?.getEntriesByType?.('navigation')[0]);
95
- } else {
96
- this.traceStorage.storeTiming(_runtime2.globalScope.performance?.timing, true);
97
- }
98
99
 
99
100
  /** Only start actually harvesting if running in full mode at init time */
100
101
  if (this.mode === _constants2.MODE.FULL) this.startHarvesting();else {
@@ -156,7 +157,7 @@ class Aggregate extends _aggregateBase.AggregateBase {
156
157
  type: 'BrowserSessionChunk',
157
158
  app_id: this.agentInfo.applicationID,
158
159
  protocol_version: '0',
159
- timestamp: Math.floor(this.timeKeeper.correctAbsoluteTimestamp(this.timeKeeper.convertRelativeTimestamp(earliestTimeStamp))),
160
+ timestamp: Math.floor(this.timeKeeper.correctRelativeTimestamp(earliestTimeStamp)),
160
161
  attributes: (0, _encode.obj)({
161
162
  ...(agentMetadata.entityGuid && {
162
163
  entityGuid: agentMetadata.entityGuid
@@ -165,8 +166,8 @@ class Aggregate extends _aggregateBase.AggregateBase {
165
166
  // this section of attributes must be controllable and stay below the query param padding limit -- see QUERY_PARAM_PADDING
166
167
  // if not, data could be lost to truncation at time of sending, potentially breaking parsing / API behavior in NR1
167
168
  // trace payload metadata
168
- 'trace.firstTimestamp': Math.floor(this.timeKeeper.correctAbsoluteTimestamp(this.timeKeeper.convertRelativeTimestamp(earliestTimeStamp))),
169
- 'trace.lastTimestamp': Math.floor(this.timeKeeper.correctAbsoluteTimestamp(this.timeKeeper.convertRelativeTimestamp(latestTimeStamp))),
169
+ 'trace.firstTimestamp': Math.floor(this.timeKeeper.correctRelativeTimestamp(earliestTimeStamp)),
170
+ 'trace.lastTimestamp': Math.floor(this.timeKeeper.correctRelativeTimestamp(latestTimeStamp)),
170
171
  'trace.nodes': stns.length,
171
172
  'trace.originTimestamp': this.timeKeeper.correctedOriginTime,
172
173
  // other payload metadata
@@ -182,7 +183,8 @@ class Aggregate extends _aggregateBase.AggregateBase {
182
183
  // customer-defined data should go last so that if it exceeds the query param padding limit it will be truncated instead of important attrs
183
184
  ...(endUserId && {
184
185
  'enduser.id': this.obfuscator.obfuscateString(endUserId)
185
- })
186
+ }),
187
+ currentUrl: this.obfuscator.obfuscateString((0, _cleanUrl.cleanURL)('' + location))
186
188
  // The Query Param is being arbitrarily limited in length here. It is also applied when estimating the size of the payload in getPayloadSize()
187
189
  }, QUERY_PARAM_PADDING).substring(1) // remove the leading '&'
188
190
  },
@@ -36,6 +36,10 @@ const {
36
36
  CB_START,
37
37
  FN_END
38
38
  } = CONSTANTS;
39
+
40
+ /**
41
+ * @deprecated This feature has been deprecated, in favor of `soft_navigations`, which is in limited preview. Consider using/importing `SoftNavigations` instead. To gain access to the limited preview, please see https://docs.newrelic.com/docs/browser/single-page-app-monitoring/get-started/browser-spa-v2/ for more information. This feature will be removed in a future release.
42
+ */
39
43
  class Instrument extends _instrumentBase.InstrumentBase {
40
44
  static featureName = FEATURE_NAME;
41
45
  constructor(agentIdentifier, aggregator, auto = true) {
@@ -176,6 +176,7 @@ class AgentBase {
176
176
  * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/interaction/}
177
177
  * @returns {InteractionInstance} An API object that is bound to a specific BrowserInteraction event. Each time this method is called for the same BrowserInteraction, a new object is created, but it still references the same interaction.
178
178
  * - Note: Does not apply to MicroAgent
179
+ * - Deprecation Notice: interaction.createTracer is deprecated. See https://docs.newrelic.com/eol/2024/04/eol-04-24-24-createtracer/ for more information.
179
180
  */
180
181
  interaction() {
181
182
  return this.#callMethod('interaction');
@@ -20,7 +20,7 @@ var _agentBase = require("./agent-base");
20
20
  function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
21
21
  function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } // loader files
22
22
  // core files
23
- const nonAutoFeatures = [_features.FEATURE_NAMES.jserrors, _features.FEATURE_NAMES.genericEvents, _features.FEATURE_NAMES.metrics];
23
+ const nonAutoFeatures = [_features.FEATURE_NAMES.jserrors, _features.FEATURE_NAMES.genericEvents, _features.FEATURE_NAMES.metrics, _features.FEATURE_NAMES.logging];
24
24
 
25
25
  /**
26
26
  * A minimal agent class designed to only respond to manual user input. As such, this class does not
@@ -72,6 +72,9 @@ const model = () => {
72
72
  page_action: {
73
73
  enabled: true
74
74
  },
75
+ user_actions: {
76
+ enabled: true
77
+ },
75
78
  page_view_event: {
76
79
  enabled: true,
77
80
  autoStart: true
@@ -6,7 +6,7 @@
6
6
  /**
7
7
  * Exposes the version of the agent
8
8
  */
9
- export const VERSION = "1.267.0";
9
+ export const VERSION = "1.269.0";
10
10
 
11
11
  /**
12
12
  * Exposes the build type of the agent
@@ -6,7 +6,7 @@
6
6
  /**
7
7
  * Exposes the version of the agent
8
8
  */
9
- export const VERSION = "1.267.0";
9
+ export const VERSION = "1.269.0";
10
10
 
11
11
  /**
12
12
  * Exposes the build type of the agent
@@ -0,0 +1,4 @@
1
+ export function isIFrameWindow(windowObject) {
2
+ if (!windowObject) return false;
3
+ return windowObject.self !== windowObject.top;
4
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Generates a CSS selector path for the given element, if possible
3
+ * @param {HTMLElement} elem
4
+ * @param {boolean} includeId
5
+ * @param {boolean} includeClass
6
+ * @returns {string|undefined}
7
+ */
8
+ export const generateSelectorPath = elem => {
9
+ if (!elem) return;
10
+ const getNthOfTypeIndex = node => {
11
+ try {
12
+ let i = 1;
13
+ const {
14
+ tagName
15
+ } = node;
16
+ while (node.previousElementSibling) {
17
+ if (node.previousElementSibling.tagName === tagName) i++;
18
+ node = node.previousElementSibling;
19
+ }
20
+ return i;
21
+ } catch (err) {
22
+ // do nothing for now. An invalid child count will make the path selector not return a nth-of-type selector statement
23
+ }
24
+ };
25
+ let pathSelector = '';
26
+ let index = getNthOfTypeIndex(elem);
27
+ try {
28
+ while (elem?.tagName) {
29
+ const {
30
+ id,
31
+ localName
32
+ } = elem;
33
+ const selector = [localName, id ? "#".concat(id) : '', pathSelector ? ">".concat(pathSelector) : ''].join('');
34
+ pathSelector = selector;
35
+ elem = elem.parentNode;
36
+ }
37
+ } catch (err) {
38
+ // do nothing for now
39
+ }
40
+ return pathSelector ? index ? "".concat(pathSelector, ":nth-of-type(").concat(index, ")") : pathSelector : undefined;
41
+ };
@@ -1,32 +1,9 @@
1
- import { globalScope } from '../constants/runtime';
2
-
3
- /*
4
- * See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#safely_detecting_option_support
5
- */
6
- let passiveSupported = false;
7
- let signalSupported = false;
8
- try {
9
- const options = {
10
- get passive() {
11
- // this function will be called when the browser attempts to access the passive property
12
- passiveSupported = true;
13
- return false;
14
- },
15
- get signal() {
16
- signalSupported = true;
17
- return false;
18
- }
19
- };
20
- globalScope.addEventListener('test', null, options);
21
- globalScope.removeEventListener('test', null, options);
22
- } catch (err) {}
23
1
  export function eventListenerOpts(useCapture, abortSignal) {
24
- return passiveSupported || signalSupported ? {
25
- capture: !!useCapture,
26
- passive: passiveSupported,
27
- // passive defaults to false
2
+ return {
3
+ capture: useCapture,
4
+ passive: false,
28
5
  signal: abortSignal
29
- } : !!useCapture; // mainly just IE11 doesn't support third param options under EventTarget API
6
+ };
30
7
  }
31
8
 
32
9
  /** Do not use this within the worker context. */
@@ -102,6 +102,15 @@ export class TimeKeeper {
102
102
  return timestamp - this.#localTimeDiff;
103
103
  }
104
104
 
105
+ /**
106
+ * Corrects relative timestamp to NR server time (epoch).
107
+ * @param {DOMHighResTimeStamp} relativeTime
108
+ * @returns {number}
109
+ */
110
+ correctRelativeTimestamp(relativeTime) {
111
+ return this.correctAbsoluteTimestamp(this.convertRelativeTimestamp(relativeTime));
112
+ }
113
+
105
114
  /** Process the session entity and use the info to set the main time calculations if present */
106
115
  processStoredDiff() {
107
116
  if (this.#ready) return; // Time diff has already been calculated
@@ -31,7 +31,7 @@ const getCircularReplacer = () => {
31
31
  */
32
32
  export function stringify(val) {
33
33
  try {
34
- return JSON.stringify(val, getCircularReplacer());
34
+ return JSON.stringify(val, getCircularReplacer()) ?? '';
35
35
  } catch (e) {
36
36
  try {
37
37
  ee.emit('internal-error', [e]);
@@ -6,10 +6,10 @@ import { stringify } from '../../../common/util/stringify';
6
6
  import { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';
7
7
  import { cleanURL } from '../../../common/url/clean-url';
8
8
  import { getInfo } from '../../../common/config/info';
9
- import { getConfigurationValue } from '../../../common/config/init';
9
+ import { getConfiguration } from '../../../common/config/init';
10
10
  import { getRuntime } from '../../../common/config/runtime';
11
11
  import { FEATURE_NAME } from '../constants';
12
- import { isBrowserScope } from '../../../common/constants/runtime';
12
+ import { initialLocation, isBrowserScope } from '../../../common/constants/runtime';
13
13
  import { AggregateBase } from '../../utils/aggregate-base';
14
14
  import { warn } from '../../../common/util/console';
15
15
  import { now } from '../../../common/timing/now';
@@ -19,13 +19,16 @@ import { SUPPORTABILITY_METRIC_CHANNEL } from '../../metrics/constants';
19
19
  import { EventBuffer } from '../../utils/event-buffer';
20
20
  import { applyFnToProps } from '../../../common/util/traverse';
21
21
  import { IDEAL_PAYLOAD_SIZE } from '../../../common/constants/agent-constants';
22
+ import { UserActionsAggregator } from './user-actions/user-actions-aggregator';
23
+ import { isIFrameWindow } from '../../../common/dom/iframe';
22
24
  export class Aggregate extends AggregateBase {
23
25
  #agentRuntime;
24
26
  static featureName = FEATURE_NAME;
25
27
  constructor(agentIdentifier, aggregator) {
26
28
  super(agentIdentifier, aggregator, FEATURE_NAME);
29
+ const agentInit = getConfiguration(this.agentIdentifier);
27
30
  this.eventsPerHarvest = 1000;
28
- this.harvestTimeSeconds = getConfigurationValue(this.agentIdentifier, 'generic_events.harvestTimeSeconds');
31
+ this.harvestTimeSeconds = agentInit.generic_events.harvestTimeSeconds;
29
32
  this.referrerUrl = isBrowserScope && document.referrer ? cleanURL(document.referrer) : undefined;
30
33
  this.events = new EventBuffer();
31
34
  this.#agentRuntime = getRuntime(this.agentIdentifier);
@@ -35,16 +38,16 @@ export class Aggregate extends AggregateBase {
35
38
  deregisterDrain(this.agentIdentifier, this.featureName);
36
39
  return;
37
40
  }
38
- if (getConfigurationValue(this.agentIdentifier, 'page_action.enabled')) {
41
+ const preHarvestMethods = [];
42
+ if (agentInit.page_action.enabled) {
39
43
  registerHandler('api-addPageAction', (timestamp, name, attributes) => {
40
44
  this.addEvent({
41
45
  ...attributes,
42
46
  eventType: 'PageAction',
43
- timestamp: Math.floor(this.#agentRuntime.timeKeeper.correctAbsoluteTimestamp(this.#agentRuntime.timeKeeper.convertRelativeTimestamp(timestamp))),
47
+ timestamp: Math.floor(this.#agentRuntime.timeKeeper.correctRelativeTimestamp(timestamp)),
44
48
  timeSinceLoad: timestamp / 1000,
45
49
  actionName: name,
46
50
  referrerUrl: this.referrerUrl,
47
- currentUrl: cleanURL('' + location),
48
51
  ...(isBrowserScope && {
49
52
  browserWidth: window.document.documentElement?.clientWidth,
50
53
  browserHeight: window.document.documentElement?.clientHeight
@@ -52,16 +55,83 @@ export class Aggregate extends AggregateBase {
52
55
  });
53
56
  }, this.featureName, this.ee);
54
57
  }
58
+ if (isBrowserScope && agentInit.user_actions.enabled) {
59
+ this.userActionAggregator = new UserActionsAggregator();
60
+ this.addUserAction = aggregatedUserAction => {
61
+ try {
62
+ /** The aggregator process only returns an event when it is "done" aggregating -
63
+ * so we still need to validate that an event was given to this method before we try to add */
64
+ if (aggregatedUserAction?.event) {
65
+ const {
66
+ target,
67
+ timeStamp,
68
+ type
69
+ } = aggregatedUserAction.event;
70
+ this.addEvent({
71
+ eventType: 'UserAction',
72
+ timestamp: Math.floor(this.#agentRuntime.timeKeeper.correctRelativeTimestamp(timeStamp)),
73
+ action: type,
74
+ actionCount: aggregatedUserAction.count,
75
+ actionDuration: aggregatedUserAction.relativeMs[aggregatedUserAction.relativeMs.length - 1],
76
+ actionMs: aggregatedUserAction.relativeMs,
77
+ rageClick: aggregatedUserAction.rageClick,
78
+ target: aggregatedUserAction.selectorPath,
79
+ ...(isIFrameWindow(window) && {
80
+ iframe: true
81
+ }),
82
+ ...(target?.id && {
83
+ targetId: target.id
84
+ }),
85
+ ...(target?.tagName && {
86
+ targetTag: target.tagName
87
+ }),
88
+ ...(target?.type && {
89
+ targetType: target.type
90
+ }),
91
+ ...(target?.className && {
92
+ targetClass: target.className
93
+ })
94
+ });
95
+ }
96
+ } catch (e) {
97
+ // do nothing for now
98
+ }
99
+ };
100
+ registerHandler('ua', evt => {
101
+ /** the processor will return the previously aggregated event if it has been completed by processing the current event */
102
+ this.addUserAction(this.userActionAggregator.process(evt));
103
+ }, this.featureName, this.ee);
104
+ preHarvestMethods.push((options = {}) => {
105
+ /** send whatever UserActions have been aggregated up to this point
106
+ * if we are in a final harvest. By accessing the aggregationEvent, the aggregation is then force-cleared */
107
+ if (options.isFinalHarvest) this.addUserAction(this.userActionAggregator.aggregationEvent);
108
+ });
109
+ }
55
110
  this.harvestScheduler = new HarvestScheduler('ins', {
56
111
  onFinished: (...args) => this.onHarvestFinished(...args)
57
112
  }, this);
58
- this.harvestScheduler.harvest.on('ins', (...args) => this.onHarvestStarted(...args));
113
+ this.harvestScheduler.harvest.on('ins', (...args) => {
114
+ preHarvestMethods.forEach(fn => fn(...args));
115
+ return this.onHarvestStarted(...args);
116
+ });
59
117
  this.harvestScheduler.startTimer(this.harvestTimeSeconds, 0);
60
118
  this.drain();
61
119
  });
62
120
  }
63
121
 
64
122
  // WARNING: Insights times are in seconds. EXCEPT timestamp, which is in ms.
123
+ /** Some keys are set by the query params or request headers sent with the harvest and override the body values, so check those before adding new standard body values...
124
+ * see harvest.js#baseQueryString for more info on the query params
125
+ * Notably:
126
+ * * name: set by the `t=` query param
127
+ * * appId: set by the `a=` query param
128
+ * * standalone: set by the `sa=` query param
129
+ * * session: set by the `s=` query param
130
+ * * sessionTraceId: set by the `ptid=` query param
131
+ * * userAgent*: set by the userAgent header
132
+ * @param {object=} obj the event object for storing in the event buffer
133
+ * @returns void
134
+ */
65
135
  addEvent(obj = {}) {
66
136
  if (!obj || !Object.keys(obj).length) return;
67
137
  if (!obj.eventType) {
@@ -74,9 +144,10 @@ export class Aggregate extends AggregateBase {
74
144
  }
75
145
  const defaultEventAttributes = {
76
146
  /** should be overridden by the event-specific attributes, but just in case -- set it to now() */
77
- timestamp: Math.floor(this.#agentRuntime.timeKeeper.correctAbsoluteTimestamp(this.#agentRuntime.timeKeeper.convertRelativeTimestamp(now()))),
78
- /** all generic events require a pageUrl */
79
- pageUrl: cleanURL(getRuntime(this.agentIdentifier).origin)
147
+ timestamp: Math.floor(this.#agentRuntime.timeKeeper.correctRelativeTimestamp(now())),
148
+ /** all generic events require pageUrl(s) */
149
+ pageUrl: cleanURL('' + initialLocation),
150
+ currentUrl: cleanURL('' + location)
80
151
  };
81
152
  const eventAttributes = {
82
153
  /** Agent-level custom attributes */
@@ -104,7 +175,7 @@ export class Aggregate extends AggregateBase {
104
175
  ins: this.events.buffer
105
176
  }, this.obfuscator.obfuscateString.bind(this.obfuscator), 'string')
106
177
  };
107
- if (options.retry) this.events.hold();
178
+ if (options.retry) this.events.hold();else this.events.clear();
108
179
  return payload;
109
180
  }
110
181
  onHarvestFinished(result) {
@@ -0,0 +1,32 @@
1
+ import { RAGE_CLICK_THRESHOLD_EVENTS, RAGE_CLICK_THRESHOLD_MS } from '../../constants';
2
+ export class AggregatedUserAction {
3
+ constructor(evt, selectorPath) {
4
+ this.event = evt;
5
+ this.count = 1;
6
+ this.originMs = Math.floor(evt.timeStamp);
7
+ this.relativeMs = [0];
8
+ this.selectorPath = selectorPath;
9
+ this.rageClick = undefined;
10
+ }
11
+
12
+ /**
13
+ * Aggregates the count and maintains the relative MS array for matching events
14
+ * Will determine if a rage click was observed as part of the aggregation
15
+ * @param {Event} evt
16
+ * @returns {void}
17
+ */
18
+ aggregate(evt) {
19
+ this.count++;
20
+ this.relativeMs.push(Math.floor(evt.timeStamp - this.originMs));
21
+ if (this.isRageClick()) this.rageClick = true;
22
+ }
23
+
24
+ /**
25
+ * Determines if the current set of relative ms values constitutes a rage click
26
+ * @returns {boolean}
27
+ */
28
+ isRageClick() {
29
+ const len = this.relativeMs.length;
30
+ return this.event.type === 'click' && len >= RAGE_CLICK_THRESHOLD_EVENTS && this.relativeMs[len - 1] - this.relativeMs[len - RAGE_CLICK_THRESHOLD_EVENTS] < RAGE_CLICK_THRESHOLD_MS;
31
+ }
32
+ }
@@ -0,0 +1,70 @@
1
+ import { generateSelectorPath } from '../../../../common/dom/selector-path';
2
+ import { OBSERVED_WINDOW_EVENTS } from '../../constants';
3
+ import { AggregatedUserAction } from './aggregated-user-action';
4
+ export class UserActionsAggregator {
5
+ /** @type {AggregatedUserAction=} */
6
+ #aggregationEvent = undefined;
7
+ #aggregationKey = '';
8
+ get aggregationEvent() {
9
+ // if this is accessed externally, we need to be done aggregating on it
10
+ // to prevent potential mutability and duplication issues, so the state is cleared upon returning.
11
+ // This value may need to be accessed during an unload harvest.
12
+ const finishedEvent = this.#aggregationEvent;
13
+ this.#aggregationKey = '';
14
+ this.#aggregationEvent = undefined;
15
+ return finishedEvent;
16
+ }
17
+
18
+ /**
19
+ * Process the event and determine if a new aggregation set should be made or if it should increment the current aggregation
20
+ * @param {Event} evt The event supplied by the addEventListener callback
21
+ * @returns {AggregatedUserAction|undefined} The previous aggregation set if it has been completed by processing the current event
22
+ */
23
+ process(evt) {
24
+ if (!evt) return;
25
+ const selectorPath = getSelectorPath(evt);
26
+ const aggregationKey = getAggregationKey(evt, selectorPath);
27
+ if (!!aggregationKey && aggregationKey === this.#aggregationKey) {
28
+ // an aggregation exists already, so lets just continue to increment
29
+ this.#aggregationEvent.aggregate(evt);
30
+ } else {
31
+ // return the prev existing one (if there is one)
32
+ const finishedEvent = this.#aggregationEvent;
33
+ // then set as this new event aggregation
34
+ this.#aggregationKey = aggregationKey;
35
+ this.#aggregationEvent = new AggregatedUserAction(evt, selectorPath);
36
+ return finishedEvent;
37
+ }
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Generates a selector path for the event, starting with simple cases like window or document and getting more complex for dom-tree traversals as needed.
43
+ * Will return a random selector path value if no other path can be determined, to force the aggregator to skip aggregation for this event.
44
+ * @param {Event} evt
45
+ * @returns {string}
46
+ */
47
+ function getSelectorPath(evt) {
48
+ let selectorPath;
49
+ if (OBSERVED_WINDOW_EVENTS.includes(evt.type) || evt.target === window) selectorPath = 'window';else if (evt.target === document) selectorPath = 'document';
50
+ // if still no selectorPath, generate one from target tree that includes elem ids
51
+ else selectorPath = generateSelectorPath(evt.target);
52
+ // if STILL no selectorPath, it will return undefined which will skip aggregation for this event
53
+ return selectorPath;
54
+ }
55
+
56
+ /**
57
+ * Returns an aggregation key based on the event type and the selector path of the event's target.
58
+ * Scrollend events are aggregated into one set, no matter what.
59
+ * @param {Event} evt
60
+ * @param {string} selectorPath
61
+ * @returns {string}
62
+ */
63
+ function getAggregationKey(evt, selectorPath) {
64
+ let aggregationKey = evt.type;
65
+ /** aggregate all scrollends into one set (if sequential), no matter what their target is
66
+ * the aggregation group's selector path with be reflected as the first one observed
67
+ * due to the way the aggregation logic works (by storing the initial value and aggregating it) */
68
+ if (evt.type !== 'scrollend') aggregationKey += '-' + selectorPath;
69
+ return aggregationKey;
70
+ }
@@ -1,4 +1,8 @@
1
1
  import { FEATURE_NAMES } from '../../loaders/features/features';
2
2
  export const FEATURE_NAME = FEATURE_NAMES.genericEvents;
3
3
  export const IDEAL_PAYLOAD_SIZE = 64000;
4
- export const MAX_PAYLOAD_SIZE = 1000000;
4
+ export const MAX_PAYLOAD_SIZE = 1000000;
5
+ export const OBSERVED_EVENTS = ['auxclick', 'click', 'copy', 'keydown', 'paste', 'scrollend'];
6
+ export const OBSERVED_WINDOW_EVENTS = ['focus', 'blur'];
7
+ export const RAGE_CLICK_THRESHOLD_EVENTS = 4;
8
+ export const RAGE_CLICK_THRESHOLD_MS = 1000;
@@ -2,17 +2,28 @@
2
2
  * SPDX-License-Identifier: Apache-2.0
3
3
  */
4
4
 
5
- import { getConfigurationValue } from '../../../common/config/init';
5
+ import { getConfiguration } from '../../../common/config/init';
6
+ import { isBrowserScope } from '../../../common/constants/runtime';
6
7
  import { deregisterDrain } from '../../../common/drain/drain';
8
+ import { handle } from '../../../common/event-emitter/handle';
9
+ import { windowAddEventListener } from '../../../common/event-listener/event-listener-opts';
7
10
  import { InstrumentBase } from '../../utils/instrument-base';
8
- import { FEATURE_NAME } from '../constants';
11
+ import { FEATURE_NAME, OBSERVED_EVENTS, OBSERVED_WINDOW_EVENTS } from '../constants';
9
12
  export class Instrument extends InstrumentBase {
10
13
  static featureName = FEATURE_NAME;
11
14
  constructor(agentIdentifier, aggregator, auto = true) {
12
15
  super(agentIdentifier, aggregator, FEATURE_NAME, auto);
13
- const genericEventSourceConfigs = [getConfigurationValue(this.agentIdentifier, 'page_action.enabled')
16
+ const agentInit = getConfiguration(this.agentIdentifier);
17
+ const genericEventSourceConfigs = [agentInit.page_action.enabled, agentInit.user_actions.enabled
14
18
  // other future generic event source configs to go here, like M&Ms, PageResouce, etc.
15
19
  ];
20
+ if (isBrowserScope && agentInit.user_actions.enabled) {
21
+ OBSERVED_EVENTS.forEach(eventType => windowAddEventListener(eventType, evt => handle('ua', [evt], undefined, this.featureName, this.ee), true));
22
+ OBSERVED_WINDOW_EVENTS.forEach(eventType => windowAddEventListener(eventType, evt => handle('ua', [evt], undefined, this.featureName, this.ee))
23
+ // Capture is not used here so that we don't get element focus/blur events, only the window's as they do not bubble. They are also not cancellable, so no worries about being front of line.
24
+ );
25
+ }
26
+
16
27
  /** If any of the sources are active, import the aggregator. otherwise deregister */
17
28
  if (genericEventSourceConfigs.some(x => x)) this.importAggregator();else deregisterDrain(this.agentIdentifier, this.featureName);
18
29
  }