@absolutejs/beacon 0.7.0-beta.1 → 0.7.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -77,9 +77,129 @@ var BEACON_ATTRIBUTE = {
77
77
  THEME: "data-beacon-theme"
78
78
  };
79
79
 
80
+ // src/early.ts
81
+ var HISTORY_LIMIT = 16;
82
+ var ENTRY_LIMIT = 50;
83
+ var now = () => typeof performance === "undefined" ? 0 : performance.now();
84
+ var describeNode = (node) => {
85
+ if (!(node instanceof Element))
86
+ return "unknown";
87
+ const id = node.id === "" ? "" : `#${node.id}`;
88
+ const classes = [...node.classList].slice(0, 3).map((name) => `.${name}`).join("");
89
+ return `${node.tagName.toLowerCase()}${id}${classes}`;
90
+ };
91
+ var copyRect = (rect) => rect === undefined ? undefined : {
92
+ bottom: rect.bottom,
93
+ height: rect.height,
94
+ left: rect.left,
95
+ right: rect.right,
96
+ top: rect.top,
97
+ width: rect.width,
98
+ x: rect.x,
99
+ y: rect.y
100
+ };
101
+ var viewportSnapshot = () => {
102
+ const visual = window.visualViewport;
103
+ return {
104
+ documentHeight: document.documentElement.scrollHeight,
105
+ documentWidth: document.documentElement.scrollWidth,
106
+ innerHeight: window.innerHeight,
107
+ innerWidth: window.innerWidth,
108
+ ...visual == null ? {} : {
109
+ visualHeight: visual.height,
110
+ visualOffsetLeft: visual.offsetLeft,
111
+ visualOffsetTop: visual.offsetTop,
112
+ visualScale: visual.scale,
113
+ visualWidth: visual.width
114
+ }
115
+ };
116
+ };
117
+ var appendLimited = (values, value) => {
118
+ values.push(value);
119
+ if (values.length > HISTORY_LIMIT)
120
+ values.splice(0, values.length - HISTORY_LIMIT);
121
+ };
122
+ var installEarlyLayoutShiftBuffer = () => {
123
+ if (typeof window === "undefined" || typeof document === "undefined" || typeof PerformanceObserver === "undefined" || window.__absoluteBeaconEarlyLayoutShift !== undefined)
124
+ return;
125
+ const interactionTimes = [];
126
+ const resizeTimes = [];
127
+ const entries = [];
128
+ const recordInteraction = () => appendLimited(interactionTimes, now());
129
+ const recordResize = () => appendLimited(resizeTimes, now());
130
+ const recordEntries = (rawEntries) => {
131
+ for (const raw of rawEntries) {
132
+ const entry = raw;
133
+ entries.push({
134
+ documentReadyState: document.readyState,
135
+ hadRecentInput: entry.hadRecentInput === true,
136
+ observedAt: now(),
137
+ sources: (entry.sources ?? []).slice(0, 5).map((source) => ({
138
+ ...source.currentRect === undefined ? {} : { currentRect: copyRect(source.currentRect) },
139
+ ...source.node === undefined || source.node === null ? {} : { node: source.node },
140
+ ...source.previousRect === undefined ? {} : { previousRect: copyRect(source.previousRect) },
141
+ target: describeNode(source.node)
142
+ })),
143
+ startTime: entry.startTime,
144
+ value: entry.value ?? 0,
145
+ viewport: viewportSnapshot()
146
+ });
147
+ }
148
+ if (entries.length > ENTRY_LIMIT)
149
+ entries.splice(0, entries.length - ENTRY_LIMIT);
150
+ };
151
+ try {
152
+ const observerStartedAt = now();
153
+ const observer = new PerformanceObserver((list) => recordEntries(list.getEntries()));
154
+ const interactionEvents = [
155
+ "click",
156
+ "keydown",
157
+ "pointerdown",
158
+ "submit"
159
+ ];
160
+ observer.observe({ buffered: true, type: "layout-shift" });
161
+ for (const event of interactionEvents)
162
+ window.addEventListener(event, recordInteraction, true);
163
+ window.addEventListener("resize", recordResize);
164
+ window.visualViewport?.addEventListener("resize", recordResize);
165
+ const cleanup = () => {
166
+ for (const event of interactionEvents)
167
+ window.removeEventListener(event, recordInteraction, true);
168
+ window.removeEventListener("resize", recordResize);
169
+ window.visualViewport?.removeEventListener("resize", recordResize);
170
+ };
171
+ window.__absoluteBeaconEarlyLayoutShift = {
172
+ cleanup,
173
+ entries,
174
+ interactionTimes,
175
+ observer,
176
+ observerStartedAt,
177
+ recordEntries,
178
+ resizeTimes
179
+ };
180
+ } catch {}
181
+ };
182
+ var consumeEarlyLayoutShiftBuffer = () => {
183
+ if (typeof window === "undefined")
184
+ return;
185
+ const installed = window.__absoluteBeaconEarlyLayoutShift;
186
+ if (installed === undefined)
187
+ return;
188
+ installed.recordEntries(installed.observer.takeRecords());
189
+ installed.observer.disconnect();
190
+ installed.cleanup();
191
+ delete window.__absoluteBeaconEarlyLayoutShift;
192
+ return {
193
+ entries: installed.entries,
194
+ interactionTimes: installed.interactionTimes,
195
+ observerStartedAt: installed.observerStartedAt,
196
+ resizeTimes: installed.resizeTimes
197
+ };
198
+ };
199
+
80
200
  // src/index.ts
81
201
  var BEACON_TRACE_HEADER = "x-absolute-trace-id";
82
- var BEACON_SDK_VERSION = "0.7.0-beta.1";
202
+ var BEACON_SDK_VERSION = "0.7.0-beta.11";
83
203
  var inBrowser = () => typeof window !== "undefined";
84
204
  var newId = () => {
85
205
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
@@ -330,14 +450,14 @@ var FACEBOOK_ANDROID_PERFORMANCE_LOGGER = "iabjs://navigation_performance_logger
330
450
  var KNOWN_CRAWLER_USER_AGENT = /(?:AdsBot-Google|Googlebot|bingbot|Baiduspider|YandexBot|DuckDuckBot|Applebot|Bytespider|PetalBot|SemrushBot|AhrefsBot|DotBot|MJ12bot|GPTBot|ClaudeBot|PerplexityBot|Google-NotebookLM|BitSightBot|Dataprovider\.com|HubSpot Crawler|meta-external(?:agent|ads))/i;
331
451
  var GOOGLE_WEB_RENDERER_SERVICE_WORKER_WRAPPER = "wrsParams.serviceWorkers.navigator.serviceWorker.register";
332
452
  var EXTENSION_STACK_PROTOCOL = /(?:chrome|moz|safari-web)-extension:\/\//u;
453
+ var stackFrames = (stack) => (stack ?? "").split(`
454
+ `).map((line) => line.trim()).filter((line) => line.startsWith("at ") || /@(?:[a-z][a-z\d+.-]*:)?\/\//iu.test(line));
333
455
  var isExtensionOnlyStack = (event) => {
334
- const frames = (event.stack ?? "").split(`
335
- `).slice(1).map((line) => line.trim()).filter(Boolean);
456
+ const frames = stackFrames(event.stack);
336
457
  return frames.length > 0 && frames.every((frame) => EXTENSION_STACK_PROTOCOL.test(frame));
337
458
  };
338
459
  var isExtensionInjectedStack = (event) => {
339
- const firstFrame = (event.stack ?? "").split(`
340
- `).slice(1).map((line) => line.trim()).find(Boolean);
460
+ const [firstFrame] = stackFrames(event.stack);
341
461
  return firstFrame !== undefined && EXTENSION_STACK_PROTOCOL.test(firstFrame);
342
462
  };
343
463
  var isStacklessBrowserAbort = (event) => event.name === "AbortError" && event.message === "The user aborted a request." && (event.stack ?? "").trim() === "";
@@ -485,6 +605,17 @@ var bfcacheLocation = (value) => {
485
605
  var UUID_PATH_SEGMENT = /\b[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\b/giu;
486
606
  var LONG_IDENTIFIER_SEGMENT = /\b(?:[0-9a-f]{16,}|\d{8,})\b/giu;
487
607
  var VOLATILE_SIGNAL_TAGS = new Set([
608
+ "area",
609
+ "gapPx",
610
+ "overlapPx",
611
+ "surfaceColor",
612
+ "surfaceLuminance",
613
+ "targetBottomPx",
614
+ "targetHeightPx",
615
+ "targetLeftPx",
616
+ "targetRightPx",
617
+ "targetTopPx",
618
+ "targetWidthPx",
488
619
  "actionId",
489
620
  "actionTrusted",
490
621
  "automation",
@@ -496,6 +627,7 @@ var VOLATILE_SIGNAL_TAGS = new Set([
496
627
  "closeCount",
497
628
  "currentRelease",
498
629
  "durationMs",
630
+ "documentReadyState",
499
631
  "elapsedMs",
500
632
  "errorCount",
501
633
  "focusEventTrusted",
@@ -504,7 +636,16 @@ var VOLATILE_SIGNAL_TAGS = new Set([
504
636
  "interactionAgeMs",
505
637
  "lastFocused",
506
638
  "loadCount",
639
+ "layoutShiftBuffered",
640
+ "layoutShiftObservedAtMs",
641
+ "layoutShiftObserverStartedAtMs",
642
+ "layoutShiftSources",
643
+ "layoutShiftStartTimeMs",
507
644
  "newestRelease",
645
+ "navigationAgeMs",
646
+ "navigationFrom",
647
+ "navigationTo",
648
+ "navigationType",
508
649
  "obscuredPx",
509
650
  "presentationDelayMs",
510
651
  "processingDurationMs",
@@ -513,17 +654,32 @@ var VOLATILE_SIGNAL_TAGS = new Set([
513
654
  "responseMs",
514
655
  "shiftValue",
515
656
  "signal",
657
+ "scriptAttribution",
516
658
  "scriptCount",
517
659
  "scriptDurationMs",
660
+ "scriptFunction",
518
661
  "scriptForcedStyleAndLayoutMs",
662
+ "scriptInvoker",
663
+ "scriptInvokerType",
519
664
  "scriptPauseDurationMs",
665
+ "scriptSource",
520
666
  "scriptSourceCharPosition",
667
+ "scriptWindowAttribution",
521
668
  "spillPx",
522
669
  "stallCount",
523
670
  "styleAndLayoutDurationMs",
524
671
  "thresholdMs",
525
672
  "userAgent",
526
673
  "viewportHeight",
674
+ "viewportDocumentHeight",
675
+ "viewportDocumentWidth",
676
+ "viewportInnerHeight",
677
+ "viewportInnerWidth",
678
+ "viewportVisualHeight",
679
+ "viewportVisualOffsetLeft",
680
+ "viewportVisualOffsetTop",
681
+ "viewportVisualScale",
682
+ "viewportVisualWidth",
527
683
  "viewportWidth",
528
684
  "windowMs"
529
685
  ]);
@@ -546,6 +702,8 @@ var signalGroupingKey = (signalTags) => {
546
702
  const hash = stableIdentityHash(identity, 2166136261) + stableIdentityHash(identity, 2654435769);
547
703
  return `beacon-signal:${signalTags.signal}:${hash}`;
548
704
  };
705
+ var AUTOMATED_BROWSER_USER_AGENT = /(?:\b(?:adsbot|bingbot|crawler|googlebot|headlesschrome|lighthouse|pagespeed|spider)\b|\b(?:bot|crawl|spider)\/)/iu;
706
+ var isAutomatedBrowser = () => typeof navigator !== "undefined" && (navigator.webdriver === true || AUTOMATED_BROWSER_USER_AGENT.test(navigator.userAgent));
549
707
  var isInvisibleAnchor = (anchor) => {
550
708
  if (anchor.target === "_blank" || anchor.hasAttribute("download"))
551
709
  return true;
@@ -817,6 +975,7 @@ var createBeacon = (options) => {
817
975
  const FORM_FRUSTRATION_THRESHOLD = 3;
818
976
  const FORM_FRUSTRATION_WINDOW_MS = 60000;
819
977
  const LAYOUT_SHIFT_RECENT_INTERACTION_MS = 500;
978
+ const LAYOUT_SHIFT_SPA_NAVIGATION_SETTLE_MS = 2000;
820
979
  const LAYOUT_SHIFT_INTERACTION_PROVENANCE_MS = 1e4;
821
980
  const LAYOUT_SHIFT_VIEWPORT_RESIZE_SETTLE_MS = 500;
822
981
  const VIEWPORT_RESIZE_HISTORY_LIMIT = 8;
@@ -847,6 +1006,7 @@ var createBeacon = (options) => {
847
1006
  let pageLifecycleGeneration = 0;
848
1007
  let pageRestoredAt;
849
1008
  let recentInteraction;
1009
+ let recentNavigation;
850
1010
  let reportErrorClick = null;
851
1011
  const reportCapturedErrorClick = (error, tags2) => {
852
1012
  if (filterKnownNoise && isKnownBeaconNoise({
@@ -929,6 +1089,7 @@ var createBeacon = (options) => {
929
1089
  rating: metric.rating === "good" || metric.rating === "needs-improvement" || metric.rating === "poor" ? metric.rating : "needs-improvement",
930
1090
  ...options.release === undefined ? {} : { release: options.release },
931
1091
  ...replayId === undefined ? {} : { replayId },
1092
+ sessionId,
932
1093
  samplingRate: vitalsOptions.samplingRate ?? 1,
933
1094
  schemaVersion: vitalsOptions.schemaVersion ?? 1,
934
1095
  ...vitalsOptions.sdkVersion === undefined ? {} : { sdkVersion: vitalsOptions.sdkVersion },
@@ -1105,6 +1266,8 @@ var createBeacon = (options) => {
1105
1266
  push(event);
1106
1267
  };
1107
1268
  const emitSignal = (message, signalTags, traceId, extra, stackBoundary, fallbackFramesToDrop = 1, useDefaultFingerprint = false) => {
1269
+ if (signals?.suppressAutomatedBrowsers === true && isAutomatedBrowser())
1270
+ return;
1108
1271
  if (staleClientRelease && signalTags.signal !== BEACON_SIGNAL.STALE_RELEASE && signalTags.signal !== BEACON_SIGNAL.RELOAD_LOOP)
1109
1272
  return;
1110
1273
  const error = new Error(message);
@@ -1249,9 +1412,9 @@ var createBeacon = (options) => {
1249
1412
  if (signals === null || signals.authFailureStorms === false)
1250
1413
  return false;
1251
1414
  const label = `${method} ${endpoint2}`;
1252
- const now = Date.now();
1253
- const failures = (authFailuresByEndpoint.get(label) ?? []).filter(({ at }) => now - at < authFailureStormWindowMs);
1254
- failures.push({ at: now, status });
1415
+ const now2 = Date.now();
1416
+ const failures = (authFailuresByEndpoint.get(label) ?? []).filter(({ at }) => now2 - at < authFailureStormWindowMs);
1417
+ failures.push({ at: now2, status });
1255
1418
  authFailuresByEndpoint.set(label, failures);
1256
1419
  if (failures.length < authFailureStormCount || reportedAuthFailureStorms.has(label)) {
1257
1420
  return false;
@@ -1386,6 +1549,9 @@ var createBeacon = (options) => {
1386
1549
  method: methods.length === 1 ? methods[0] : "multiple",
1387
1550
  online: onlineStates.length === 1 ? onlineStates[0] : "mixed",
1388
1551
  reportDelayMs: String(reportDelayMs),
1552
+ requestOrigins: [
1553
+ ...new Set(failures.map((failure) => failure.sameOrigin === true ? "same-origin" : failure.origin ?? "unknown"))
1554
+ ].sort().join(","),
1389
1555
  signal: BEACON_SIGNAL.FETCH_FAILED,
1390
1556
  transport: transports.length === 1 ? transports[0] : "multiple",
1391
1557
  visibilityState: visibilityStates.length === 1 ? visibilityStates[0] : "mixed",
@@ -1394,6 +1560,19 @@ var createBeacon = (options) => {
1394
1560
  }
1395
1561
  };
1396
1562
  flushPendingNetworkFailures = flushNetworkFailures;
1563
+ const requestOrigin = (url) => {
1564
+ try {
1565
+ const parsed = new URL(url, location.href);
1566
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
1567
+ return {};
1568
+ return {
1569
+ origin: parsed.origin,
1570
+ sameOrigin: parsed.origin === location.origin
1571
+ };
1572
+ } catch {
1573
+ return {};
1574
+ }
1575
+ };
1397
1576
  const reportFailureSignal = (url, method, durationMs, transportKind, errorValue) => {
1398
1577
  if (signals === null || signals.failedRequests === false)
1399
1578
  return;
@@ -1406,6 +1585,7 @@ var createBeacon = (options) => {
1406
1585
  const properties = errorProperties(error);
1407
1586
  const state = networkState();
1408
1587
  const failure = {
1588
+ ...requestOrigin(url),
1409
1589
  at: Date.now(),
1410
1590
  durationMs,
1411
1591
  endpoint: shortUrl(url),
@@ -2093,7 +2273,7 @@ var createBeacon = (options) => {
2093
2273
  const seenScanIssues = new Set;
2094
2274
  let scanIssueReports = 0;
2095
2275
  const SCAN_ISSUE_MAX_REPORTS = 10;
2096
- const reportScanIssue = (element, signal, detail, extraTags) => {
2276
+ const reportScanIssue = (element, signal, detail, extraTags, extra) => {
2097
2277
  const bucket = viewportBucket();
2098
2278
  const key = `${signal}:${describeElement(element)}@${bucket}`;
2099
2279
  if (seenScanIssues.has(key))
@@ -2108,7 +2288,7 @@ var createBeacon = (options) => {
2108
2288
  target: describeElement(element),
2109
2289
  viewportBucket: bucket,
2110
2290
  viewportWidth: String(document.documentElement.clientWidth)
2111
- });
2291
+ }, undefined, extra);
2112
2292
  };
2113
2293
  const reportOverflow = (element, kind, detail, spillPx) => {
2114
2294
  const bucket = viewportBucket();
@@ -2235,6 +2415,8 @@ var createBeacon = (options) => {
2235
2415
  return visible;
2236
2416
  };
2237
2417
  const isExtensionOwnedCover = (element) => {
2418
+ if (element.closest("com-1password-notification") !== null)
2419
+ return true;
2238
2420
  if (element.tagName !== "IFRAME")
2239
2421
  return false;
2240
2422
  const source = element.getAttribute("src")?.trim().toLowerCase() ?? "";
@@ -2249,6 +2431,38 @@ var createBeacon = (options) => {
2249
2431
  const secondDialog = second.closest('[role="dialog"], dialog');
2250
2432
  return firstDialog === null !== (secondDialog === null);
2251
2433
  };
2434
+ const scanLayoutContext = (target, other) => {
2435
+ const geometry = (element) => {
2436
+ const rect = element.getBoundingClientRect();
2437
+ let positionedAncestor = element;
2438
+ while (positionedAncestor !== null && !["fixed", "sticky"].includes(window.getComputedStyle(positionedAncestor).position)) {
2439
+ positionedAncestor = positionedAncestor.parentElement;
2440
+ }
2441
+ return {
2442
+ rect: {
2443
+ top: rect.top,
2444
+ right: rect.right,
2445
+ bottom: rect.bottom,
2446
+ left: rect.left,
2447
+ width: rect.width,
2448
+ height: rect.height
2449
+ },
2450
+ position: window.getComputedStyle(element).position,
2451
+ ...positionedAncestor ? {
2452
+ positionedAncestor: describeElement(positionedAncestor),
2453
+ ancestorPosition: window.getComputedStyle(positionedAncestor).position
2454
+ } : {}
2455
+ };
2456
+ };
2457
+ return {
2458
+ layout: {
2459
+ target: geometry(target),
2460
+ other: geometry(other),
2461
+ scrollX: window.scrollX,
2462
+ scrollY: window.scrollY
2463
+ }
2464
+ };
2465
+ };
2252
2466
  const scanForControlCollisions = () => {
2253
2467
  const viewportWidth = document.documentElement.clientWidth;
2254
2468
  const viewportHeight = document.documentElement.clientHeight;
@@ -2295,7 +2509,7 @@ var createBeacon = (options) => {
2295
2509
  collisionAxis: axis2,
2296
2510
  collisionKind: "overlap",
2297
2511
  overlapPx: String(Math.round(axis2 === "vertical" ? overlapY : overlapX))
2298
- });
2512
+ }, scanLayoutContext(first.element, second.element));
2299
2513
  continue;
2300
2514
  }
2301
2515
  if (first.element.parentElement === second.element.parentElement || sharedIntentionalControlGroup(first.element, second.element) || first.positioned || second.positioned) {
@@ -2319,7 +2533,7 @@ var createBeacon = (options) => {
2319
2533
  collisionAxis: axis,
2320
2534
  collisionKind: "touching",
2321
2535
  gapPx: String(Math.round(axis === "vertical" ? verticalGap : horizontalGap))
2322
- });
2536
+ }, scanLayoutContext(first.element, second.element));
2323
2537
  }
2324
2538
  }
2325
2539
  };
@@ -2354,7 +2568,7 @@ var createBeacon = (options) => {
2354
2568
  const coverage = Math.max(overlapX, 0) * Math.max(overlapY, 0) / ((visibleRect.right - visibleRect.left) * (visibleRect.bottom - visibleRect.top));
2355
2569
  if (coverage < OCCLUSION_COVERAGE_MIN)
2356
2570
  continue;
2357
- reportScanIssue(control, BEACON_SIGNAL.OCCLUDED_CONTROL, `Occluded control — ${describeElement(control)} is covered by ${describeElement(top)}`, { coveredBy: describeElement(top) });
2571
+ reportScanIssue(control, BEACON_SIGNAL.OCCLUDED_CONTROL, `Occluded control — ${describeElement(control)} is covered by ${describeElement(top)}`, { coveredBy: describeElement(top) }, scanLayoutContext(control, top));
2358
2572
  }
2359
2573
  };
2360
2574
  const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
@@ -2639,9 +2853,9 @@ var createBeacon = (options) => {
2639
2853
  const checkStuckLoading = () => {
2640
2854
  if (document.visibilityState === "hidden")
2641
2855
  return;
2642
- const now = Date.now();
2643
- const missedPollWindow = lastLoadingCheckAt !== undefined && now - lastLoadingCheckAt > STUCK_LOADING_POLL_MS * 3;
2644
- lastLoadingCheckAt = now;
2856
+ const now2 = Date.now();
2857
+ const missedPollWindow = lastLoadingCheckAt !== undefined && now2 - lastLoadingCheckAt > STUCK_LOADING_POLL_MS * 3;
2858
+ lastLoadingCheckAt = now2;
2645
2859
  const indicators = Array.from(document.querySelectorAll(loadingIndicatorSelector));
2646
2860
  const activeIndicators = new Set(indicators);
2647
2861
  for (const tracked of trackedLoadingIndicators) {
@@ -2659,22 +2873,22 @@ var createBeacon = (options) => {
2659
2873
  continue;
2660
2874
  }
2661
2875
  if (missedPollWindow && loadingFirstSeen.has(indicator)) {
2662
- loadingFirstSeen.set(indicator, now);
2876
+ loadingFirstSeen.set(indicator, now2);
2663
2877
  }
2664
2878
  const firstSeen = loadingFirstSeen.get(indicator);
2665
2879
  if (firstSeen === undefined) {
2666
- loadingFirstSeen.set(indicator, now);
2880
+ loadingFirstSeen.set(indicator, now2);
2667
2881
  trackedLoadingIndicators.add(indicator);
2668
2882
  continue;
2669
2883
  }
2670
2884
  const deadlineMs = loadingDeadlineMs(indicator);
2671
- if (now - firstSeen < deadlineMs || reportedStuckLoading.has(indicator)) {
2885
+ if (now2 - firstSeen < deadlineMs || reportedStuckLoading.has(indicator)) {
2672
2886
  continue;
2673
2887
  }
2674
2888
  reportedStuckLoading.add(indicator);
2675
2889
  reportScanIssue(indicator, BEACON_SIGNAL.STUCK_LOADING, `Stuck loading — ${describeElement(indicator)} never resolved`, {
2676
2890
  deadlineMs: String(deadlineMs),
2677
- visibleMs: String(now - firstSeen)
2891
+ visibleMs: String(now2 - firstSeen)
2678
2892
  });
2679
2893
  }
2680
2894
  };
@@ -2777,7 +2991,9 @@ var createBeacon = (options) => {
2777
2991
  if (signals !== null && signals.disruptiveLayoutShifts !== false && typeof PerformanceObserver !== "undefined") {
2778
2992
  const minimum = signals.disruptiveLayoutShiftMin ?? DISRUPTIVE_LAYOUT_SHIFT_DEFAULT_MIN;
2779
2993
  const reported = new Set;
2780
- let viewportResizeTimes = [];
2994
+ const earlyBuffer = consumeEarlyLayoutShiftBuffer();
2995
+ let viewportResizeTimes = [...earlyBuffer?.resizeTimes ?? []];
2996
+ const earlyInteractionTimes = earlyBuffer?.interactionTimes ?? [];
2781
2997
  const recordViewportResize = () => {
2782
2998
  viewportResizeTimes.push(performance.now());
2783
2999
  if (viewportResizeTimes.length > VIEWPORT_RESIZE_HISTORY_LIMIT) {
@@ -2787,50 +3003,131 @@ var createBeacon = (options) => {
2787
3003
  window.addEventListener("resize", recordViewportResize);
2788
3004
  window.visualViewport?.addEventListener("resize", recordViewportResize);
2789
3005
  try {
3006
+ const currentViewport = () => {
3007
+ const visual = window.visualViewport;
3008
+ return {
3009
+ documentHeight: document.documentElement.scrollHeight,
3010
+ documentWidth: document.documentElement.scrollWidth,
3011
+ innerHeight: window.innerHeight,
3012
+ innerWidth: window.innerWidth,
3013
+ ...visual == null ? {} : {
3014
+ visualHeight: visual.height,
3015
+ visualOffsetLeft: visual.offsetLeft,
3016
+ visualOffsetTop: visual.offsetTop,
3017
+ visualScale: visual.scale,
3018
+ visualWidth: visual.width
3019
+ }
3020
+ };
3021
+ };
3022
+ const processLayoutShift = (entry) => {
3023
+ const firstContentfulPaint = performance.getEntriesByName("first-contentful-paint")[0]?.startTime;
3024
+ if (firstContentfulPaint !== undefined && entry.startTime < firstContentfulPaint)
3025
+ return;
3026
+ const interactionTimes = [
3027
+ ...earlyInteractionTimes,
3028
+ ...recentInteraction === undefined ? [] : [recentInteraction.performanceAt]
3029
+ ];
3030
+ const interactionAgeMs = interactionTimes.map((interactionAt) => entry.startTime - interactionAt).filter((age) => age >= 0).sort((left, right) => left - right)[0];
3031
+ const beaconSawRecentInput = interactionAgeMs !== undefined && interactionAgeMs <= LAYOUT_SHIFT_RECENT_INTERACTION_MS;
3032
+ const navigationAgeMs = recentNavigation === undefined ? undefined : entry.startTime - recentNavigation.performanceAt;
3033
+ const navigationSettling = navigationAgeMs !== undefined && navigationAgeMs >= 0 && navigationAgeMs <= LAYOUT_SHIFT_SPA_NAVIGATION_SETTLE_MS;
3034
+ const resizeAdjacent = viewportResizeTimes.some((resizedAt) => {
3035
+ const resizeAgeMs = entry.startTime - resizedAt;
3036
+ return resizeAgeMs >= 0 && resizeAgeMs <= LAYOUT_SHIFT_VIEWPORT_RESIZE_SETTLE_MS;
3037
+ });
3038
+ if (entry.hadRecentInput || beaconSawRecentInput || navigationSettling || resizeAdjacent || mobileKeyboardViewportActive() || entry.value < minimum)
3039
+ return;
3040
+ const sourceElements = entry.sources.map(({ node }) => node instanceof Element ? node : undefined).filter((node) => node !== undefined);
3041
+ if (sourceElements.length > 0 && sourceElements.every((node) => node.closest(`[${BEACON_ATTRIBUTE.LAYOUT_SHIFT}="allow"]`) !== null))
3042
+ return;
3043
+ const targets = entry.sources.map((source) => source.node instanceof Element ? describeElement(source.node) : source.target).filter((target) => target !== "unknown").slice(0, 5);
3044
+ const key = targets.join(",") || "unknown";
3045
+ const framePhase = entry.startTime < MAIN_THREAD_STALL_DEFAULT_WINDOW_MS ? "startup" : "runtime";
3046
+ const interactionProvenance = key === "unknown" && recentInteraction !== undefined && interactionAgeMs !== undefined && interactionAgeMs <= LAYOUT_SHIFT_INTERACTION_PROVENANCE_MS ? recentInteraction : undefined;
3047
+ const reportKey = key === "unknown" ? [
3048
+ key,
3049
+ framePhase,
3050
+ interactionProvenance?.type ?? "no-interaction",
3051
+ interactionProvenance?.target ?? "unknown"
3052
+ ].join("|") : key;
3053
+ if (reported.has(reportKey))
3054
+ return;
3055
+ reported.add(reportKey);
3056
+ emitSignal(`Disruptive layout shift — ${key} — ${shortUrl(location.href)}`, {
3057
+ documentReadyState: entry.documentReadyState,
3058
+ ...key === "unknown" ? {
3059
+ framePhase,
3060
+ ...interactionProvenance === undefined ? {} : {
3061
+ interactionAgeMs: String(Math.round(interactionAgeMs ?? 0)),
3062
+ interactionTarget: interactionProvenance.target,
3063
+ interactionType: interactionProvenance.type
3064
+ }
3065
+ } : {},
3066
+ ...recentNavigation === undefined || navigationAgeMs === undefined || navigationAgeMs < 0 || navigationAgeMs > LAYOUT_SHIFT_INTERACTION_PROVENANCE_MS ? {} : {
3067
+ navigationAgeMs: String(Math.round(navigationAgeMs)),
3068
+ navigationFrom: recentNavigation.from,
3069
+ navigationTo: recentNavigation.to,
3070
+ navigationType: recentNavigation.type
3071
+ },
3072
+ layoutShiftBuffered: String(entry.buffered),
3073
+ layoutShiftObservedAtMs: String(Math.round(entry.observedAt)),
3074
+ layoutShiftObserverStartedAtMs: String(Math.round(entry.observerStartedAt)),
3075
+ layoutShiftSources: JSON.stringify(entry.sources.map(({ currentRect, previousRect, target }) => ({
3076
+ currentRect,
3077
+ previousRect,
3078
+ target
3079
+ }))),
3080
+ layoutShiftStartTimeMs: String(Math.round(entry.startTime)),
3081
+ shiftValue: String(entry.value),
3082
+ signal: BEACON_SIGNAL.DISRUPTIVE_LAYOUT_SHIFT,
3083
+ target: key,
3084
+ viewportDocumentHeight: String(entry.viewport.documentHeight),
3085
+ viewportDocumentWidth: String(entry.viewport.documentWidth),
3086
+ viewportInnerHeight: String(entry.viewport.innerHeight),
3087
+ viewportInnerWidth: String(entry.viewport.innerWidth),
3088
+ ...entry.viewport.visualHeight === undefined ? {} : {
3089
+ viewportVisualHeight: String(entry.viewport.visualHeight),
3090
+ viewportVisualOffsetLeft: String(entry.viewport.visualOffsetLeft),
3091
+ viewportVisualOffsetTop: String(entry.viewport.visualOffsetTop),
3092
+ viewportVisualScale: String(entry.viewport.visualScale),
3093
+ viewportVisualWidth: String(entry.viewport.visualWidth)
3094
+ }
3095
+ });
3096
+ };
3097
+ for (const entry of earlyBuffer?.entries ?? []) {
3098
+ processLayoutShift({
3099
+ ...entry,
3100
+ buffered: true,
3101
+ observerStartedAt: earlyBuffer?.observerStartedAt ?? 0
3102
+ });
3103
+ }
3104
+ const observerStartedAt = performance.now();
2790
3105
  const observer = new PerformanceObserver((list) => {
2791
3106
  for (const raw of list.getEntries()) {
2792
3107
  const entry = raw;
2793
- const interactionAgeMs = recentInteraction === undefined ? undefined : entry.startTime - recentInteraction.performanceAt;
2794
- const beaconSawRecentInput = interactionAgeMs !== undefined && interactionAgeMs >= 0 && interactionAgeMs <= LAYOUT_SHIFT_RECENT_INTERACTION_MS;
2795
- const resizeAdjacent = viewportResizeTimes.some((resizedAt) => {
2796
- const resizeAgeMs = entry.startTime - resizedAt;
2797
- return resizeAgeMs >= 0 && resizeAgeMs <= LAYOUT_SHIFT_VIEWPORT_RESIZE_SETTLE_MS;
2798
- });
2799
- if (entry.hadRecentInput === true || beaconSawRecentInput || resizeAdjacent || mobileKeyboardViewportActive() || (entry.value ?? 0) < minimum)
2800
- continue;
2801
- const sourceElements = (entry.sources ?? []).map(({ node }) => node instanceof Element ? node : undefined).filter((node) => node !== undefined);
2802
- if (sourceElements.length > 0 && sourceElements.every((node) => node.closest(`[${BEACON_ATTRIBUTE.LAYOUT_SHIFT}="allow"]`) !== null)) {
2803
- continue;
2804
- }
2805
- const targets = sourceElements.map((node) => describeElement(node)).slice(0, 5);
2806
- const key = targets.join(",") || "unknown";
2807
- const framePhase = entry.startTime < MAIN_THREAD_STALL_DEFAULT_WINDOW_MS ? "startup" : "runtime";
2808
- const interactionProvenance = key === "unknown" && recentInteraction !== undefined && interactionAgeMs !== undefined && interactionAgeMs >= 0 && interactionAgeMs <= LAYOUT_SHIFT_INTERACTION_PROVENANCE_MS ? recentInteraction : undefined;
2809
- const reportKey = key === "unknown" ? [
2810
- key,
2811
- framePhase,
2812
- interactionProvenance?.type ?? "no-interaction",
2813
- interactionProvenance?.target ?? "unknown"
2814
- ].join("|") : key;
2815
- if (reported.has(reportKey))
2816
- continue;
2817
- reported.add(reportKey);
2818
- emitSignal(`Disruptive layout shift — ${key} — ${shortUrl(location.href)}`, {
2819
- ...key === "unknown" ? {
2820
- framePhase,
2821
- ...interactionProvenance === undefined ? {} : {
2822
- interactionAgeMs: String(Math.round(interactionAgeMs ?? 0)),
2823
- interactionTarget: interactionProvenance.target,
2824
- interactionType: interactionProvenance.type
2825
- }
2826
- } : {},
2827
- shiftValue: String(entry.value ?? 0),
2828
- signal: BEACON_SIGNAL.DISRUPTIVE_LAYOUT_SHIFT,
2829
- target: key
3108
+ const viewport = currentViewport();
3109
+ processLayoutShift({
3110
+ buffered: entry.startTime < observerStartedAt,
3111
+ documentReadyState: document.readyState,
3112
+ hadRecentInput: entry.hadRecentInput === true,
3113
+ observedAt: performance.now(),
3114
+ observerStartedAt,
3115
+ sources: (entry.sources ?? []).map((source) => ({
3116
+ currentRect: source.currentRect,
3117
+ ...source.node === undefined || source.node === null ? {} : { node: source.node },
3118
+ previousRect: source.previousRect,
3119
+ target: source.node instanceof Element ? describeElement(source.node) : "unknown"
3120
+ })),
3121
+ startTime: entry.startTime,
3122
+ value: entry.value ?? 0,
3123
+ viewport
2830
3124
  });
2831
3125
  }
2832
3126
  });
2833
- observer.observe({ buffered: true, type: "layout-shift" });
3127
+ observer.observe({
3128
+ buffered: earlyBuffer === undefined,
3129
+ type: "layout-shift"
3130
+ });
2834
3131
  cleanups.push(() => {
2835
3132
  observer.disconnect();
2836
3133
  window.removeEventListener("resize", recordViewportResize);
@@ -2895,7 +3192,9 @@ var createBeacon = (options) => {
2895
3192
  recordBlockingFrames(blockingObserver.takeRecords());
2896
3193
  }
2897
3194
  const interactionEnd = entry.startTime + entry.duration;
2898
- const overlappingFrame = blockingFrames.filter((frame) => frame.startTime < interactionEnd && frame.startTime + frame.duration > entry.startTime).sort((left, right) => {
3195
+ const overlappingFrames = blockingFrames.filter((frame) => frame.startTime < interactionEnd && frame.startTime + frame.duration > entry.startTime);
3196
+ const onlyIdleFrames = overlappingFrames.length > 0 && overlappingFrames.every((frame) => frame.entryType === "long-animation-frame" && frame.blockingDuration === 0 && Array.isArray(frame.scripts) && frame.scripts.length === 0);
3197
+ const overlappingFrame = overlappingFrames.sort((left, right) => {
2899
3198
  const leftBlocking = left.blockingDuration ?? Math.max(0, left.duration - LONG_TASK_MS);
2900
3199
  const rightBlocking = right.blockingDuration ?? Math.max(0, right.duration - LONG_TASK_MS);
2901
3200
  return rightBlocking - leftBlocking;
@@ -2905,7 +3204,7 @@ var createBeacon = (options) => {
2905
3204
  const processingDurationMs = hasPhaseTiming ? Math.round(Math.max(0, entry.processingEnd - entry.processingStart)) : undefined;
2906
3205
  const presentationDelayMs = hasPhaseTiming ? Math.round(Math.max(0, interactionEnd - entry.processingEnd)) : undefined;
2907
3206
  const inputDelayMs = hasPhaseTiming ? Math.round(Math.max(0, entry.processingStart - entry.startTime)) : undefined;
2908
- if (overlappingFrame === undefined && processingDurationMs !== undefined && processingDurationMs <= 16 && presentationDelayMs !== undefined && presentationDelayMs >= minimum)
3207
+ if ((overlappingFrame === undefined || onlyIdleFrames && inputDelayMs !== undefined && inputDelayMs < minimum) && processingDurationMs !== undefined && processingDurationMs <= 16 && presentationDelayMs !== undefined && presentationDelayMs >= minimum)
2909
3208
  continue;
2910
3209
  if (blockingObserver !== undefined && overlappingFrame === undefined && inputDelayMs !== undefined && inputDelayMs >= minimum && processingDurationMs !== undefined && processingDurationMs <= 16 && presentationDelayMs !== undefined && presentationDelayMs < minimum)
2911
3210
  continue;
@@ -3352,16 +3651,16 @@ var createBeacon = (options) => {
3352
3651
  jailBurst = [];
3353
3652
  return;
3354
3653
  }
3355
- const now = Date.now();
3654
+ const now2 = Date.now();
3356
3655
  if (jailScroller !== scroller) {
3357
3656
  jailScroller = scroller;
3358
3657
  jailBurst = [];
3359
3658
  }
3360
- jailBurst = jailBurst.filter((entry) => now - entry.at < SCROLL_JAIL_WINDOW_MS);
3659
+ jailBurst = jailBurst.filter((entry) => now2 - entry.at < SCROLL_JAIL_WINDOW_MS && !entry.event.defaultPrevented);
3361
3660
  if (jailBurst.length === 0) {
3362
3661
  jailStartingScrollGeneration = scrollActivityGeneration;
3363
3662
  }
3364
- jailBurst.push({ at: now, position: scroller.scrollTop });
3663
+ jailBurst.push({ at: now2, position: scroller.scrollTop, event });
3365
3664
  if (jailBurst.length < SCROLL_JAIL_EVENT_COUNT)
3366
3665
  return;
3367
3666
  const first = jailBurst[0];
@@ -3373,7 +3672,10 @@ var createBeacon = (options) => {
3373
3672
  const startingPosition = first.position;
3374
3673
  jailSettleTimer = setTimeout(() => {
3375
3674
  jailSettleTimer = undefined;
3675
+ const confirmedBurst = jailBurst.filter((entry) => !entry.event.defaultPrevented);
3376
3676
  jailBurst = [];
3677
+ if (confirmedBurst.length < SCROLL_JAIL_EVENT_COUNT)
3678
+ return;
3377
3679
  if (scrollActivityGeneration !== jailStartingScrollGeneration)
3378
3680
  return;
3379
3681
  if (!scroller.isConnected || scroller.scrollTop !== startingPosition)
@@ -3387,7 +3689,29 @@ var createBeacon = (options) => {
3387
3689
  if (reportedScrollers.has(descriptor))
3388
3690
  return;
3389
3691
  reportedScrollers.add(descriptor);
3390
- emitSignal(`Scroll jail — ${descriptor} has scrollable content but never moves — ${shortUrl(location.href)}`, { signal: BEACON_SIGNAL.SCROLL_JAIL, target: descriptor });
3692
+ emitSignal(`Scroll jail — ${descriptor} has scrollable content but never moves — ${shortUrl(location.href)}`, { signal: BEACON_SIGNAL.SCROLL_JAIL, target: descriptor }, undefined, {
3693
+ scroll: {
3694
+ target: target ? describeElement(target) : undefined,
3695
+ scroller: descriptor,
3696
+ direction: scrollingDown ? "down" : "up",
3697
+ wheelCount: confirmedBurst.length,
3698
+ burstDurationMs: now2 - (confirmedBurst[0]?.at ?? now2),
3699
+ scrollTop: scroller.scrollTop,
3700
+ scrollHeight: scroller.scrollHeight,
3701
+ clientHeight: scroller.clientHeight,
3702
+ overflowY: window.getComputedStyle(scroller).overflowY,
3703
+ overscrollBehaviorY: window.getComputedStyle(scroller).overscrollBehaviorY,
3704
+ bodyOverflowY: window.getComputedStyle(document.body).overflowY,
3705
+ rootOverflowY: window.getComputedStyle(document.documentElement).overflowY,
3706
+ modal: modal ? describeElement(modal) : undefined,
3707
+ rect: {
3708
+ top: scroller.getBoundingClientRect().top,
3709
+ left: scroller.getBoundingClientRect().left,
3710
+ width: scroller.getBoundingClientRect().width,
3711
+ height: scroller.getBoundingClientRect().height
3712
+ }
3713
+ }
3714
+ });
3391
3715
  }, SCROLL_JAIL_SETTLE_MS);
3392
3716
  };
3393
3717
  document.addEventListener("scroll", onDocumentScroll, {
@@ -3420,9 +3744,9 @@ var createBeacon = (options) => {
3420
3744
  previous = { x: event.clientX, y: event.clientY };
3421
3745
  if (Math.hypot(dx, dy) < 8)
3422
3746
  return;
3423
- const now = Date.now();
3424
- points = points.filter((point) => now - point.at < THRASHED_CURSOR_WINDOW_MS);
3425
- points.push({ at: now, dx, dy });
3747
+ const now2 = Date.now();
3748
+ points = points.filter((point) => now2 - point.at < THRASHED_CURSOR_WINDOW_MS);
3749
+ points.push({ at: now2, dx, dy });
3426
3750
  let reversals = 0;
3427
3751
  for (let index = 1;index < points.length; index += 1) {
3428
3752
  const prior = points[index - 1];
@@ -3650,14 +3974,14 @@ var createBeacon = (options) => {
3650
3974
  if (data === null)
3651
3975
  return;
3652
3976
  const activity = activityFor(form);
3653
- const now = Date.now();
3977
+ const now2 = Date.now();
3654
3978
  if (data !== activity.lastData) {
3655
3979
  activity.lastData = data;
3656
- activity.identicalSubmits = [now];
3980
+ activity.identicalSubmits = [now2];
3657
3981
  return;
3658
3982
  }
3659
- activity.identicalSubmits = activity.identicalSubmits.filter((at) => now - at < FORM_FRUSTRATION_WINDOW_MS);
3660
- activity.identicalSubmits.push(now);
3983
+ activity.identicalSubmits = activity.identicalSubmits.filter((at) => now2 - at < FORM_FRUSTRATION_WINDOW_MS);
3984
+ activity.identicalSubmits.push(now2);
3661
3985
  if (activity.identicalSubmits.length >= FORM_FRUSTRATION_THRESHOLD) {
3662
3986
  reportForm(form, "was submitted with identical values repeatedly");
3663
3987
  }
@@ -3668,14 +3992,14 @@ var createBeacon = (options) => {
3668
3992
  if (form === null)
3669
3993
  return;
3670
3994
  const activity = activityFor(form);
3671
- const now = Date.now();
3672
- if (now - activity.lastInvalidAt < FORM_INVALID_BURST_GAP_MS) {
3673
- activity.lastInvalidAt = now;
3995
+ const now2 = Date.now();
3996
+ if (now2 - activity.lastInvalidAt < FORM_INVALID_BURST_GAP_MS) {
3997
+ activity.lastInvalidAt = now2;
3674
3998
  return;
3675
3999
  }
3676
- activity.lastInvalidAt = now;
3677
- activity.invalidBursts = activity.invalidBursts.filter((at) => now - at < FORM_FRUSTRATION_WINDOW_MS);
3678
- activity.invalidBursts.push(now);
4000
+ activity.lastInvalidAt = now2;
4001
+ activity.invalidBursts = activity.invalidBursts.filter((at) => now2 - at < FORM_FRUSTRATION_WINDOW_MS);
4002
+ activity.invalidBursts.push(now2);
3679
4003
  if (activity.invalidBursts.length >= FORM_FRUSTRATION_THRESHOLD) {
3680
4004
  reportForm(form, "keeps failing native validation");
3681
4005
  }
@@ -3774,9 +4098,9 @@ var createBeacon = (options) => {
3774
4098
  if (signals.sseFlapping === false || pageLifecycleEnding || document.visibilityState === "hidden") {
3775
4099
  return;
3776
4100
  }
3777
- const now = Date.now();
3778
- const errors = (errorsByEndpoint.get(endpointLabel) ?? []).filter((at) => now - at < sseFlapWindowMs);
3779
- errors.push(now);
4101
+ const now2 = Date.now();
4102
+ const errors = (errorsByEndpoint.get(endpointLabel) ?? []).filter((at) => now2 - at < sseFlapWindowMs);
4103
+ errors.push(now2);
3780
4104
  errorsByEndpoint.set(endpointLabel, errors);
3781
4105
  if (errors.length < sseFlapCount || reportedFlappingStreams.has(endpointLabel)) {
3782
4106
  return;
@@ -3852,6 +4176,9 @@ var createBeacon = (options) => {
3852
4176
  const restoredLifecycleClose = pageRestoredAt !== undefined && socketLifecycleGeneration < pageLifecycleGeneration && Date.now() - pageRestoredAt <= RESTORED_SOCKET_CLOSE_GRACE_MS;
3853
4177
  if (pageLifecycleEnding || applicationClose || restoredLifecycleClose)
3854
4178
  return;
4179
+ const expectedServerClose = typeof CloseEvent !== "undefined" && event instanceof CloseEvent && (event.wasClean || event.code === 1000 || event.code === 1001 || event.code === 1012);
4180
+ if (expectedServerClose)
4181
+ return;
3855
4182
  if (signals.socketAbnormalCloses !== false && typeof CloseEvent !== "undefined" && event instanceof CloseEvent && !event.wasClean && !recoverableSocket(socketUrl)) {
3856
4183
  const abnormalKey = `${label}|${event.code}`;
3857
4184
  if (!reportedAbnormalCloses.has(abnormalKey)) {
@@ -3866,10 +4193,10 @@ var createBeacon = (options) => {
3866
4193
  }
3867
4194
  if (signals.socketFlapping === false)
3868
4195
  return;
3869
- const now = Date.now();
3870
- const closes = (closesByUrl.get(label) ?? []).filter((close) => now - close.at < SOCKET_FLAP_WINDOW_MS);
4196
+ const now2 = Date.now();
4197
+ const closes = (closesByUrl.get(label) ?? []).filter((close) => now2 - close.at < SOCKET_FLAP_WINDOW_MS);
3871
4198
  closes.push({
3872
- at: now,
4199
+ at: now2,
3873
4200
  code: typeof CloseEvent !== "undefined" && event instanceof CloseEvent ? event.code : null,
3874
4201
  wasClean: typeof CloseEvent !== "undefined" && event instanceof CloseEvent ? event.wasClean : null
3875
4202
  });
@@ -3885,7 +4212,7 @@ var createBeacon = (options) => {
3885
4212
  windowMs: String(SOCKET_FLAP_WINDOW_MS)
3886
4213
  }, undefined, {
3887
4214
  closeSamples: closes.map((close) => ({
3888
- ageMs: now - close.at,
4215
+ ageMs: now2 - close.at,
3889
4216
  code: close.code,
3890
4217
  wasClean: close.wasClean
3891
4218
  }))
@@ -4116,23 +4443,23 @@ var createBeacon = (options) => {
4116
4443
  try {
4117
4444
  const navigation = performance.getEntriesByType("navigation")[0];
4118
4445
  if (navigation?.type !== "back_forward") {
4119
- const now = Date.now();
4446
+ const now2 = Date.now();
4120
4447
  const route = shortUrl(location.href);
4121
4448
  const raw = sessionStorage.getItem(RELOAD_LOOP_STORAGE_KEY);
4122
4449
  const parsed = raw === null ? [] : JSON.parse(raw);
4123
- let history2 = (Array.isArray(parsed) ? parsed : []).filter((entry) => entry !== null && typeof entry === "object" && typeof entry.at === "number" && typeof entry.route === "string" && now - entry.at < RELOAD_LOOP_WINDOW_MS);
4450
+ let history2 = (Array.isArray(parsed) ? parsed : []).filter((entry) => entry !== null && typeof entry === "object" && typeof entry.at === "number" && typeof entry.route === "string" && now2 - entry.at < RELOAD_LOOP_WINDOW_MS);
4124
4451
  let entryKind = "app";
4125
4452
  const rawNavigationIntent = sessionStorage.getItem(NAVIGATION_INTENT_STORAGE_KEY);
4126
4453
  sessionStorage.removeItem(NAVIGATION_INTENT_STORAGE_KEY);
4127
4454
  const navigationIntentAt = Number(rawNavigationIntent);
4128
- if (rawNavigationIntent !== null && Number.isFinite(navigationIntentAt) && now - navigationIntentAt >= 0 && now - navigationIntentAt <= NAVIGATION_INTENT_MAX_AGE_MS) {
4455
+ if (rawNavigationIntent !== null && Number.isFinite(navigationIntentAt) && now2 - navigationIntentAt >= 0 && now2 - navigationIntentAt <= NAVIGATION_INTENT_MAX_AGE_MS) {
4129
4456
  history2 = [];
4130
4457
  entryKind = "intentional-navigation";
4131
4458
  }
4132
4459
  const rawServiceWorkerUpdateIntent = sessionStorage.getItem(SERVICE_WORKER_UPDATE_INTENT_STORAGE_KEY);
4133
4460
  sessionStorage.removeItem(SERVICE_WORKER_UPDATE_INTENT_STORAGE_KEY);
4134
4461
  const serviceWorkerUpdateIntentAt = Number(rawServiceWorkerUpdateIntent);
4135
- if (rawServiceWorkerUpdateIntent !== null && Number.isFinite(serviceWorkerUpdateIntentAt) && now - serviceWorkerUpdateIntentAt >= 0 && now - serviceWorkerUpdateIntentAt <= NAVIGATION_INTENT_MAX_AGE_MS) {
4462
+ if (rawServiceWorkerUpdateIntent !== null && Number.isFinite(serviceWorkerUpdateIntentAt) && now2 - serviceWorkerUpdateIntentAt >= 0 && now2 - serviceWorkerUpdateIntentAt <= NAVIGATION_INTENT_MAX_AGE_MS) {
4136
4463
  history2 = [];
4137
4464
  entryKind = "service-worker-update";
4138
4465
  }
@@ -4143,7 +4470,7 @@ var createBeacon = (options) => {
4143
4470
  entryKind = "external";
4144
4471
  }
4145
4472
  }
4146
- history2.push({ at: now, route });
4473
+ history2.push({ at: now2, route });
4147
4474
  sessionStorage.setItem(RELOAD_LOOP_STORAGE_KEY, JSON.stringify(history2));
4148
4475
  let loadCount = 0;
4149
4476
  for (let index = history2.length - 1;index >= 0; index -= 1) {
@@ -4152,7 +4479,7 @@ var createBeacon = (options) => {
4152
4479
  loadCount += 1;
4153
4480
  }
4154
4481
  if (loadCount === RELOAD_LOOP_COUNT) {
4155
- const firstLoad = history2.at(-loadCount)?.at ?? now;
4482
+ const firstLoad = history2.at(-loadCount)?.at ?? now2;
4156
4483
  emitSignal(`Reload loop — repeated page loads within a minute — ${shortUrl(location.href)}`, {
4157
4484
  currentRelease: options.release ?? "unknown",
4158
4485
  entryKind,
@@ -4161,7 +4488,7 @@ var createBeacon = (options) => {
4161
4488
  serviceWorkerControlled: String(navigator.serviceWorker?.controller !== null && navigator.serviceWorker?.controller !== undefined),
4162
4489
  serviceWorkerScript: navigator.serviceWorker?.controller?.scriptURL ?? "none",
4163
4490
  signal: BEACON_SIGNAL.RELOAD_LOOP,
4164
- windowMs: String(now - firstLoad)
4491
+ windowMs: String(now2 - firstLoad)
4165
4492
  });
4166
4493
  flush(true);
4167
4494
  }
@@ -4171,7 +4498,7 @@ var createBeacon = (options) => {
4171
4498
  if (signals !== null && signals.staleReleases !== false && typeof localStorage !== "undefined" && typeof options.release === "string" && options.release !== "") {
4172
4499
  try {
4173
4500
  const currentRelease = options.release;
4174
- const now = Date.now();
4501
+ const now2 = Date.now();
4175
4502
  const raw = localStorage.getItem(STALE_RELEASE_STORAGE_KEY);
4176
4503
  const parsed = raw === null ? {} : JSON.parse(raw);
4177
4504
  const firstSeenByRelease = {};
@@ -4181,10 +4508,10 @@ var createBeacon = (options) => {
4181
4508
  firstSeenByRelease[release] = at;
4182
4509
  }
4183
4510
  }
4184
- const currentFirstSeen = firstSeenByRelease[currentRelease] ?? now;
4511
+ const currentFirstSeen = firstSeenByRelease[currentRelease] ?? now2;
4185
4512
  firstSeenByRelease[currentRelease] = currentFirstSeen;
4186
4513
  const newest = Object.entries(firstSeenByRelease).filter(([release, at]) => release !== currentRelease && at > currentFirstSeen).sort((left, right) => right[1] - left[1])[0];
4187
- if (newest !== undefined && now - newest[1] > STALE_RELEASE_GRACE_MS) {
4514
+ if (newest !== undefined && now2 - newest[1] > STALE_RELEASE_GRACE_MS) {
4188
4515
  emitSignal(`Stale release — this page is running a build older than one this browser already saw — ${shortUrl(location.href)}`, {
4189
4516
  currentRelease,
4190
4517
  newestRelease: newest[0],
@@ -4304,9 +4631,9 @@ var createBeacon = (options) => {
4304
4631
  const reportedStorms = new Set;
4305
4632
  recordRequestForStorm = (url, method) => {
4306
4633
  const label = `${method.toUpperCase()} ${shortUrl(url)}`;
4307
- const now = Date.now();
4308
- const hits = (hitsByEndpoint.get(label) ?? []).filter((at) => now - at < stormWindowMs);
4309
- hits.push(now);
4634
+ const now2 = Date.now();
4635
+ const hits = (hitsByEndpoint.get(label) ?? []).filter((at) => now2 - at < stormWindowMs);
4636
+ hits.push(now2);
4310
4637
  hitsByEndpoint.set(label, hits);
4311
4638
  if (hits.length < stormCount || reportedStorms.has(label))
4312
4639
  return;
@@ -4419,15 +4746,15 @@ var createBeacon = (options) => {
4419
4746
  type: "xhr"
4420
4747
  });
4421
4748
  if (!failed) {
4422
- reportResponseSignal(request.url, request.method, this.status, Date.now() - start, responseTraceId(this.getResponseHeader(BEACON_TRACE_HEADER)));
4749
+ const headers = new Headers;
4750
+ for (const line of this.getAllResponseHeaders().split(/\r?\n/u)) {
4751
+ const separator = line.indexOf(":");
4752
+ if (separator <= 0)
4753
+ continue;
4754
+ headers.append(line.slice(0, separator).trim(), line.slice(separator + 1).trim());
4755
+ }
4756
+ reportResponseSignal(request.url, request.method, this.status, Date.now() - start, responseTraceId(headers.get(BEACON_TRACE_HEADER)));
4423
4757
  if ((instrument.classifyResponse !== undefined && this.status >= 200 && this.status < 300 || instrument.classifyErrorResponse !== undefined && this.status >= 400) && (this.responseType === "" || this.responseType === "text")) {
4424
- const headers = new Headers;
4425
- for (const line of this.getAllResponseHeaders().split(/\r?\n/u)) {
4426
- const separator = line.indexOf(":");
4427
- if (separator <= 0)
4428
- continue;
4429
- headers.append(line.slice(0, separator).trim(), line.slice(separator + 1).trim());
4430
- }
4431
4758
  classifyInstrumentedResponse(new Response(this.responseText, {
4432
4759
  headers,
4433
4760
  status: this.status,
@@ -4450,11 +4777,17 @@ var createBeacon = (options) => {
4450
4777
  }
4451
4778
  if (instrument.history !== false && typeof history !== "undefined") {
4452
4779
  let recordedHistoryUrl = location.href;
4453
- const record = () => {
4780
+ const record = (from, type) => {
4454
4781
  addBreadcrumb({
4455
4782
  message: `navigate ${location.pathname}${location.search}`,
4456
4783
  type: "navigation"
4457
4784
  });
4785
+ recentNavigation = {
4786
+ from: shortUrl(from),
4787
+ performanceAt: performance.now(),
4788
+ to: shortUrl(location.href),
4789
+ type
4790
+ };
4458
4791
  recordedHistoryUrl = location.href;
4459
4792
  overflowScanOnNavigation?.();
4460
4793
  };
@@ -4476,7 +4809,7 @@ var createBeacon = (options) => {
4476
4809
  if (!changesUrl)
4477
4810
  return result;
4478
4811
  reportFormAbandonmentOnNavigation?.(departedUrl);
4479
- record();
4812
+ record(departedUrl, key);
4480
4813
  return result;
4481
4814
  };
4482
4815
  return () => {
@@ -4488,7 +4821,7 @@ var createBeacon = (options) => {
4488
4821
  if (location.href === recordedHistoryUrl)
4489
4822
  return;
4490
4823
  reportFormAbandonmentOnNavigation?.(recordedHistoryUrl);
4491
- record();
4824
+ record(recordedHistoryUrl, "popstate");
4492
4825
  };
4493
4826
  window.addEventListener("popstate", onPopState);
4494
4827
  cleanups.push(() => window.removeEventListener("popstate", onPopState));
@@ -4579,10 +4912,11 @@ export {
4579
4912
  createBeacon,
4580
4913
  getBeacon,
4581
4914
  initBeacon,
4915
+ isAutomatedBrowser,
4582
4916
  isKnownBeaconNoise,
4583
4917
  observeCapability,
4584
4918
  redactBeaconEvent
4585
4919
  };
4586
4920
 
4587
- //# debugId=5C89D1E136B8537164756E2164756E21
4921
+ //# debugId=70E392D07533AB9164756E2164756E21
4588
4922
  //# sourceMappingURL=index.js.map