clarity-js 0.7.70 → 0.8.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 (102) hide show
  1. package/README.md +26 -26
  2. package/build/clarity.extended.js +1 -1
  3. package/build/clarity.insight.js +1 -1
  4. package/build/clarity.js +5479 -5477
  5. package/build/clarity.min.js +1 -1
  6. package/build/clarity.module.js +5479 -5477
  7. package/build/clarity.performance.js +1 -1
  8. package/package.json +70 -70
  9. package/rollup.config.ts +98 -98
  10. package/src/clarity.ts +60 -60
  11. package/src/core/api.ts +8 -8
  12. package/src/core/config.ts +32 -32
  13. package/src/core/copy.ts +3 -3
  14. package/src/core/event.ts +30 -30
  15. package/src/core/hash.ts +19 -19
  16. package/src/core/history.ts +73 -73
  17. package/src/core/index.ts +83 -83
  18. package/src/core/measure.ts +19 -19
  19. package/src/core/report.ts +28 -28
  20. package/src/core/scrub.ts +196 -196
  21. package/src/core/task.ts +180 -180
  22. package/src/core/time.ts +19 -19
  23. package/src/core/timeout.ts +10 -10
  24. package/src/core/version.ts +2 -2
  25. package/src/data/baseline.ts +155 -155
  26. package/src/data/compress.ts +31 -31
  27. package/src/data/consent.ts +20 -20
  28. package/src/data/custom.ts +23 -23
  29. package/src/data/dimension.ts +53 -53
  30. package/src/data/encode.ts +140 -140
  31. package/src/data/envelope.ts +53 -53
  32. package/src/data/extract.ts +204 -204
  33. package/src/data/index.ts +46 -46
  34. package/src/data/limit.ts +44 -44
  35. package/src/data/metadata.ts +356 -356
  36. package/src/data/metric.ts +51 -51
  37. package/src/data/ping.ts +36 -36
  38. package/src/data/signal.ts +30 -30
  39. package/src/data/summary.ts +34 -34
  40. package/src/data/token.ts +39 -39
  41. package/src/data/upgrade.ts +37 -37
  42. package/src/data/upload.ts +283 -283
  43. package/src/data/variable.ts +83 -83
  44. package/src/diagnostic/encode.ts +40 -40
  45. package/src/diagnostic/fraud.ts +36 -36
  46. package/src/diagnostic/index.ts +15 -15
  47. package/src/diagnostic/internal.ts +28 -28
  48. package/src/diagnostic/script.ts +37 -37
  49. package/src/global.ts +6 -6
  50. package/src/index.ts +9 -9
  51. package/src/insight/blank.ts +14 -14
  52. package/src/insight/encode.ts +60 -60
  53. package/src/insight/snapshot.ts +114 -114
  54. package/src/interaction/change.ts +40 -40
  55. package/src/interaction/click.ts +162 -162
  56. package/src/interaction/clipboard.ts +34 -34
  57. package/src/interaction/encode.ts +193 -193
  58. package/src/interaction/index.ts +59 -59
  59. package/src/interaction/input.ts +59 -59
  60. package/src/interaction/pointer.ts +139 -139
  61. package/src/interaction/resize.ts +47 -47
  62. package/src/interaction/scroll.ts +124 -124
  63. package/src/interaction/selection.ts +68 -68
  64. package/src/interaction/submit.ts +32 -32
  65. package/src/interaction/timeline.ts +65 -65
  66. package/src/interaction/unload.ts +28 -28
  67. package/src/interaction/visibility.ts +26 -26
  68. package/src/layout/animation.ts +133 -133
  69. package/src/layout/discover.ts +31 -31
  70. package/src/layout/document.ts +48 -48
  71. package/src/layout/dom.ts +414 -414
  72. package/src/layout/encode.ts +147 -145
  73. package/src/layout/index.ts +41 -41
  74. package/src/layout/mutation.ts +412 -412
  75. package/src/layout/node.ts +264 -264
  76. package/src/layout/offset.ts +19 -19
  77. package/src/layout/region.ts +153 -153
  78. package/src/layout/schema.ts +63 -63
  79. package/src/layout/selector.ts +82 -82
  80. package/src/layout/style.ts +150 -150
  81. package/src/layout/target.ts +32 -32
  82. package/src/layout/traverse.ts +27 -27
  83. package/src/performance/blank.ts +7 -7
  84. package/src/performance/encode.ts +31 -31
  85. package/src/performance/index.ts +14 -14
  86. package/src/performance/interaction.ts +125 -125
  87. package/src/performance/navigation.ts +31 -31
  88. package/src/performance/observer.ts +108 -108
  89. package/src/queue.ts +33 -33
  90. package/test/core.test.ts +139 -139
  91. package/test/helper.ts +162 -162
  92. package/test/html/core.html +27 -27
  93. package/test/tsconfig.test.json +5 -5
  94. package/tsconfig.json +21 -21
  95. package/tslint.json +32 -32
  96. package/types/core.d.ts +154 -154
  97. package/types/data.d.ts +510 -510
  98. package/types/diagnostic.d.ts +24 -24
  99. package/types/index.d.ts +39 -39
  100. package/types/interaction.d.ts +165 -165
  101. package/types/layout.d.ts +273 -273
  102. package/types/performance.d.ts +64 -64
@@ -1,412 +1,412 @@
1
- import { Priority, Task, Timer } from "@clarity-types/core";
2
- import { Code, Event, Metric, Severity } from "@clarity-types/data";
3
- import { Constant, MutationHistory, MutationRecordWithTime, MutationQueue, Setting, Source } from "@clarity-types/layout";
4
- import { FunctionNames } from "@clarity-types/performance";
5
- import api from "@src/core/api";
6
- import * as core from "@src/core";
7
- import { bind } from "@src/core/event";
8
- import measure from "@src/core/measure";
9
- import * as task from "@src/core/task";
10
- import { time } from "@src/core/time";
11
- import { clearTimeout, setTimeout } from "@src/core/timeout";
12
- import { id } from "@src/data/metadata";
13
- import * as summary from "@src/data/summary";
14
- import * as internal from "@src/diagnostic/internal";
15
- import * as doc from "@src/layout/document";
16
- import * as dom from "@src/layout/dom";
17
- import * as metric from "@src/data/metric";
18
- import encode from "@src/layout/encode";
19
- import * as region from "@src/layout/region";
20
- import traverse from "@src/layout/traverse";
21
- import processNode from "./node";
22
- import config from "@src/core/config";
23
-
24
- let observers: MutationObserver[] = [];
25
- let mutations: MutationQueue[] = [];
26
- let throttledMutations: { [key: number]: MutationRecordWithTime } = {};
27
- let insertRule: (rule: string, index?: number) => number = null;
28
- let deleteRule: (index?: number) => void = null;
29
- let attachShadow: (init: ShadowRootInit) => ShadowRoot = null;
30
- let mediaInsertRule: (rule: string, index?: number) => number = null;
31
- let mediaDeleteRule: (index?: number) => void = null;
32
- let queue: Node[] = [];
33
- let timeout: number = null;
34
- let throttleDelay: number = null;
35
- let activePeriod = null;
36
- let history: MutationHistory = {};
37
- let criticalPeriod = null;
38
- let observedNodes: WeakMap<Node, MutationObserver> = new WeakMap<Node, MutationObserver>();
39
-
40
- // We ignore mutations if these attributes are updated
41
- const IGNORED_ATTRIBUTES = ["data-google-query-id", "data-load-complete", "data-google-container-id"];
42
-
43
- export function start(): void {
44
- start.dn = FunctionNames.MutationStart;
45
- observers = [];
46
- queue = [];
47
- timeout = null;
48
- activePeriod = 0;
49
- history = {};
50
- criticalPeriod = 0;
51
- observedNodes = new WeakMap<Node, MutationObserver>();
52
-
53
- // Some popular open source libraries, like styled-components, optimize performance
54
- // by injecting CSS using insertRule API vs. appending text node. A side effect of
55
- // using javascript API is that it doesn't trigger DOM mutation and therefore we
56
- // need to override the insertRule API and listen for changes manually.
57
- if (insertRule === null) {
58
- insertRule = CSSStyleSheet.prototype.insertRule;
59
- CSSStyleSheet.prototype.insertRule = function (): number {
60
- if (core.active()) {
61
- schedule(this.ownerNode);
62
- }
63
- return insertRule.apply(this, arguments);
64
- };
65
- }
66
-
67
- if ("CSSMediaRule" in window && mediaInsertRule === null) {
68
- mediaInsertRule = CSSMediaRule.prototype.insertRule;
69
- CSSMediaRule.prototype.insertRule = function (): number {
70
- if (core.active()) {
71
- schedule(this.parentStyleSheet.ownerNode);
72
- }
73
- return mediaInsertRule.apply(this, arguments);
74
- };
75
- }
76
-
77
- if (deleteRule === null) {
78
- deleteRule = CSSStyleSheet.prototype.deleteRule;
79
- CSSStyleSheet.prototype.deleteRule = function (): void {
80
- if (core.active()) {
81
- schedule(this.ownerNode);
82
- }
83
- return deleteRule.apply(this, arguments);
84
- };
85
- }
86
-
87
- if ("CSSMediaRule" in window && mediaDeleteRule === null) {
88
- mediaDeleteRule = CSSMediaRule.prototype.deleteRule;
89
- CSSMediaRule.prototype.deleteRule = function (): void {
90
- if (core.active()) {
91
- schedule(this.parentStyleSheet.ownerNode);
92
- }
93
- return mediaDeleteRule.apply(this, arguments);
94
- };
95
- }
96
-
97
- // Add a hook to attachShadow API calls
98
- // In case we are unable to add a hook and browser throws an exception,
99
- // reset attachShadow variable and resume processing like before
100
- if (attachShadow === null) {
101
- attachShadow = Element.prototype.attachShadow;
102
- try {
103
- Element.prototype.attachShadow = function (): ShadowRoot {
104
- if (core.active()) {
105
- return schedule(attachShadow.apply(this, arguments)) as ShadowRoot;
106
- } else {
107
- return attachShadow.apply(this, arguments);
108
- }
109
- };
110
- } catch {
111
- attachShadow = null;
112
- }
113
- }
114
- }
115
-
116
- export function observe(node: Node): void {
117
- // Create a new observer for every time a new DOM tree (e.g. root document or shadowdom root) is discovered on the page
118
- // In the case of shadow dom, any mutations that happen within the shadow dom are not bubbled up to the host document
119
- // For this reason, we need to wire up mutations every time we see a new shadow dom.
120
- // Also, wrap it inside a try / catch. In certain browsers (e.g. legacy Edge), observer on shadow dom can throw errors
121
- try {
122
- // Cleanup old observer if present.
123
- if (observedNodes.has(node)) {
124
- observedNodes.get(node)?.disconnect();
125
- }
126
-
127
- let m = api(Constant.MutationObserver);
128
- let observer = m in window ? new window[m](measure(handle) as MutationCallback) : null;
129
- if (observer) {
130
- observer.observe(node, { attributes: true, childList: true, characterData: true, subtree: true });
131
- observedNodes.set(node, observer);
132
- observers.push(observer);
133
- }
134
- } catch (e) {
135
- internal.log(Code.MutationObserver, Severity.Info, e ? e.name : null);
136
- }
137
- }
138
-
139
- export function monitor(frame: HTMLIFrameElement): void {
140
- // Bind to iframe's onload event so we get notified anytime there's an update to iframe content.
141
- // This includes cases where iframe location is updated without explicitly updating src attribute
142
- // E.g. iframe.contentWindow.location.href = "new-location";
143
- if (dom.has(frame) === false) {
144
- bind(frame, Constant.LoadEvent, generate.bind(this, frame, Constant.ChildList), true);
145
- }
146
- }
147
-
148
- export function stop(): void {
149
- for (let observer of observers) {
150
- if (observer) {
151
- observer.disconnect();
152
- }
153
- }
154
- observers = [];
155
- history = {};
156
- mutations = [];
157
- throttledMutations = [];
158
- queue = [];
159
- activePeriod = 0;
160
- timeout = null;
161
- criticalPeriod = 0;
162
- }
163
-
164
- export function active(): void {
165
- activePeriod = time() + Setting.MutationActivePeriod;
166
- criticalPeriod = time() + config.criticalMs;
167
- }
168
-
169
- function handle(m: MutationRecord[]): void {
170
- handle.dn = FunctionNames.MutationHandle;
171
- // Queue up mutation records for asynchronous processing
172
- let now = time();
173
- summary.track(Event.Mutation, now);
174
- mutations.push({ time: now, mutations: m });
175
- task.schedule(process, Priority.High).then((): void => {
176
- setTimeout(doc.compute);
177
- measure(region.compute)();
178
- });
179
- }
180
-
181
- async function processMutation(timer: Timer, mutation: MutationRecord, instance: number, timestamp: number): Promise<void> {
182
- let state = task.state(timer);
183
-
184
- if (state === Task.Wait) {
185
- state = await task.suspend(timer);
186
- }
187
- if (state === Task.Stop) {
188
- return;
189
- }
190
-
191
- let target = mutation.target;
192
- let type = config.throttleDom ? track(mutation, timer, instance, timestamp) : mutation.type;
193
-
194
- if (type && target && target.ownerDocument) {
195
- dom.parse(target.ownerDocument);
196
- }
197
-
198
- if (type && target && target.nodeType == Node.DOCUMENT_FRAGMENT_NODE && (target as ShadowRoot).host) {
199
- dom.parse(target as ShadowRoot);
200
- }
201
-
202
- switch (type) {
203
- case Constant.Attributes:
204
- if (IGNORED_ATTRIBUTES.indexOf(mutation.attributeName) < 0) {
205
- processNode(target, Source.Attributes, timestamp);
206
- }
207
- break;
208
- case Constant.CharacterData:
209
- processNode(target, Source.CharacterData, timestamp);
210
- break;
211
- case Constant.ChildList:
212
- processNodeList(mutation.addedNodes, Source.ChildListAdd, timer, timestamp);
213
- processNodeList(mutation.removedNodes, Source.ChildListRemove, timer, timestamp);
214
- break;
215
- case Constant.Throttle:
216
- default:
217
- break;
218
- }
219
- }
220
- async function process(): Promise<void> {
221
- let timer: Timer = { id: id(), cost: Metric.LayoutCost };
222
- task.start(timer);
223
- while (mutations.length > 0) {
224
- let record = mutations.shift();
225
- let instance = time();
226
- for (let mutation of record.mutations) {
227
- await processMutation(timer, mutation, instance, record.time);
228
- }
229
- await encode(Event.Mutation, timer, record.time);
230
- }
231
-
232
- let processedMutations = false;
233
- for (var key of Object.keys(throttledMutations)) {
234
- let throttledMutationToProcess: MutationRecordWithTime = throttledMutations[key];
235
- delete throttledMutations[key];
236
- await processMutation(timer, throttledMutationToProcess.mutation, time(), throttledMutationToProcess.timestamp);
237
- processedMutations = true;
238
- }
239
-
240
- if (Object.keys(throttledMutations).length > 0) {
241
- processThrottledMutations();
242
- }
243
-
244
- // ensure we encode the previously throttled mutations once we have finished them
245
- if (Object.keys(throttledMutations).length === 0 && processedMutations) {
246
- await encode(Event.Mutation, timer, time());
247
- }
248
-
249
- cleanHistory();
250
-
251
- task.stop(timer);
252
- }
253
-
254
- function cleanHistory(): void {
255
- let now = time();
256
- if (Object.keys(history).length > Setting.MaxMutationHistoryCount) {
257
- history = {};
258
- metric.count(Metric.HistoryClear);
259
- }
260
-
261
- for (let key of Object.keys(history)) {
262
- let h = history[key];
263
- if (now > h[1] + Setting.MaxMutationHistoryTime) {
264
- delete history[key];
265
- }
266
- }
267
- }
268
-
269
- function track(m: MutationRecord, timer: Timer, instance: number, timestamp: number): string {
270
- let value = m.target ? dom.get(m.target.parentNode) : null;
271
-
272
- // Check if the parent is already discovered and that the parent is not the document root
273
- if (value && value.data.tag !== Constant.HTML) {
274
- // calculate inactive period based on the timestamp of the mutation not when the mutation is processed
275
- let inactive = timestamp > activePeriod;
276
-
277
- // Calculate critical period based on when mutation is processed
278
- const critical = instance < criticalPeriod;
279
- let target = dom.get(m.target);
280
- let element = target && target.selector ? target.selector.join() : m.target.nodeName;
281
- let parent = value.selector ? value.selector.join() : Constant.Empty;
282
-
283
- // Check if its a low priority (e.g., ads related) element mutation happening during critical period
284
- // If the discard list is empty, we discard all mutations during critical period
285
- const lowPriMutation = config.throttleMutations && critical && (config.discard.length === 0 || config.discard.some((key) => element.includes(key)));
286
-
287
- // We use selector, instead of id, to determine the key (signature for the mutation) because in some cases
288
- // repeated mutations can cause elements to be destroyed and then recreated as new DOM nodes
289
- // In those cases, IDs will change however the selector (which is relative to DOM xPath) remains the same
290
- let key = [parent, element, m.attributeName, names(m.addedNodes), names(m.removedNodes)].join();
291
-
292
- // Initialize an entry if it doesn't already exist
293
- history[key] = key in history ? history[key] : [0, instance];
294
- let h = history[key];
295
-
296
- // Lookup any pending nodes queued up for removal, and process them now if we suspended a mutation before
297
- if (inactive === false && h[0] >= Setting.MutationSuspendThreshold) {
298
- processNodeList(h[2], Source.ChildListRemove, timer, timestamp);
299
- }
300
-
301
- // Update the counter, do not reset counter if its critical period
302
- h[0] = inactive || lowPriMutation ? (h[1] === instance ? h[0] : h[0] + 1) : 1;
303
- h[1] = instance;
304
-
305
- // Return updated mutation type based on,
306
- // 1. if we have already hit the threshold or not
307
- // 2. if its a low priority mutation happening during critical time period
308
- if (h[0] >= Setting.MutationSuspendThreshold || lowPriMutation) {
309
- // Store a reference to removedNodes so we can process them later
310
- // when we resume mutations again on user interactions
311
- h[2] = m.removedNodes;
312
- if (instance > timestamp + Setting.MutationActivePeriod) {
313
- return m.type;
314
- }
315
-
316
- if (!config.dropMutations) {
317
- // we only store the most recent mutation for a given key if it is being throttled
318
- throttledMutations[key] = { mutation: m, timestamp };
319
- }
320
-
321
- return Constant.Throttle;
322
- }
323
- }
324
- return m.type;
325
- }
326
-
327
- function names(nodes: NodeList): string {
328
- let output: string[] = [];
329
- for (let i = 0; nodes && i < nodes.length; i++) {
330
- output.push(nodes[i].nodeName);
331
- }
332
- return output.join();
333
- }
334
-
335
- async function processNodeList(list: NodeList, source: Source, timer: Timer, timestamp: number): Promise<void> {
336
- let length = list ? list.length : 0;
337
- for (let i = 0; i < length; i++) {
338
- const node = list[i];
339
- if (source === Source.ChildListAdd) {
340
- traverse(node, timer, source, timestamp);
341
- } else {
342
- let state = task.state(timer);
343
- if (state === Task.Wait) {
344
- state = await task.suspend(timer);
345
- }
346
- if (state === Task.Stop) {
347
- break;
348
- }
349
- processNode(node, source, timestamp);
350
- }
351
- }
352
- }
353
-
354
- function processThrottledMutations(): void {
355
- if (throttleDelay) {
356
- clearTimeout(throttleDelay);
357
- }
358
- throttleDelay = setTimeout(() => {
359
- task.schedule(process, Priority.High);
360
- }, Setting.LookAhead);
361
- }
362
-
363
- export function schedule(node: Node): Node {
364
- // Only schedule manual trigger for this node if it's not already in the queue
365
- if (queue.indexOf(node) < 0) {
366
- queue.push(node);
367
- }
368
-
369
- // Cancel any previous trigger before scheduling a new one.
370
- // It's common for a webpage to call multiple synchronous "insertRule" / "deleteRule" calls.
371
- // And in those cases we do not wish to monitor changes multiple times for the same node.
372
- if (timeout) {
373
- clearTimeout(timeout);
374
- }
375
- timeout = setTimeout(() => {
376
- trigger();
377
- }, Setting.LookAhead);
378
-
379
- return node;
380
- }
381
-
382
- function trigger(): void {
383
- for (let node of queue) {
384
- // Generate a mutation for this node only if it still exists
385
- if (node) {
386
- let shadowRoot = node.nodeType === Node.DOCUMENT_FRAGMENT_NODE;
387
- // Skip re-processing shadowRoot if it was already discovered
388
- if (shadowRoot && dom.has(node)) {
389
- continue;
390
- }
391
- generate(node, shadowRoot ? Constant.ChildList : Constant.CharacterData);
392
- }
393
- }
394
- queue = [];
395
- }
396
-
397
- function generate(target: Node, type: MutationRecordType): void {
398
- generate.dn = FunctionNames.MutationGenerate;
399
- measure(handle)([
400
- {
401
- addedNodes: [target],
402
- attributeName: null,
403
- attributeNamespace: null,
404
- nextSibling: null,
405
- oldValue: null,
406
- previousSibling: null,
407
- removedNodes: [],
408
- target,
409
- type,
410
- },
411
- ]);
412
- }
1
+ import { Priority, Task, Timer } from "@clarity-types/core";
2
+ import { Code, Event, Metric, Severity } from "@clarity-types/data";
3
+ import { Constant, MutationHistory, MutationRecordWithTime, MutationQueue, Setting, Source } from "@clarity-types/layout";
4
+ import { FunctionNames } from "@clarity-types/performance";
5
+ import api from "@src/core/api";
6
+ import * as core from "@src/core";
7
+ import { bind } from "@src/core/event";
8
+ import measure from "@src/core/measure";
9
+ import * as task from "@src/core/task";
10
+ import { time } from "@src/core/time";
11
+ import { clearTimeout, setTimeout } from "@src/core/timeout";
12
+ import { id } from "@src/data/metadata";
13
+ import * as summary from "@src/data/summary";
14
+ import * as internal from "@src/diagnostic/internal";
15
+ import * as doc from "@src/layout/document";
16
+ import * as dom from "@src/layout/dom";
17
+ import * as metric from "@src/data/metric";
18
+ import encode from "@src/layout/encode";
19
+ import * as region from "@src/layout/region";
20
+ import traverse from "@src/layout/traverse";
21
+ import processNode from "./node";
22
+ import config from "@src/core/config";
23
+
24
+ let observers: MutationObserver[] = [];
25
+ let mutations: MutationQueue[] = [];
26
+ let throttledMutations: { [key: number]: MutationRecordWithTime } = {};
27
+ let insertRule: (rule: string, index?: number) => number = null;
28
+ let deleteRule: (index?: number) => void = null;
29
+ let attachShadow: (init: ShadowRootInit) => ShadowRoot = null;
30
+ let mediaInsertRule: (rule: string, index?: number) => number = null;
31
+ let mediaDeleteRule: (index?: number) => void = null;
32
+ let queue: Node[] = [];
33
+ let timeout: number = null;
34
+ let throttleDelay: number = null;
35
+ let activePeriod = null;
36
+ let history: MutationHistory = {};
37
+ let criticalPeriod = null;
38
+ let observedNodes: WeakMap<Node, MutationObserver> = new WeakMap<Node, MutationObserver>();
39
+
40
+ // We ignore mutations if these attributes are updated
41
+ const IGNORED_ATTRIBUTES = ["data-google-query-id", "data-load-complete", "data-google-container-id"];
42
+
43
+ export function start(): void {
44
+ start.dn = FunctionNames.MutationStart;
45
+ observers = [];
46
+ queue = [];
47
+ timeout = null;
48
+ activePeriod = 0;
49
+ history = {};
50
+ criticalPeriod = 0;
51
+ observedNodes = new WeakMap<Node, MutationObserver>();
52
+
53
+ // Some popular open source libraries, like styled-components, optimize performance
54
+ // by injecting CSS using insertRule API vs. appending text node. A side effect of
55
+ // using javascript API is that it doesn't trigger DOM mutation and therefore we
56
+ // need to override the insertRule API and listen for changes manually.
57
+ if (insertRule === null) {
58
+ insertRule = CSSStyleSheet.prototype.insertRule;
59
+ CSSStyleSheet.prototype.insertRule = function (): number {
60
+ if (core.active()) {
61
+ schedule(this.ownerNode);
62
+ }
63
+ return insertRule.apply(this, arguments);
64
+ };
65
+ }
66
+
67
+ if ("CSSMediaRule" in window && mediaInsertRule === null) {
68
+ mediaInsertRule = CSSMediaRule.prototype.insertRule;
69
+ CSSMediaRule.prototype.insertRule = function (): number {
70
+ if (core.active()) {
71
+ schedule(this.parentStyleSheet.ownerNode);
72
+ }
73
+ return mediaInsertRule.apply(this, arguments);
74
+ };
75
+ }
76
+
77
+ if (deleteRule === null) {
78
+ deleteRule = CSSStyleSheet.prototype.deleteRule;
79
+ CSSStyleSheet.prototype.deleteRule = function (): void {
80
+ if (core.active()) {
81
+ schedule(this.ownerNode);
82
+ }
83
+ return deleteRule.apply(this, arguments);
84
+ };
85
+ }
86
+
87
+ if ("CSSMediaRule" in window && mediaDeleteRule === null) {
88
+ mediaDeleteRule = CSSMediaRule.prototype.deleteRule;
89
+ CSSMediaRule.prototype.deleteRule = function (): void {
90
+ if (core.active()) {
91
+ schedule(this.parentStyleSheet.ownerNode);
92
+ }
93
+ return mediaDeleteRule.apply(this, arguments);
94
+ };
95
+ }
96
+
97
+ // Add a hook to attachShadow API calls
98
+ // In case we are unable to add a hook and browser throws an exception,
99
+ // reset attachShadow variable and resume processing like before
100
+ if (attachShadow === null) {
101
+ attachShadow = Element.prototype.attachShadow;
102
+ try {
103
+ Element.prototype.attachShadow = function (): ShadowRoot {
104
+ if (core.active()) {
105
+ return schedule(attachShadow.apply(this, arguments)) as ShadowRoot;
106
+ } else {
107
+ return attachShadow.apply(this, arguments);
108
+ }
109
+ };
110
+ } catch {
111
+ attachShadow = null;
112
+ }
113
+ }
114
+ }
115
+
116
+ export function observe(node: Node): void {
117
+ // Create a new observer for every time a new DOM tree (e.g. root document or shadowdom root) is discovered on the page
118
+ // In the case of shadow dom, any mutations that happen within the shadow dom are not bubbled up to the host document
119
+ // For this reason, we need to wire up mutations every time we see a new shadow dom.
120
+ // Also, wrap it inside a try / catch. In certain browsers (e.g. legacy Edge), observer on shadow dom can throw errors
121
+ try {
122
+ // Cleanup old observer if present.
123
+ if (observedNodes.has(node)) {
124
+ observedNodes.get(node)?.disconnect();
125
+ }
126
+
127
+ let m = api(Constant.MutationObserver);
128
+ let observer = m in window ? new window[m](measure(handle) as MutationCallback) : null;
129
+ if (observer) {
130
+ observer.observe(node, { attributes: true, childList: true, characterData: true, subtree: true });
131
+ observedNodes.set(node, observer);
132
+ observers.push(observer);
133
+ }
134
+ } catch (e) {
135
+ internal.log(Code.MutationObserver, Severity.Info, e ? e.name : null);
136
+ }
137
+ }
138
+
139
+ export function monitor(frame: HTMLIFrameElement): void {
140
+ // Bind to iframe's onload event so we get notified anytime there's an update to iframe content.
141
+ // This includes cases where iframe location is updated without explicitly updating src attribute
142
+ // E.g. iframe.contentWindow.location.href = "new-location";
143
+ if (dom.has(frame) === false) {
144
+ bind(frame, Constant.LoadEvent, generate.bind(this, frame, Constant.ChildList), true);
145
+ }
146
+ }
147
+
148
+ export function stop(): void {
149
+ for (let observer of observers) {
150
+ if (observer) {
151
+ observer.disconnect();
152
+ }
153
+ }
154
+ observers = [];
155
+ history = {};
156
+ mutations = [];
157
+ throttledMutations = [];
158
+ queue = [];
159
+ activePeriod = 0;
160
+ timeout = null;
161
+ criticalPeriod = 0;
162
+ }
163
+
164
+ export function active(): void {
165
+ activePeriod = time() + Setting.MutationActivePeriod;
166
+ criticalPeriod = time() + config.criticalMs;
167
+ }
168
+
169
+ function handle(m: MutationRecord[]): void {
170
+ handle.dn = FunctionNames.MutationHandle;
171
+ // Queue up mutation records for asynchronous processing
172
+ let now = time();
173
+ summary.track(Event.Mutation, now);
174
+ mutations.push({ time: now, mutations: m });
175
+ task.schedule(process, Priority.High).then((): void => {
176
+ setTimeout(doc.compute);
177
+ measure(region.compute)();
178
+ });
179
+ }
180
+
181
+ async function processMutation(timer: Timer, mutation: MutationRecord, instance: number, timestamp: number): Promise<void> {
182
+ let state = task.state(timer);
183
+
184
+ if (state === Task.Wait) {
185
+ state = await task.suspend(timer);
186
+ }
187
+ if (state === Task.Stop) {
188
+ return;
189
+ }
190
+
191
+ let target = mutation.target;
192
+ let type = config.throttleDom ? track(mutation, timer, instance, timestamp) : mutation.type;
193
+
194
+ if (type && target && target.ownerDocument) {
195
+ dom.parse(target.ownerDocument);
196
+ }
197
+
198
+ if (type && target && target.nodeType == Node.DOCUMENT_FRAGMENT_NODE && (target as ShadowRoot).host) {
199
+ dom.parse(target as ShadowRoot);
200
+ }
201
+
202
+ switch (type) {
203
+ case Constant.Attributes:
204
+ if (IGNORED_ATTRIBUTES.indexOf(mutation.attributeName) < 0) {
205
+ processNode(target, Source.Attributes, timestamp);
206
+ }
207
+ break;
208
+ case Constant.CharacterData:
209
+ processNode(target, Source.CharacterData, timestamp);
210
+ break;
211
+ case Constant.ChildList:
212
+ processNodeList(mutation.addedNodes, Source.ChildListAdd, timer, timestamp);
213
+ processNodeList(mutation.removedNodes, Source.ChildListRemove, timer, timestamp);
214
+ break;
215
+ case Constant.Throttle:
216
+ default:
217
+ break;
218
+ }
219
+ }
220
+ async function process(): Promise<void> {
221
+ let timer: Timer = { id: id(), cost: Metric.LayoutCost };
222
+ task.start(timer);
223
+ while (mutations.length > 0) {
224
+ let record = mutations.shift();
225
+ let instance = time();
226
+ for (let mutation of record.mutations) {
227
+ await processMutation(timer, mutation, instance, record.time);
228
+ }
229
+ await encode(Event.Mutation, timer, record.time);
230
+ }
231
+
232
+ let processedMutations = false;
233
+ for (var key of Object.keys(throttledMutations)) {
234
+ let throttledMutationToProcess: MutationRecordWithTime = throttledMutations[key];
235
+ delete throttledMutations[key];
236
+ await processMutation(timer, throttledMutationToProcess.mutation, time(), throttledMutationToProcess.timestamp);
237
+ processedMutations = true;
238
+ }
239
+
240
+ if (Object.keys(throttledMutations).length > 0) {
241
+ processThrottledMutations();
242
+ }
243
+
244
+ // ensure we encode the previously throttled mutations once we have finished them
245
+ if (Object.keys(throttledMutations).length === 0 && processedMutations) {
246
+ await encode(Event.Mutation, timer, time());
247
+ }
248
+
249
+ cleanHistory();
250
+
251
+ task.stop(timer);
252
+ }
253
+
254
+ function cleanHistory(): void {
255
+ let now = time();
256
+ if (Object.keys(history).length > Setting.MaxMutationHistoryCount) {
257
+ history = {};
258
+ metric.count(Metric.HistoryClear);
259
+ }
260
+
261
+ for (let key of Object.keys(history)) {
262
+ let h = history[key];
263
+ if (now > h[1] + Setting.MaxMutationHistoryTime) {
264
+ delete history[key];
265
+ }
266
+ }
267
+ }
268
+
269
+ function track(m: MutationRecord, timer: Timer, instance: number, timestamp: number): string {
270
+ let value = m.target ? dom.get(m.target.parentNode) : null;
271
+
272
+ // Check if the parent is already discovered and that the parent is not the document root
273
+ if (value && value.data.tag !== Constant.HTML) {
274
+ // calculate inactive period based on the timestamp of the mutation not when the mutation is processed
275
+ let inactive = timestamp > activePeriod;
276
+
277
+ // Calculate critical period based on when mutation is processed
278
+ const critical = instance < criticalPeriod;
279
+ let target = dom.get(m.target);
280
+ let element = target && target.selector ? target.selector.join() : m.target.nodeName;
281
+ let parent = value.selector ? value.selector.join() : Constant.Empty;
282
+
283
+ // Check if its a low priority (e.g., ads related) element mutation happening during critical period
284
+ // If the discard list is empty, we discard all mutations during critical period
285
+ const lowPriMutation = config.throttleMutations && critical && (config.discard.length === 0 || config.discard.some((key) => element.includes(key)));
286
+
287
+ // We use selector, instead of id, to determine the key (signature for the mutation) because in some cases
288
+ // repeated mutations can cause elements to be destroyed and then recreated as new DOM nodes
289
+ // In those cases, IDs will change however the selector (which is relative to DOM xPath) remains the same
290
+ let key = [parent, element, m.attributeName, names(m.addedNodes), names(m.removedNodes)].join();
291
+
292
+ // Initialize an entry if it doesn't already exist
293
+ history[key] = key in history ? history[key] : [0, instance];
294
+ let h = history[key];
295
+
296
+ // Lookup any pending nodes queued up for removal, and process them now if we suspended a mutation before
297
+ if (inactive === false && h[0] >= Setting.MutationSuspendThreshold) {
298
+ processNodeList(h[2], Source.ChildListRemove, timer, timestamp);
299
+ }
300
+
301
+ // Update the counter, do not reset counter if its critical period
302
+ h[0] = inactive || lowPriMutation ? (h[1] === instance ? h[0] : h[0] + 1) : 1;
303
+ h[1] = instance;
304
+
305
+ // Return updated mutation type based on,
306
+ // 1. if we have already hit the threshold or not
307
+ // 2. if its a low priority mutation happening during critical time period
308
+ if (h[0] >= Setting.MutationSuspendThreshold || lowPriMutation) {
309
+ // Store a reference to removedNodes so we can process them later
310
+ // when we resume mutations again on user interactions
311
+ h[2] = m.removedNodes;
312
+ if (instance > timestamp + Setting.MutationActivePeriod) {
313
+ return m.type;
314
+ }
315
+
316
+ if (!config.dropMutations) {
317
+ // we only store the most recent mutation for a given key if it is being throttled
318
+ throttledMutations[key] = { mutation: m, timestamp };
319
+ }
320
+
321
+ return Constant.Throttle;
322
+ }
323
+ }
324
+ return m.type;
325
+ }
326
+
327
+ function names(nodes: NodeList): string {
328
+ let output: string[] = [];
329
+ for (let i = 0; nodes && i < nodes.length; i++) {
330
+ output.push(nodes[i].nodeName);
331
+ }
332
+ return output.join();
333
+ }
334
+
335
+ async function processNodeList(list: NodeList, source: Source, timer: Timer, timestamp: number): Promise<void> {
336
+ let length = list ? list.length : 0;
337
+ for (let i = 0; i < length; i++) {
338
+ const node = list[i];
339
+ if (source === Source.ChildListAdd) {
340
+ traverse(node, timer, source, timestamp);
341
+ } else {
342
+ let state = task.state(timer);
343
+ if (state === Task.Wait) {
344
+ state = await task.suspend(timer);
345
+ }
346
+ if (state === Task.Stop) {
347
+ break;
348
+ }
349
+ processNode(node, source, timestamp);
350
+ }
351
+ }
352
+ }
353
+
354
+ function processThrottledMutations(): void {
355
+ if (throttleDelay) {
356
+ clearTimeout(throttleDelay);
357
+ }
358
+ throttleDelay = setTimeout(() => {
359
+ task.schedule(process, Priority.High);
360
+ }, Setting.LookAhead);
361
+ }
362
+
363
+ export function schedule(node: Node): Node {
364
+ // Only schedule manual trigger for this node if it's not already in the queue
365
+ if (queue.indexOf(node) < 0) {
366
+ queue.push(node);
367
+ }
368
+
369
+ // Cancel any previous trigger before scheduling a new one.
370
+ // It's common for a webpage to call multiple synchronous "insertRule" / "deleteRule" calls.
371
+ // And in those cases we do not wish to monitor changes multiple times for the same node.
372
+ if (timeout) {
373
+ clearTimeout(timeout);
374
+ }
375
+ timeout = setTimeout(() => {
376
+ trigger();
377
+ }, Setting.LookAhead);
378
+
379
+ return node;
380
+ }
381
+
382
+ function trigger(): void {
383
+ for (let node of queue) {
384
+ // Generate a mutation for this node only if it still exists
385
+ if (node) {
386
+ let shadowRoot = node.nodeType === Node.DOCUMENT_FRAGMENT_NODE;
387
+ // Skip re-processing shadowRoot if it was already discovered
388
+ if (shadowRoot && dom.has(node)) {
389
+ continue;
390
+ }
391
+ generate(node, shadowRoot ? Constant.ChildList : Constant.CharacterData);
392
+ }
393
+ }
394
+ queue = [];
395
+ }
396
+
397
+ function generate(target: Node, type: MutationRecordType): void {
398
+ generate.dn = FunctionNames.MutationGenerate;
399
+ measure(handle)([
400
+ {
401
+ addedNodes: [target],
402
+ attributeName: null,
403
+ attributeNamespace: null,
404
+ nextSibling: null,
405
+ oldValue: null,
406
+ previousSibling: null,
407
+ removedNodes: [],
408
+ target,
409
+ type,
410
+ },
411
+ ]);
412
+ }