clarity-js 0.8.6 → 0.8.8

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