@absolutejs/beacon 0.4.13 → 0.4.14

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
@@ -11,15 +11,28 @@ var BEACON_SIGNAL = {
11
11
  CONSOLE_ERROR: "console_error",
12
12
  DEAD_CLICK: "dead_click",
13
13
  FETCH_FAILED: "fetch_failed",
14
+ FOCUS_LOST: "focus_lost",
15
+ FONT_FAILURE: "font_failure",
16
+ FORM_FRUSTRATION: "form_frustration",
14
17
  HTTP_5XX: "http_5xx",
18
+ INVISIBLE_TEXT: "invisible_text",
15
19
  LAYOUT_OVERFLOW: "layout_overflow",
20
+ OCCLUDED_CONTROL: "occluded_control",
16
21
  RAGE_CLICK: "rage_click",
17
- SLOW_RESPONSE: "slow_response"
22
+ RELOAD_LOOP: "reload_loop",
23
+ REQUEST_STORM: "request_storm",
24
+ SCROLL_JAIL: "scroll_jail",
25
+ SLOW_RESPONSE: "slow_response",
26
+ SOCKET_FLAPPING: "socket_flapping",
27
+ STALE_RELEASE: "stale_release",
28
+ STALLED_STREAM: "stalled_stream",
29
+ STUCK_LOADING: "stuck_loading"
18
30
  };
19
31
  var BEACON_ATTRIBUTE = {
20
32
  DEAD_CLICK: "data-beacon-dead-click",
21
33
  NAME: "data-beacon-name",
22
- OVERFLOW: "data-beacon-overflow"
34
+ OVERFLOW: "data-beacon-overflow",
35
+ SCAN: "data-beacon-scan"
23
36
  };
24
37
  var BEACON_TRACE_HEADER = "x-absolute-trace-id";
25
38
  var inBrowser = () => typeof window !== "undefined";
@@ -353,6 +366,9 @@ var describeElement = (element) => {
353
366
  };
354
367
  var SHORT_URL_MAX = 80;
355
368
  var shortUrl = (url) => {
369
+ try {
370
+ return new URL(url).pathname;
371
+ } catch {}
356
372
  try {
357
373
  return new URL(url, location.origin).pathname;
358
374
  } catch {
@@ -520,6 +536,29 @@ var createBeacon = (options) => {
520
536
  const VIEWPORT_BUCKET_MD_PX = 768;
521
537
  const VIEWPORT_BUCKET_LG_PX = 1024;
522
538
  const VIEWPORT_BUCKET_XL_PX = 1440;
539
+ const OCCLUSION_SAMPLE_LIMIT = 25;
540
+ const OCCLUSION_COVERAGE_MIN = 0.9;
541
+ const INVISIBLE_TEXT_SAMPLE_LIMIT = 40;
542
+ const INVISIBLE_TEXT_CONTRAST_MAX = 1.2;
543
+ const STUCK_LOADING_DEFAULT_MS = 20000;
544
+ const STUCK_LOADING_POLL_MS = 5000;
545
+ const SCROLL_JAIL_EVENT_COUNT = 8;
546
+ const SCROLL_JAIL_WINDOW_MS = 2000;
547
+ const SCROLL_JAIL_BOUNDARY_TOLERANCE_PX = 2;
548
+ const REQUEST_STORM_DEFAULT_COUNT = 15;
549
+ const REQUEST_STORM_DEFAULT_WINDOW_MS = 1e4;
550
+ const SOCKET_FLAP_CYCLES = 4;
551
+ const SOCKET_FLAP_WINDOW_MS = 60000;
552
+ const STALLED_STREAM_DEFAULT_MS = 60000;
553
+ const RELOAD_LOOP_COUNT = 4;
554
+ const RELOAD_LOOP_WINDOW_MS = 60000;
555
+ const RELOAD_LOOP_STORAGE_KEY = "beacon:reload-times";
556
+ const STALE_RELEASE_STORAGE_KEY = "beacon:release-first-seen";
557
+ const STALE_RELEASE_GRACE_MS = 600000;
558
+ const STALE_RELEASE_HISTORY_LIMIT = 5;
559
+ const FORM_FRUSTRATION_THRESHOLD = 3;
560
+ const FORM_FRUSTRATION_WINDOW_MS = 60000;
561
+ const FORM_INVALID_BURST_GAP_MS = 100;
523
562
  const SIGNAL_TEXT_MAX = 180;
524
563
  const slowResponseMs = signals?.slowResponseMs ?? SLOW_RESPONSE_DEFAULT_MS;
525
564
  const navigationResponseMs = Math.max(DEAD_CLICK_WINDOW_MS, signals?.navigationResponseMs ?? NAVIGATION_RESPONSE_DEFAULT_MS);
@@ -529,6 +568,7 @@ var createBeacon = (options) => {
529
568
  let inSignalConsole = false;
530
569
  let pageLifecycleEnding = false;
531
570
  let overflowScanOnNavigation = null;
571
+ let recordRequestForStorm = null;
532
572
  const vitalsOptions = options.vitals === undefined || options.vitals === false ? null : options.vitals === true ? {} : options.vitals;
533
573
  if (vitalsOptions !== null) {
534
574
  const vitalsEndpoint = vitalsOptions.endpoint ?? "/ingest/vitals";
@@ -1067,9 +1107,14 @@ var createBeacon = (options) => {
1067
1107
  document.addEventListener("click", onClick, true);
1068
1108
  cleanups.push(() => document.removeEventListener("click", onClick, true));
1069
1109
  }
1070
- if (signals !== null && signals.layoutOverflows !== false && typeof document !== "undefined" && typeof window.getComputedStyle === "function") {
1110
+ if (signals !== null && typeof document !== "undefined" && typeof window.getComputedStyle === "function") {
1111
+ const detectOverflow = signals.layoutOverflows !== false;
1112
+ const detectOcclusion = signals.occludedControls !== false;
1113
+ const detectInvisibleText = signals.invisibleText !== false;
1114
+ const detectStuckLoading = signals.stuckLoading !== false;
1071
1115
  const overflowSettleMs = signals.layoutOverflowSettleMs ?? LAYOUT_OVERFLOW_SETTLE_DEFAULT_MS;
1072
1116
  const overflowMaxReports = signals.layoutOverflowMaxReports ?? LAYOUT_OVERFLOW_MAX_REPORTS_DEFAULT;
1117
+ const stuckLoadingMs = signals.stuckLoadingMs ?? STUCK_LOADING_DEFAULT_MS;
1073
1118
  const seenOverflows = new Set;
1074
1119
  let overflowReports = 0;
1075
1120
  let overflowTimer;
@@ -1085,6 +1130,27 @@ var createBeacon = (options) => {
1085
1130
  return "lg";
1086
1131
  return "xl";
1087
1132
  };
1133
+ const isScanExempt = (element) => element.closest(`[${BEACON_ATTRIBUTE.SCAN}="allow"]`) !== null;
1134
+ const seenScanIssues = new Set;
1135
+ let scanIssueReports = 0;
1136
+ const SCAN_ISSUE_MAX_REPORTS = 10;
1137
+ const reportScanIssue = (element, signal, detail, extraTags) => {
1138
+ const bucket = viewportBucket();
1139
+ const key = `${signal}:${describeElement(element)}@${bucket}`;
1140
+ if (seenScanIssues.has(key))
1141
+ return;
1142
+ if (scanIssueReports >= SCAN_ISSUE_MAX_REPORTS)
1143
+ return;
1144
+ seenScanIssues.add(key);
1145
+ scanIssueReports += 1;
1146
+ emitSignal(`${detail} — ${shortUrl(location.href)} [${bucket}]`, {
1147
+ ...extraTags,
1148
+ signal,
1149
+ target: describeElement(element),
1150
+ viewportBucket: bucket,
1151
+ viewportWidth: String(document.documentElement.clientWidth)
1152
+ });
1153
+ };
1088
1154
  const reportOverflow = (element, kind, detail, spillPx) => {
1089
1155
  const bucket = viewportBucket();
1090
1156
  const key = `${kind}:${describeElement(element)}@${bucket}`;
@@ -1148,12 +1214,174 @@ var createBeacon = (options) => {
1148
1214
  };
1149
1215
  visit(body, null);
1150
1216
  };
1217
+ const scanForOcclusion = () => {
1218
+ if (typeof document.elementFromPoint !== "function")
1219
+ return;
1220
+ if (document.querySelector('[aria-modal="true"], dialog[open]') !== null) {
1221
+ return;
1222
+ }
1223
+ const viewportWidth = document.documentElement.clientWidth;
1224
+ const viewportHeight = document.documentElement.clientHeight;
1225
+ const controls = document.querySelectorAll('a[href], button, input, select, textarea, [role="button"]');
1226
+ let sampled = 0;
1227
+ for (const control of Array.from(controls)) {
1228
+ if (sampled >= OCCLUSION_SAMPLE_LIMIT)
1229
+ return;
1230
+ if (isScanExempt(control))
1231
+ continue;
1232
+ const rect = control.getBoundingClientRect();
1233
+ if (rect.width === 0 || rect.height === 0)
1234
+ continue;
1235
+ if (rect.left < 0 || rect.top < 0 || rect.right > viewportWidth || rect.bottom > viewportHeight) {
1236
+ continue;
1237
+ }
1238
+ sampled += 1;
1239
+ const top = document.elementFromPoint((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2);
1240
+ if (top === null || top === control || control.contains(top) || top.contains(control)) {
1241
+ continue;
1242
+ }
1243
+ const topRect = top.getBoundingClientRect();
1244
+ const overlapX = Math.min(rect.right, topRect.right) - Math.max(rect.left, topRect.left);
1245
+ const overlapY = Math.min(rect.bottom, topRect.bottom) - Math.max(rect.top, topRect.top);
1246
+ const coverage = Math.max(overlapX, 0) * Math.max(overlapY, 0) / (rect.width * rect.height);
1247
+ if (coverage < OCCLUSION_COVERAGE_MIN)
1248
+ continue;
1249
+ reportScanIssue(control, BEACON_SIGNAL.OCCLUDED_CONTROL, `Occluded control — ${describeElement(control)} is covered by ${describeElement(top)}`, { coveredBy: describeElement(top) });
1250
+ }
1251
+ };
1252
+ const parseColor = (value) => {
1253
+ const match = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[\s,/]+([\d.]+))?\s*\)$/u.exec(value);
1254
+ if (match === null)
1255
+ return null;
1256
+ return {
1257
+ a: match[4] === undefined ? 1 : Number(match[4]),
1258
+ b: Number(match[3]),
1259
+ g: Number(match[2]),
1260
+ r: Number(match[1])
1261
+ };
1262
+ };
1263
+ const channelLuminance = (channel) => {
1264
+ const scaled = channel / 255;
1265
+ return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;
1266
+ };
1267
+ const relativeLuminance = (color) => 0.2126 * channelLuminance(color.r) + 0.7152 * channelLuminance(color.g) + 0.0722 * channelLuminance(color.b);
1268
+ const compositeOver = (top, bottom) => {
1269
+ const alpha = top.a + bottom.a * (1 - top.a);
1270
+ if (alpha === 0)
1271
+ return { a: 0, b: 0, g: 0, r: 0 };
1272
+ const blend = (topChannel, bottomChannel) => (topChannel * top.a + bottomChannel * bottom.a * (1 - top.a)) / alpha;
1273
+ return {
1274
+ a: alpha,
1275
+ b: blend(top.b, bottom.b),
1276
+ g: blend(top.g, bottom.g),
1277
+ r: blend(top.r, bottom.r)
1278
+ };
1279
+ };
1280
+ const effectiveBackground = (element) => {
1281
+ let accumulated = null;
1282
+ let node = element;
1283
+ while (node !== null) {
1284
+ const style = window.getComputedStyle(node);
1285
+ if (style.backgroundImage !== "none" && style.backgroundImage !== "") {
1286
+ return null;
1287
+ }
1288
+ const background = parseColor(style.backgroundColor);
1289
+ if (background !== null && background.a > 0) {
1290
+ accumulated = accumulated === null ? background : compositeOver(accumulated, background);
1291
+ if (accumulated.a >= 0.999)
1292
+ return accumulated;
1293
+ }
1294
+ node = node.parentElement;
1295
+ }
1296
+ return null;
1297
+ };
1298
+ const scanForInvisibleText = () => {
1299
+ const viewportWidth = document.documentElement.clientWidth;
1300
+ const viewportHeight = document.documentElement.clientHeight;
1301
+ const candidates = document.querySelectorAll('h1, h2, h3, button, a[href], label, [role="button"]');
1302
+ let sampled = 0;
1303
+ for (const element of Array.from(candidates)) {
1304
+ if (sampled >= INVISIBLE_TEXT_SAMPLE_LIMIT)
1305
+ return;
1306
+ if (isScanExempt(element))
1307
+ continue;
1308
+ if ((element.textContent ?? "").trim() === "")
1309
+ continue;
1310
+ const rect = element.getBoundingClientRect();
1311
+ if (rect.width === 0 || rect.height === 0)
1312
+ continue;
1313
+ if (rect.bottom < 0 || rect.top > viewportHeight || rect.right < 0 || rect.left > viewportWidth) {
1314
+ continue;
1315
+ }
1316
+ const style = window.getComputedStyle(element);
1317
+ if (Number(style.opacity || "1") < 0.1)
1318
+ continue;
1319
+ const foreground = parseColor(style.color);
1320
+ if (foreground === null)
1321
+ continue;
1322
+ sampled += 1;
1323
+ const background = effectiveBackground(element);
1324
+ if (background === null)
1325
+ continue;
1326
+ const transparentText = foreground.a < 0.05;
1327
+ const contrast = (() => {
1328
+ const fgLuminance = relativeLuminance(foreground);
1329
+ const bgLuminance = relativeLuminance(background);
1330
+ const lighter = Math.max(fgLuminance, bgLuminance);
1331
+ const darker = Math.min(fgLuminance, bgLuminance);
1332
+ return (lighter + 0.05) / (darker + 0.05);
1333
+ })();
1334
+ if (!transparentText && contrast > INVISIBLE_TEXT_CONTRAST_MAX) {
1335
+ continue;
1336
+ }
1337
+ reportScanIssue(element, BEACON_SIGNAL.INVISIBLE_TEXT, `Invisible text — ${describeElement(element)} renders (nearly) the same color as its background`, {
1338
+ background: `rgb(${Math.round(background.r)},${Math.round(background.g)},${Math.round(background.b)})`,
1339
+ contrast: contrast.toFixed(2),
1340
+ foreground: style.color
1341
+ });
1342
+ }
1343
+ };
1344
+ const loadingFirstSeen = new WeakMap;
1345
+ const reportedStuckLoading = new WeakSet;
1346
+ const checkStuckLoading = () => {
1347
+ if (document.visibilityState === "hidden")
1348
+ return;
1349
+ const indicators = document.querySelectorAll('[aria-busy="true"], [role="progressbar"]');
1350
+ const now = Date.now();
1351
+ for (const indicator of Array.from(indicators)) {
1352
+ if (isScanExempt(indicator))
1353
+ continue;
1354
+ const rect = indicator.getBoundingClientRect();
1355
+ if (rect.width === 0 && rect.height === 0)
1356
+ continue;
1357
+ const firstSeen = loadingFirstSeen.get(indicator);
1358
+ if (firstSeen === undefined) {
1359
+ loadingFirstSeen.set(indicator, now);
1360
+ continue;
1361
+ }
1362
+ if (now - firstSeen < stuckLoadingMs || reportedStuckLoading.has(indicator)) {
1363
+ continue;
1364
+ }
1365
+ reportedStuckLoading.add(indicator);
1366
+ reportScanIssue(indicator, BEACON_SIGNAL.STUCK_LOADING, `Stuck loading — ${describeElement(indicator)} never resolved`, { visibleMs: String(now - firstSeen) });
1367
+ }
1368
+ };
1369
+ const runSettledScan = () => {
1370
+ if (detectOverflow)
1371
+ scanForOverflow();
1372
+ if (detectOcclusion)
1373
+ scanForOcclusion();
1374
+ if (detectInvisibleText)
1375
+ scanForInvisibleText();
1376
+ if (detectStuckLoading)
1377
+ checkStuckLoading();
1378
+ };
1151
1379
  const scheduleOverflowScan = () => {
1152
1380
  if (overflowTimer !== undefined)
1153
1381
  clearTimeout(overflowTimer);
1154
1382
  overflowTimer = setTimeout(() => {
1155
1383
  overflowTimer = undefined;
1156
- scanForOverflow();
1384
+ runSettledScan();
1157
1385
  }, overflowSettleMs);
1158
1386
  };
1159
1387
  if (document.readyState === "complete") {
@@ -1171,6 +1399,368 @@ var createBeacon = (options) => {
1171
1399
  if (overflowTimer !== undefined)
1172
1400
  clearTimeout(overflowTimer);
1173
1401
  });
1402
+ if (detectStuckLoading) {
1403
+ const stuckTimer = setInterval(checkStuckLoading, STUCK_LOADING_POLL_MS);
1404
+ stuckTimer.unref?.();
1405
+ cleanups.push(() => clearInterval(stuckTimer));
1406
+ }
1407
+ }
1408
+ if (signals !== null && typeof document !== "undefined") {
1409
+ if (signals.scrollJail !== false) {
1410
+ const nearestScrollable = (start) => {
1411
+ let node = start;
1412
+ while (node !== null && node !== document.body) {
1413
+ const style = window.getComputedStyle(node);
1414
+ const overflowY = style.overflowY;
1415
+ if ((overflowY === "auto" || overflowY === "scroll") && node.scrollHeight > node.clientHeight + 1) {
1416
+ return node;
1417
+ }
1418
+ node = node.parentElement;
1419
+ }
1420
+ return null;
1421
+ };
1422
+ let jailBurst = [];
1423
+ let jailScroller = null;
1424
+ const reportedScrollers = new Set;
1425
+ const onWheel = (event) => {
1426
+ if (event.ctrlKey || event.defaultPrevented || event.deltaY === 0) {
1427
+ jailBurst = [];
1428
+ return;
1429
+ }
1430
+ const target = event.target instanceof Element ? event.target : null;
1431
+ const scroller = nearestScrollable(target) ?? document.scrollingElement;
1432
+ if (!(scroller instanceof Element)) {
1433
+ jailBurst = [];
1434
+ return;
1435
+ }
1436
+ const scrollingDown = event.deltaY > 0;
1437
+ const canMove = scrollingDown ? scroller.scrollTop + scroller.clientHeight < scroller.scrollHeight - SCROLL_JAIL_BOUNDARY_TOLERANCE_PX : scroller.scrollTop > SCROLL_JAIL_BOUNDARY_TOLERANCE_PX;
1438
+ if (!canMove) {
1439
+ jailBurst = [];
1440
+ return;
1441
+ }
1442
+ const now = Date.now();
1443
+ if (jailScroller !== scroller) {
1444
+ jailScroller = scroller;
1445
+ jailBurst = [];
1446
+ }
1447
+ jailBurst = jailBurst.filter((entry) => now - entry.at < SCROLL_JAIL_WINDOW_MS);
1448
+ jailBurst.push({ at: now, position: scroller.scrollTop });
1449
+ if (jailBurst.length < SCROLL_JAIL_EVENT_COUNT)
1450
+ return;
1451
+ const first = jailBurst[0];
1452
+ const moved = first === undefined || jailBurst.some((entry) => entry.position !== first.position) || scroller.scrollTop !== first.position;
1453
+ jailBurst = [];
1454
+ if (moved)
1455
+ return;
1456
+ const descriptor = describeElement(scroller);
1457
+ if (reportedScrollers.has(descriptor))
1458
+ return;
1459
+ reportedScrollers.add(descriptor);
1460
+ emitSignal(`Scroll jail — ${descriptor} has scrollable content but never moves — ${shortUrl(location.href)}`, { signal: BEACON_SIGNAL.SCROLL_JAIL, target: descriptor });
1461
+ };
1462
+ document.addEventListener("wheel", onWheel, { passive: true });
1463
+ cleanups.push(() => document.removeEventListener("wheel", onWheel));
1464
+ }
1465
+ if (signals.focusLoss !== false) {
1466
+ const DIALOG_SELECTOR = '[role="dialog"], [aria-modal="true"], dialog';
1467
+ let lastDialogFocus = null;
1468
+ const reportedFocusLoss = new Set;
1469
+ const onFocusIn = (event) => {
1470
+ const target = event.target;
1471
+ lastDialogFocus = target instanceof Element && target.closest(DIALOG_SELECTOR) !== null ? target : null;
1472
+ };
1473
+ const onFocusOut = () => {
1474
+ const candidate = lastDialogFocus;
1475
+ if (candidate === null)
1476
+ return;
1477
+ setTimeout(() => {
1478
+ const active = document.activeElement;
1479
+ const focusDropped = active === null || active === document.body;
1480
+ if (!focusDropped || candidate.isConnected)
1481
+ return;
1482
+ const descriptor = describeElement(candidate);
1483
+ if (reportedFocusLoss.has(descriptor))
1484
+ return;
1485
+ reportedFocusLoss.add(descriptor);
1486
+ emitSignal(`Focus lost — a dialog closed and dropped keyboard focus on body — ${shortUrl(location.href)}`, { lastFocused: descriptor, signal: BEACON_SIGNAL.FOCUS_LOST });
1487
+ }, 0);
1488
+ };
1489
+ document.addEventListener("focusin", onFocusIn, true);
1490
+ document.addEventListener("focusout", onFocusOut, true);
1491
+ cleanups.push(() => {
1492
+ document.removeEventListener("focusin", onFocusIn, true);
1493
+ document.removeEventListener("focusout", onFocusOut, true);
1494
+ });
1495
+ }
1496
+ if (signals.formFrustration !== false) {
1497
+ const formActivity = new WeakMap;
1498
+ const reportedForms = new WeakSet;
1499
+ const activityFor = (form) => {
1500
+ const existing = formActivity.get(form);
1501
+ if (existing !== undefined)
1502
+ return existing;
1503
+ const created = {
1504
+ identicalSubmits: [],
1505
+ invalidBursts: [],
1506
+ lastData: null,
1507
+ lastInvalidAt: 0
1508
+ };
1509
+ formActivity.set(form, created);
1510
+ return created;
1511
+ };
1512
+ const serializeForm = (form) => {
1513
+ try {
1514
+ return Array.from(new FormData(form).entries()).map(([key, value]) => `${key}=${typeof value === "string" ? value : "file"}`).join("&");
1515
+ } catch {
1516
+ return null;
1517
+ }
1518
+ };
1519
+ const reportForm = (form, reason) => {
1520
+ if (reportedForms.has(form))
1521
+ return;
1522
+ reportedForms.add(form);
1523
+ emitSignal(`Form frustration — ${describeElement(form)} ${reason} — ${shortUrl(location.href)}`, {
1524
+ signal: BEACON_SIGNAL.FORM_FRUSTRATION,
1525
+ target: describeElement(form)
1526
+ });
1527
+ };
1528
+ const onSubmit = (event) => {
1529
+ const form = event.target;
1530
+ if (!(form instanceof HTMLFormElement))
1531
+ return;
1532
+ const data = serializeForm(form);
1533
+ if (data === null)
1534
+ return;
1535
+ const activity = activityFor(form);
1536
+ const now = Date.now();
1537
+ if (data !== activity.lastData) {
1538
+ activity.lastData = data;
1539
+ activity.identicalSubmits = [now];
1540
+ return;
1541
+ }
1542
+ activity.identicalSubmits = activity.identicalSubmits.filter((at) => now - at < FORM_FRUSTRATION_WINDOW_MS);
1543
+ activity.identicalSubmits.push(now);
1544
+ if (activity.identicalSubmits.length >= FORM_FRUSTRATION_THRESHOLD) {
1545
+ reportForm(form, "was submitted with identical values repeatedly");
1546
+ }
1547
+ };
1548
+ const onInvalid = (event) => {
1549
+ const control = event.target;
1550
+ const form = control instanceof HTMLInputElement || control instanceof HTMLSelectElement || control instanceof HTMLTextAreaElement ? control.form : null;
1551
+ if (form === null)
1552
+ return;
1553
+ const activity = activityFor(form);
1554
+ const now = Date.now();
1555
+ if (now - activity.lastInvalidAt < FORM_INVALID_BURST_GAP_MS) {
1556
+ activity.lastInvalidAt = now;
1557
+ return;
1558
+ }
1559
+ activity.lastInvalidAt = now;
1560
+ activity.invalidBursts = activity.invalidBursts.filter((at) => now - at < FORM_FRUSTRATION_WINDOW_MS);
1561
+ activity.invalidBursts.push(now);
1562
+ if (activity.invalidBursts.length >= FORM_FRUSTRATION_THRESHOLD) {
1563
+ reportForm(form, "keeps failing native validation");
1564
+ }
1565
+ };
1566
+ document.addEventListener("submit", onSubmit, true);
1567
+ document.addEventListener("invalid", onInvalid, true);
1568
+ cleanups.push(() => {
1569
+ document.removeEventListener("submit", onSubmit, true);
1570
+ document.removeEventListener("invalid", onInvalid, true);
1571
+ });
1572
+ }
1573
+ }
1574
+ if (signals !== null && signals.stalledStreams !== false && typeof window.EventSource === "function") {
1575
+ const stalledStreamMs = signals.stalledStreamMs ?? STALLED_STREAM_DEFAULT_MS;
1576
+ const OriginalEventSource = window.EventSource;
1577
+ const reportedStreams = new Set;
1578
+ const instrumentSource = (source, endpointLabel) => {
1579
+ let stallTimer;
1580
+ const disarm = () => {
1581
+ if (stallTimer !== undefined)
1582
+ clearTimeout(stallTimer);
1583
+ };
1584
+ const check = () => {
1585
+ if (source.readyState !== OriginalEventSource.OPEN)
1586
+ return;
1587
+ if (document.visibilityState === "hidden") {
1588
+ arm();
1589
+ return;
1590
+ }
1591
+ if (reportedStreams.has(endpointLabel))
1592
+ return;
1593
+ reportedStreams.add(endpointLabel);
1594
+ emitSignal(`Stalled stream — ${endpointLabel} is open but silent — ${shortUrl(location.href)}`, {
1595
+ endpoint: endpointLabel,
1596
+ quietMs: String(stalledStreamMs),
1597
+ signal: BEACON_SIGNAL.STALLED_STREAM
1598
+ });
1599
+ };
1600
+ const arm = () => {
1601
+ disarm();
1602
+ stallTimer = setTimeout(check, stalledStreamMs);
1603
+ };
1604
+ const originalAddEventListener = source.addEventListener.bind(source);
1605
+ const armedTypes = new Set(["error", "message", "open"]);
1606
+ source.addEventListener = (type, listener, options2) => {
1607
+ if (!armedTypes.has(type)) {
1608
+ armedTypes.add(type);
1609
+ originalAddEventListener(type, arm);
1610
+ }
1611
+ if (listener !== null) {
1612
+ originalAddEventListener(type, listener, options2);
1613
+ }
1614
+ };
1615
+ originalAddEventListener("open", arm);
1616
+ originalAddEventListener("message", arm);
1617
+ originalAddEventListener("error", disarm);
1618
+ const originalClose = source.close.bind(source);
1619
+ source.close = () => {
1620
+ disarm();
1621
+ originalClose();
1622
+ };
1623
+ arm();
1624
+ };
1625
+ const wrappedEventSource = new Proxy(OriginalEventSource, {
1626
+ construct(target, args) {
1627
+ const source = Reflect.construct(target, args);
1628
+ instrumentSource(source, shortUrl(String(args[0])));
1629
+ return source;
1630
+ }
1631
+ });
1632
+ window.EventSource = wrappedEventSource;
1633
+ cleanups.push(() => {
1634
+ if (window.EventSource === wrappedEventSource) {
1635
+ window.EventSource = OriginalEventSource;
1636
+ }
1637
+ });
1638
+ }
1639
+ if (signals !== null && signals.socketFlapping !== false && typeof window.WebSocket === "function") {
1640
+ const OriginalWebSocket = window.WebSocket;
1641
+ const closesByUrl = new Map;
1642
+ const reportedSockets = new Set;
1643
+ const wrappedWebSocket = new Proxy(OriginalWebSocket, {
1644
+ construct(target, args) {
1645
+ const socket = Reflect.construct(target, args);
1646
+ const label = shortUrl(String(args[0]));
1647
+ socket.addEventListener("close", () => {
1648
+ if (pageLifecycleEnding)
1649
+ return;
1650
+ const now = Date.now();
1651
+ const closes = (closesByUrl.get(label) ?? []).filter((at) => now - at < SOCKET_FLAP_WINDOW_MS);
1652
+ closes.push(now);
1653
+ closesByUrl.set(label, closes);
1654
+ if (closes.length < SOCKET_FLAP_CYCLES || reportedSockets.has(label)) {
1655
+ return;
1656
+ }
1657
+ reportedSockets.add(label);
1658
+ emitSignal(`Socket flapping — ${label} keeps connecting and closing — ${shortUrl(location.href)}`, {
1659
+ closeCount: String(closes.length),
1660
+ endpoint: label,
1661
+ signal: BEACON_SIGNAL.SOCKET_FLAPPING,
1662
+ windowMs: String(SOCKET_FLAP_WINDOW_MS)
1663
+ });
1664
+ });
1665
+ return socket;
1666
+ }
1667
+ });
1668
+ window.WebSocket = wrappedWebSocket;
1669
+ cleanups.push(() => {
1670
+ if (window.WebSocket === wrappedWebSocket) {
1671
+ window.WebSocket = OriginalWebSocket;
1672
+ }
1673
+ });
1674
+ }
1675
+ if (signals !== null && signals.reloadLoops !== false && typeof sessionStorage !== "undefined") {
1676
+ try {
1677
+ const now = Date.now();
1678
+ const raw = sessionStorage.getItem(RELOAD_LOOP_STORAGE_KEY);
1679
+ const parsed = raw === null ? [] : JSON.parse(raw);
1680
+ const times = (Array.isArray(parsed) ? parsed : []).filter((at) => typeof at === "number" && now - at < RELOAD_LOOP_WINDOW_MS);
1681
+ times.push(now);
1682
+ sessionStorage.setItem(RELOAD_LOOP_STORAGE_KEY, JSON.stringify(times));
1683
+ if (times.length >= RELOAD_LOOP_COUNT) {
1684
+ emitSignal(`Reload loop — repeated page loads within a minute — ${shortUrl(location.href)}`, {
1685
+ loadCount: String(times.length),
1686
+ signal: BEACON_SIGNAL.RELOAD_LOOP
1687
+ });
1688
+ }
1689
+ } catch {}
1690
+ }
1691
+ if (signals !== null && signals.staleReleases !== false && typeof localStorage !== "undefined" && typeof options.release === "string" && options.release !== "") {
1692
+ try {
1693
+ const currentRelease = options.release;
1694
+ const now = Date.now();
1695
+ const raw = localStorage.getItem(STALE_RELEASE_STORAGE_KEY);
1696
+ const parsed = raw === null ? {} : JSON.parse(raw);
1697
+ const firstSeenByRelease = {};
1698
+ if (parsed !== null && typeof parsed === "object") {
1699
+ for (const [release, at] of Object.entries(parsed)) {
1700
+ if (typeof at === "number")
1701
+ firstSeenByRelease[release] = at;
1702
+ }
1703
+ }
1704
+ const currentFirstSeen = firstSeenByRelease[currentRelease] ?? now;
1705
+ firstSeenByRelease[currentRelease] = currentFirstSeen;
1706
+ const newest = Object.entries(firstSeenByRelease).filter(([release, at]) => release !== currentRelease && at > currentFirstSeen).sort((left, right) => right[1] - left[1])[0];
1707
+ if (newest !== undefined && now - newest[1] > STALE_RELEASE_GRACE_MS) {
1708
+ emitSignal(`Stale release — this page is running a build older than one this browser already saw — ${shortUrl(location.href)}`, {
1709
+ currentRelease,
1710
+ newestRelease: newest[0],
1711
+ signal: BEACON_SIGNAL.STALE_RELEASE
1712
+ });
1713
+ }
1714
+ const trimmed = Object.fromEntries(Object.entries(firstSeenByRelease).sort((left, right) => right[1] - left[1]).slice(0, STALE_RELEASE_HISTORY_LIMIT));
1715
+ localStorage.setItem(STALE_RELEASE_STORAGE_KEY, JSON.stringify(trimmed));
1716
+ } catch {}
1717
+ }
1718
+ if (signals !== null && signals.fontFailures !== false && typeof document !== "undefined" && "fonts" in document) {
1719
+ const reportedFonts = new Set;
1720
+ const sweepFonts = () => {
1721
+ document.fonts.forEach((face) => {
1722
+ if (face.status !== "error" || reportedFonts.has(face.family))
1723
+ return;
1724
+ reportedFonts.add(face.family);
1725
+ emitSignal(`Font failure — ${face.family} failed to load — ${shortUrl(location.href)}`, { fontFamily: face.family, signal: BEACON_SIGNAL.FONT_FAILURE });
1726
+ });
1727
+ };
1728
+ const fontsReady = document.fonts.ready;
1729
+ if (fontsReady !== undefined) {
1730
+ fontsReady.then(sweepFonts).catch(() => {
1731
+ return;
1732
+ });
1733
+ }
1734
+ if (typeof document.fonts.addEventListener === "function") {
1735
+ document.fonts.addEventListener("loadingerror", sweepFonts);
1736
+ cleanups.push(() => document.fonts.removeEventListener("loadingerror", sweepFonts));
1737
+ }
1738
+ }
1739
+ if (signals !== null && signals.requestStorms !== false) {
1740
+ const stormWindowMs = signals.requestStormWindowMs ?? REQUEST_STORM_DEFAULT_WINDOW_MS;
1741
+ const stormCount = signals.requestStormCount ?? REQUEST_STORM_DEFAULT_COUNT;
1742
+ const hitsByEndpoint = new Map;
1743
+ const reportedStorms = new Set;
1744
+ recordRequestForStorm = (url, method) => {
1745
+ const label = `${method.toUpperCase()} ${shortUrl(url)}`;
1746
+ const now = Date.now();
1747
+ const hits = (hitsByEndpoint.get(label) ?? []).filter((at) => now - at < stormWindowMs);
1748
+ hits.push(now);
1749
+ hitsByEndpoint.set(label, hits);
1750
+ if (hits.length < stormCount || reportedStorms.has(label))
1751
+ return;
1752
+ reportedStorms.add(label);
1753
+ emitSignal(`Request storm — ${label} hit repeatedly within seconds — ${shortUrl(location.href)}`, {
1754
+ endpoint: shortUrl(url),
1755
+ method: method.toUpperCase(),
1756
+ requestCount: String(hits.length),
1757
+ signal: BEACON_SIGNAL.REQUEST_STORM,
1758
+ windowMs: String(stormWindowMs)
1759
+ });
1760
+ };
1761
+ cleanups.push(() => {
1762
+ recordRequestForStorm = null;
1763
+ });
1174
1764
  }
1175
1765
  if (instrument.fetch !== false && typeof window.fetch === "function") {
1176
1766
  const originalFetch = window.fetch;
@@ -1182,6 +1772,7 @@ var createBeacon = (options) => {
1182
1772
  return originalFetch(...args);
1183
1773
  const start = Date.now();
1184
1774
  networkRequestCount += 1;
1775
+ recordRequestForStorm?.(url, method);
1185
1776
  try {
1186
1777
  const response = await originalFetch(...args);
1187
1778
  addBreadcrumb({
@@ -1221,6 +1812,7 @@ var createBeacon = (options) => {
1221
1812
  if (request !== undefined && !request.url.includes(endpoint)) {
1222
1813
  const start = Date.now();
1223
1814
  networkRequestCount += 1;
1815
+ recordRequestForStorm?.(request.url, request.method);
1224
1816
  let outcome = "error";
1225
1817
  this.addEventListener("abort", () => {
1226
1818
  outcome = "aborted";
@@ -1342,5 +1934,5 @@ export {
1342
1934
  BEACON_ATTRIBUTE
1343
1935
  };
1344
1936
 
1345
- //# debugId=92E5FD994B7535B364756E2164756E21
1937
+ //# debugId=1E667C299C91D38F64756E2164756E21
1346
1938
  //# sourceMappingURL=index.js.map