@absolutejs/beacon 0.4.17 → 0.4.18

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
@@ -8,7 +8,10 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
8
8
 
9
9
  // src/index.ts
10
10
  var BEACON_SIGNAL = {
11
+ AUTH_FAILURE_STORM: "auth_failure_storm",
12
+ BROWSER_INTERVENTION: "browser_intervention",
11
13
  CONSOLE_ERROR: "console_error",
14
+ CSP_VIOLATION: "csp_violation",
12
15
  DEAD_CLICK: "dead_click",
13
16
  FETCH_FAILED: "fetch_failed",
14
17
  FOCUS_LOST: "focus_lost",
@@ -17,16 +20,23 @@ var BEACON_SIGNAL = {
17
20
  HTTP_5XX: "http_5xx",
18
21
  INVISIBLE_TEXT: "invisible_text",
19
22
  LAYOUT_OVERFLOW: "layout_overflow",
23
+ MAIN_THREAD_STALL: "main_thread_stall",
24
+ MODAL_FOCUS_ESCAPE: "modal_focus_escape",
20
25
  OCCLUDED_CONTROL: "occluded_control",
21
26
  RAGE_CLICK: "rage_click",
27
+ RATE_LIMITED: "rate_limited",
22
28
  RELOAD_LOOP: "reload_loop",
23
29
  REQUEST_STORM: "request_storm",
24
30
  SCROLL_JAIL: "scroll_jail",
25
31
  SLOW_RESPONSE: "slow_response",
32
+ SOCKET_ABNORMAL_CLOSE: "socket_abnormal_close",
26
33
  SOCKET_FLAPPING: "socket_flapping",
34
+ SSE_FLAPPING: "sse_flapping",
27
35
  STALE_RELEASE: "stale_release",
28
36
  STALLED_STREAM: "stalled_stream",
29
- STUCK_LOADING: "stuck_loading"
37
+ STUCK_LOADING: "stuck_loading",
38
+ SERVICE_WORKER_FAILURE: "service_worker_failure",
39
+ WORKER_FAILURE: "worker_failure"
30
40
  };
31
41
  var BEACON_ATTRIBUTE = {
32
42
  DEAD_CLICK: "data-beacon-dead-click",
@@ -197,9 +207,12 @@ var SENSITIVE_KEY_NAMES = new Set([
197
207
  "token"
198
208
  ]);
199
209
  var URL_KEY_NAMES = new Set([
210
+ "blockeduri",
200
211
  "endpoint",
201
212
  "errorfilename",
213
+ "reporturl",
202
214
  "resourceurl",
215
+ "sourcefile",
203
216
  "url"
204
217
  ]);
205
218
  var normalizeFieldName = (key) => key.replace(/[^a-z0-9]/gi, "").toLowerCase();
@@ -545,11 +558,19 @@ var createBeacon = (options) => {
545
558
  const SCROLL_JAIL_EVENT_COUNT = 8;
546
559
  const SCROLL_JAIL_WINDOW_MS = 2000;
547
560
  const SCROLL_JAIL_BOUNDARY_TOLERANCE_PX = 2;
561
+ const AUTH_FAILURE_STORM_DEFAULT_COUNT = 4;
562
+ const AUTH_FAILURE_STORM_DEFAULT_WINDOW_MS = 30000;
548
563
  const REQUEST_STORM_DEFAULT_COUNT = 15;
549
564
  const REQUEST_STORM_DEFAULT_WINDOW_MS = 1e4;
550
565
  const SOCKET_FLAP_CYCLES = 4;
551
566
  const SOCKET_FLAP_WINDOW_MS = 60000;
567
+ const SSE_FLAP_DEFAULT_COUNT = 4;
568
+ const SSE_FLAP_DEFAULT_WINDOW_MS = 60000;
552
569
  const STALLED_STREAM_DEFAULT_MS = 60000;
570
+ const MODAL_FOCUS_SETTLE_MS = 100;
571
+ const MAIN_THREAD_STALL_DEFAULT_MS = 200;
572
+ const MAIN_THREAD_STALL_DEFAULT_COUNT = 3;
573
+ const MAIN_THREAD_STALL_DEFAULT_WINDOW_MS = 1e4;
553
574
  const RELOAD_LOOP_COUNT = 4;
554
575
  const RELOAD_LOOP_WINDOW_MS = 60000;
555
576
  const RELOAD_LOOP_STORAGE_KEY = "beacon:reload-times";
@@ -788,6 +809,33 @@ var createBeacon = (options) => {
788
809
  const traceId = value?.trim().toLowerCase();
789
810
  return traceId !== undefined && /^[0-9a-f]{32}$/.test(traceId) ? traceId : undefined;
790
811
  };
812
+ const authFailureStormCount = signals?.authFailureStormCount ?? AUTH_FAILURE_STORM_DEFAULT_COUNT;
813
+ const authFailureStormWindowMs = signals?.authFailureStormWindowMs ?? AUTH_FAILURE_STORM_DEFAULT_WINDOW_MS;
814
+ const authFailuresByEndpoint = new Map;
815
+ const reportedAuthFailureStorms = new Set;
816
+ const recordAuthFailure = (endpoint2, method, status) => {
817
+ if (signals === null || signals.authFailureStorms === false)
818
+ return false;
819
+ const label = `${method} ${endpoint2}`;
820
+ const now = Date.now();
821
+ const failures = (authFailuresByEndpoint.get(label) ?? []).filter(({ at }) => now - at < authFailureStormWindowMs);
822
+ failures.push({ at: now, status });
823
+ authFailuresByEndpoint.set(label, failures);
824
+ if (failures.length < authFailureStormCount || reportedAuthFailureStorms.has(label)) {
825
+ return false;
826
+ }
827
+ reportedAuthFailureStorms.add(label);
828
+ const statuses = [...new Set(failures.map((failure) => failure.status))];
829
+ emitSignal(`Authorization failure storm — ${label} repeatedly rejected requests — ${shortUrl(location.href)}`, {
830
+ endpoint: endpoint2,
831
+ failureCount: String(failures.length),
832
+ method,
833
+ signal: BEACON_SIGNAL.AUTH_FAILURE_STORM,
834
+ statuses: statuses.join(","),
835
+ windowMs: String(authFailureStormWindowMs)
836
+ });
837
+ return true;
838
+ };
791
839
  const reportResponseSignal = (url, method, status, durationMs, traceId) => {
792
840
  if (signals === null)
793
841
  return;
@@ -802,6 +850,18 @@ var createBeacon = (options) => {
802
850
  }, traceId);
803
851
  return;
804
852
  }
853
+ if (signals.rateLimits !== false && status === 429) {
854
+ emitSignal(`Rate limited — ${responseMethod} ${responseEndpoint} returned 429`, {
855
+ endpoint: responseEndpoint,
856
+ method: responseMethod,
857
+ signal: BEACON_SIGNAL.RATE_LIMITED,
858
+ status: String(status)
859
+ }, traceId);
860
+ return;
861
+ }
862
+ if ((status === 401 || status === 403) && recordAuthFailure(responseEndpoint, responseMethod, status)) {
863
+ return;
864
+ }
805
865
  if (signals.slowResponses !== false && durationMs > slowResponseMs) {
806
866
  emitSignal(`Slow response — ${responseMethod} ${responseEndpoint}`, {
807
867
  durationMs: String(durationMs),
@@ -988,6 +1048,108 @@ var createBeacon = (options) => {
988
1048
  }, DEAD_CLICK_WINDOW_MS);
989
1049
  };
990
1050
  const clickSignalMessage = (message, control) => `${message} — ${shortUrl(location.href)} — ${describeElement(control)}`;
1051
+ if (signals !== null && signals.cspViolations !== false && typeof document !== "undefined") {
1052
+ const reportedViolations = new Set;
1053
+ const onSecurityPolicyViolation = (event) => {
1054
+ const violation = event;
1055
+ if (violation.disposition !== "enforce")
1056
+ return;
1057
+ const directive = violation.effectiveDirective || violation.violatedDirective || "unknown";
1058
+ const blockedUri = violation.blockedURI || "unknown";
1059
+ const key = `${directive}|${blockedUri}`;
1060
+ if (reportedViolations.has(key))
1061
+ return;
1062
+ reportedViolations.add(key);
1063
+ emitSignal(`CSP violation — ${directive} blocked a resource — ${shortUrl(location.href)}`, {
1064
+ blockedUri,
1065
+ directive,
1066
+ disposition: violation.disposition,
1067
+ signal: BEACON_SIGNAL.CSP_VIOLATION,
1068
+ ...violation.sourceFile === "" ? {} : { sourceFile: violation.sourceFile },
1069
+ ...violation.lineNumber > 0 ? { sourceLine: String(violation.lineNumber) } : {}
1070
+ });
1071
+ };
1072
+ document.addEventListener("securitypolicyviolation", onSecurityPolicyViolation);
1073
+ cleanups.push(() => document.removeEventListener("securitypolicyviolation", onSecurityPolicyViolation));
1074
+ }
1075
+ if (signals !== null && signals.browserInterventions !== false && typeof ReportingObserver !== "undefined") {
1076
+ try {
1077
+ const reportedInterventions = new Set;
1078
+ const observer = new ReportingObserver((reports) => {
1079
+ for (const report of reports) {
1080
+ if (report.type !== "intervention")
1081
+ continue;
1082
+ const body = report.body;
1083
+ const interventionId = typeof body.id === "string" && body.id !== "" ? body.id.slice(0, SIGNAL_TEXT_MAX) : "browser-intervention";
1084
+ const reportUrl = report.url || location.href;
1085
+ const key = `${interventionId}|${shortUrl(reportUrl)}`;
1086
+ if (reportedInterventions.has(key))
1087
+ continue;
1088
+ reportedInterventions.add(key);
1089
+ emitSignal(`Browser intervention — ${interventionId} — ${shortUrl(location.href)}`, {
1090
+ interventionId,
1091
+ reportUrl,
1092
+ signal: BEACON_SIGNAL.BROWSER_INTERVENTION,
1093
+ ...typeof body.sourceFile === "string" ? { sourceFile: body.sourceFile } : {},
1094
+ ...typeof body.lineNumber === "number" ? { sourceLine: String(body.lineNumber) } : {}
1095
+ }, undefined, {
1096
+ ...typeof body.message === "string" ? {
1097
+ interventionMessage: body.message.slice(0, SIGNAL_TEXT_MAX)
1098
+ } : {}
1099
+ });
1100
+ }
1101
+ }, { buffered: true, types: ["intervention"] });
1102
+ observer.observe();
1103
+ cleanups.push(() => observer.disconnect());
1104
+ } catch {}
1105
+ }
1106
+ if (signals !== null && signals.mainThreadStalls !== false && typeof PerformanceObserver !== "undefined") {
1107
+ const stallMs = signals.mainThreadStallMs ?? MAIN_THREAD_STALL_DEFAULT_MS;
1108
+ const stallCount = signals.mainThreadStallCount ?? MAIN_THREAD_STALL_DEFAULT_COUNT;
1109
+ const stallWindowMs = signals.mainThreadStallWindowMs ?? MAIN_THREAD_STALL_DEFAULT_WINDOW_MS;
1110
+ let stallTimes = [];
1111
+ let reported = false;
1112
+ try {
1113
+ const observer = new PerformanceObserver((list) => {
1114
+ if (reported || document.visibilityState === "hidden")
1115
+ return;
1116
+ for (const entry of list.getEntries()) {
1117
+ if (entry.duration < stallMs)
1118
+ continue;
1119
+ const now = Date.now();
1120
+ stallTimes = stallTimes.filter((at) => now - at < stallWindowMs);
1121
+ stallTimes.push(now);
1122
+ if (stallTimes.length < stallCount)
1123
+ continue;
1124
+ reported = true;
1125
+ emitSignal(`Main-thread stall — repeated long frames blocked the page — ${shortUrl(location.href)}`, {
1126
+ durationMs: String(Math.round(entry.duration)),
1127
+ entryType: entry.entryType,
1128
+ signal: BEACON_SIGNAL.MAIN_THREAD_STALL,
1129
+ stallCount: String(stallTimes.length),
1130
+ windowMs: String(stallWindowMs)
1131
+ });
1132
+ break;
1133
+ }
1134
+ });
1135
+ const supportedTypes = PerformanceObserver.supportedEntryTypes;
1136
+ let observing = false;
1137
+ if (supportedTypes?.includes("long-animation-frame")) {
1138
+ observer.observe({ buffered: true, type: "long-animation-frame" });
1139
+ observing = true;
1140
+ } else if (supportedTypes?.includes("longtask")) {
1141
+ observer.observe({ buffered: true, type: "longtask" });
1142
+ observing = true;
1143
+ } else if (supportedTypes === undefined || supportedTypes.length === 0) {
1144
+ observer.observe({ buffered: true, type: "long-animation-frame" });
1145
+ observing = true;
1146
+ } else {
1147
+ observer.disconnect();
1148
+ }
1149
+ if (observing)
1150
+ cleanups.push(() => observer.disconnect());
1151
+ } catch {}
1152
+ }
991
1153
  if (instrument.globalErrors !== false) {
992
1154
  const onError = (event) => {
993
1155
  if (event instanceof ErrorEvent) {
@@ -1564,12 +1726,47 @@ var createBeacon = (options) => {
1564
1726
  document.addEventListener("wheel", onWheel, { passive: true });
1565
1727
  cleanups.push(() => document.removeEventListener("wheel", onWheel));
1566
1728
  }
1567
- if (signals.focusLoss !== false) {
1729
+ if (signals.focusLoss !== false || signals.modalFocusEscape !== false) {
1568
1730
  const DIALOG_SELECTOR = '[role="dialog"], [aria-modal="true"], dialog';
1731
+ const MODAL_SELECTOR = '[aria-modal="true"], dialog[open]';
1569
1732
  let lastDialogFocus = null;
1570
1733
  const reportedFocusLoss = new Set;
1734
+ const reportedModalEscapes = new WeakSet;
1735
+ const modalTimers = new Set;
1736
+ const reportModalEscape = (modal, active, reason) => {
1737
+ if (signals.modalFocusEscape === false || reportedModalEscapes.has(modal) || document.visibilityState === "hidden") {
1738
+ return;
1739
+ }
1740
+ reportedModalEscapes.add(modal);
1741
+ const modalDescriptor = describeElement(modal);
1742
+ emitSignal(`Modal focus escape — ${modalDescriptor} did not contain keyboard focus — ${shortUrl(location.href)}`, {
1743
+ modal: modalDescriptor,
1744
+ reason,
1745
+ signal: BEACON_SIGNAL.MODAL_FOCUS_ESCAPE,
1746
+ target: active === null ? "none" : describeElement(active)
1747
+ });
1748
+ };
1749
+ const openModals = () => Array.from(document.querySelectorAll(MODAL_SELECTOR));
1750
+ const checkInitialModalFocus = (modal) => {
1751
+ const timer2 = setTimeout(() => {
1752
+ modalTimers.delete(timer2);
1753
+ if (!modal.isConnected || !modal.matches(MODAL_SELECTOR))
1754
+ return;
1755
+ const active = document.activeElement instanceof Element ? document.activeElement : null;
1756
+ if (active !== null && modal.contains(active))
1757
+ return;
1758
+ reportModalEscape(modal, active, "initial-focus-missing");
1759
+ }, MODAL_FOCUS_SETTLE_MS);
1760
+ modalTimers.add(timer2);
1761
+ };
1571
1762
  const onFocusIn = (event) => {
1572
1763
  const target = event.target;
1764
+ if (signals.modalFocusEscape !== false && target instanceof Element) {
1765
+ const modals = openModals();
1766
+ if (modals.length > 0 && !modals.some((modal) => modal.contains(target))) {
1767
+ reportModalEscape(modals[modals.length - 1], target, "escaped");
1768
+ }
1769
+ }
1573
1770
  lastDialogFocus = target instanceof Element && target.closest(DIALOG_SELECTOR) !== null ? target : null;
1574
1771
  };
1575
1772
  const onFocusOut = () => {
@@ -1590,9 +1787,40 @@ var createBeacon = (options) => {
1590
1787
  };
1591
1788
  document.addEventListener("focusin", onFocusIn, true);
1592
1789
  document.addEventListener("focusout", onFocusOut, true);
1790
+ let modalObserver;
1791
+ if (signals.modalFocusEscape !== false && typeof MutationObserver !== "undefined") {
1792
+ for (const modal of openModals())
1793
+ checkInitialModalFocus(modal);
1794
+ modalObserver = new MutationObserver((records) => {
1795
+ for (const record of records) {
1796
+ if (record.type === "attributes" && record.target instanceof Element && record.target.matches(MODAL_SELECTOR)) {
1797
+ checkInitialModalFocus(record.target);
1798
+ }
1799
+ for (const added of Array.from(record.addedNodes)) {
1800
+ if (!(added instanceof Element))
1801
+ continue;
1802
+ if (added.matches(MODAL_SELECTOR))
1803
+ checkInitialModalFocus(added);
1804
+ for (const modal of Array.from(added.querySelectorAll(MODAL_SELECTOR))) {
1805
+ checkInitialModalFocus(modal);
1806
+ }
1807
+ }
1808
+ }
1809
+ });
1810
+ modalObserver.observe(document.documentElement, {
1811
+ attributeFilter: ["aria-modal", "open"],
1812
+ attributes: true,
1813
+ childList: true,
1814
+ subtree: true
1815
+ });
1816
+ }
1593
1817
  cleanups.push(() => {
1594
1818
  document.removeEventListener("focusin", onFocusIn, true);
1595
1819
  document.removeEventListener("focusout", onFocusOut, true);
1820
+ modalObserver?.disconnect();
1821
+ for (const timer2 of modalTimers)
1822
+ clearTimeout(timer2);
1823
+ modalTimers.clear();
1596
1824
  });
1597
1825
  }
1598
1826
  if (signals.formFrustration !== false) {
@@ -1673,10 +1901,14 @@ var createBeacon = (options) => {
1673
1901
  });
1674
1902
  }
1675
1903
  }
1676
- if (signals !== null && signals.stalledStreams !== false && typeof window.EventSource === "function") {
1904
+ if (signals !== null && (signals.stalledStreams !== false || signals.sseFlapping !== false) && typeof window.EventSource === "function") {
1677
1905
  const stalledStreamMs = signals.stalledStreamMs ?? STALLED_STREAM_DEFAULT_MS;
1906
+ const sseFlapCount = signals.sseFlapCount ?? SSE_FLAP_DEFAULT_COUNT;
1907
+ const sseFlapWindowMs = signals.sseFlapWindowMs ?? SSE_FLAP_DEFAULT_WINDOW_MS;
1678
1908
  const OriginalEventSource = window.EventSource;
1679
1909
  const reportedStreams = new Set;
1910
+ const errorsByEndpoint = new Map;
1911
+ const reportedFlappingStreams = new Set;
1680
1912
  const instrumentSource = (source, endpointLabel) => {
1681
1913
  let stallTimer;
1682
1914
  const disarm = () => {
@@ -1684,6 +1916,8 @@ var createBeacon = (options) => {
1684
1916
  clearTimeout(stallTimer);
1685
1917
  };
1686
1918
  const check = () => {
1919
+ if (signals.stalledStreams === false)
1920
+ return;
1687
1921
  if (source.readyState !== OriginalEventSource.OPEN)
1688
1922
  return;
1689
1923
  if (document.visibilityState === "hidden") {
@@ -1699,8 +1933,30 @@ var createBeacon = (options) => {
1699
1933
  signal: BEACON_SIGNAL.STALLED_STREAM
1700
1934
  });
1701
1935
  };
1936
+ const recordError = () => {
1937
+ disarm();
1938
+ if (signals.sseFlapping === false || pageLifecycleEnding || document.visibilityState === "hidden") {
1939
+ return;
1940
+ }
1941
+ const now = Date.now();
1942
+ const errors = (errorsByEndpoint.get(endpointLabel) ?? []).filter((at) => now - at < sseFlapWindowMs);
1943
+ errors.push(now);
1944
+ errorsByEndpoint.set(endpointLabel, errors);
1945
+ if (errors.length < sseFlapCount || reportedFlappingStreams.has(endpointLabel)) {
1946
+ return;
1947
+ }
1948
+ reportedFlappingStreams.add(endpointLabel);
1949
+ emitSignal(`SSE flapping — ${endpointLabel} keeps failing and reconnecting — ${shortUrl(location.href)}`, {
1950
+ endpoint: endpointLabel,
1951
+ errorCount: String(errors.length),
1952
+ signal: BEACON_SIGNAL.SSE_FLAPPING,
1953
+ windowMs: String(sseFlapWindowMs)
1954
+ });
1955
+ };
1702
1956
  const arm = () => {
1703
1957
  disarm();
1958
+ if (signals.stalledStreams === false)
1959
+ return;
1704
1960
  stallTimer = setTimeout(check, stalledStreamMs);
1705
1961
  };
1706
1962
  const originalAddEventListener = source.addEventListener.bind(source);
@@ -1716,7 +1972,7 @@ var createBeacon = (options) => {
1716
1972
  };
1717
1973
  originalAddEventListener("open", arm);
1718
1974
  originalAddEventListener("message", arm);
1719
- originalAddEventListener("error", disarm);
1975
+ originalAddEventListener("error", recordError);
1720
1976
  const originalClose = source.close.bind(source);
1721
1977
  source.close = () => {
1722
1978
  disarm();
@@ -1738,17 +1994,32 @@ var createBeacon = (options) => {
1738
1994
  }
1739
1995
  });
1740
1996
  }
1741
- if (signals !== null && signals.socketFlapping !== false && typeof window.WebSocket === "function") {
1997
+ if (signals !== null && (signals.socketFlapping !== false || signals.socketAbnormalCloses !== false) && typeof window.WebSocket === "function") {
1742
1998
  const OriginalWebSocket = window.WebSocket;
1743
1999
  const closesByUrl = new Map;
1744
2000
  const reportedSockets = new Set;
2001
+ const reportedAbnormalCloses = new Set;
1745
2002
  const wrappedWebSocket = new Proxy(OriginalWebSocket, {
1746
2003
  construct(target, args) {
1747
2004
  const socket = Reflect.construct(target, args);
1748
2005
  const label = shortUrl(String(args[0]));
1749
- socket.addEventListener("close", () => {
2006
+ socket.addEventListener("close", (event) => {
1750
2007
  if (pageLifecycleEnding)
1751
2008
  return;
2009
+ if (signals.socketAbnormalCloses !== false && typeof CloseEvent !== "undefined" && event instanceof CloseEvent && (!event.wasClean || event.code !== 1000 && event.code !== 1001)) {
2010
+ const abnormalKey = `${label}|${event.code}`;
2011
+ if (!reportedAbnormalCloses.has(abnormalKey)) {
2012
+ reportedAbnormalCloses.add(abnormalKey);
2013
+ emitSignal(`Abnormal socket close — ${label} closed unexpectedly — ${shortUrl(location.href)}`, {
2014
+ closeCode: String(event.code),
2015
+ endpoint: label,
2016
+ signal: BEACON_SIGNAL.SOCKET_ABNORMAL_CLOSE,
2017
+ wasClean: String(event.wasClean)
2018
+ });
2019
+ }
2020
+ }
2021
+ if (signals.socketFlapping === false)
2022
+ return;
1752
2023
  const now = Date.now();
1753
2024
  const closes = (closesByUrl.get(label) ?? []).filter((at) => now - at < SOCKET_FLAP_WINDOW_MS);
1754
2025
  closes.push(now);
@@ -1774,6 +2045,168 @@ var createBeacon = (options) => {
1774
2045
  }
1775
2046
  });
1776
2047
  }
2048
+ if (signals !== null && signals.workerFailures !== false) {
2049
+ const reportedWorkerFailures = new Set;
2050
+ const workerListenerCleanups = [];
2051
+ cleanups.push(() => {
2052
+ for (const cleanup of workerListenerCleanups.splice(0, workerListenerCleanups.length)) {
2053
+ cleanup();
2054
+ }
2055
+ });
2056
+ const reportWorkerFailure = (workerType, endpointLabel, failureKind2, error) => {
2057
+ const key = `${workerType}|${endpointLabel}|${failureKind2}`;
2058
+ if (reportedWorkerFailures.has(key))
2059
+ return;
2060
+ reportedWorkerFailures.add(key);
2061
+ emitSignal(`Worker failure — ${workerType} worker ${endpointLabel} failed — ${shortUrl(location.href)}`, {
2062
+ endpoint: endpointLabel,
2063
+ failureKind: failureKind2,
2064
+ signal: BEACON_SIGNAL.WORKER_FAILURE,
2065
+ workerType
2066
+ }, undefined, error === undefined ? undefined : {
2067
+ workerError: {
2068
+ message: error.message,
2069
+ name: error.name,
2070
+ ...error.stack === undefined ? {} : { stack: error.stack }
2071
+ }
2072
+ });
2073
+ };
2074
+ if (typeof window.Worker === "function") {
2075
+ const OriginalWorker = window.Worker;
2076
+ const wrappedWorker = new Proxy(OriginalWorker, {
2077
+ construct(target, args) {
2078
+ const endpointLabel = shortUrl(String(args[0]));
2079
+ try {
2080
+ const worker = Reflect.construct(target, args);
2081
+ const onError = (event) => {
2082
+ const error = event instanceof ErrorEvent ? errorWithStack("WorkerError", event.message || "Worker runtime error", errorEventLocation(event)) : undefined;
2083
+ reportWorkerFailure("dedicated", endpointLabel, "error", error);
2084
+ };
2085
+ const onMessageError = () => reportWorkerFailure("dedicated", endpointLabel, "messageerror");
2086
+ worker.addEventListener("error", onError);
2087
+ worker.addEventListener("messageerror", onMessageError);
2088
+ workerListenerCleanups.push(() => {
2089
+ worker.removeEventListener("error", onError);
2090
+ worker.removeEventListener("messageerror", onMessageError);
2091
+ });
2092
+ return worker;
2093
+ } catch (error) {
2094
+ reportWorkerFailure("dedicated", endpointLabel, "construction", toError(error));
2095
+ throw error;
2096
+ }
2097
+ }
2098
+ });
2099
+ window.Worker = wrappedWorker;
2100
+ cleanups.push(() => {
2101
+ if (window.Worker === wrappedWorker)
2102
+ window.Worker = OriginalWorker;
2103
+ });
2104
+ }
2105
+ if (typeof window.SharedWorker === "function") {
2106
+ const OriginalSharedWorker = window.SharedWorker;
2107
+ const wrappedSharedWorker = new Proxy(OriginalSharedWorker, {
2108
+ construct(target, args) {
2109
+ const endpointLabel = shortUrl(String(args[0]));
2110
+ try {
2111
+ const worker = Reflect.construct(target, args);
2112
+ const onError = (event) => {
2113
+ const error = event instanceof ErrorEvent ? errorWithStack("WorkerError", event.message || "Shared worker runtime error", errorEventLocation(event)) : undefined;
2114
+ reportWorkerFailure("shared", endpointLabel, "error", error);
2115
+ };
2116
+ const onMessageError = () => reportWorkerFailure("shared", endpointLabel, "messageerror");
2117
+ worker.addEventListener("error", onError);
2118
+ worker.port.addEventListener("messageerror", onMessageError);
2119
+ workerListenerCleanups.push(() => {
2120
+ worker.removeEventListener("error", onError);
2121
+ worker.port.removeEventListener("messageerror", onMessageError);
2122
+ });
2123
+ return worker;
2124
+ } catch (error) {
2125
+ reportWorkerFailure("shared", endpointLabel, "construction", toError(error));
2126
+ throw error;
2127
+ }
2128
+ }
2129
+ });
2130
+ window.SharedWorker = wrappedSharedWorker;
2131
+ cleanups.push(() => {
2132
+ if (window.SharedWorker === wrappedSharedWorker) {
2133
+ window.SharedWorker = OriginalSharedWorker;
2134
+ }
2135
+ });
2136
+ }
2137
+ }
2138
+ if (signals !== null && signals.serviceWorkerFailures !== false && typeof navigator !== "undefined" && "serviceWorker" in navigator) {
2139
+ try {
2140
+ const container = navigator.serviceWorker;
2141
+ const reportedServiceWorkerFailures = new Set;
2142
+ const serviceWorkerListenerCleanups = [];
2143
+ const reportServiceWorkerFailure = (endpointLabel, failureKind2, error) => {
2144
+ const key = `${endpointLabel}|${failureKind2}`;
2145
+ if (reportedServiceWorkerFailures.has(key))
2146
+ return;
2147
+ reportedServiceWorkerFailures.add(key);
2148
+ emitSignal(`Service worker failure — ${endpointLabel} failed during ${failureKind2} — ${shortUrl(location.href)}`, {
2149
+ endpoint: endpointLabel,
2150
+ failureKind: failureKind2,
2151
+ signal: BEACON_SIGNAL.SERVICE_WORKER_FAILURE
2152
+ }, undefined, error === undefined ? undefined : {
2153
+ serviceWorkerError: {
2154
+ message: error.message,
2155
+ name: error.name,
2156
+ ...error.stack === undefined ? {} : { stack: error.stack }
2157
+ }
2158
+ });
2159
+ };
2160
+ const watchInstallingWorker = (worker) => {
2161
+ let activated = worker.state === "activated";
2162
+ const onStateChange = () => {
2163
+ if (worker.state === "activated")
2164
+ activated = true;
2165
+ if (worker.state !== "redundant" || activated)
2166
+ return;
2167
+ reportServiceWorkerFailure(shortUrl(worker.scriptURL), "installation");
2168
+ };
2169
+ worker.addEventListener("statechange", onStateChange);
2170
+ serviceWorkerListenerCleanups.push(() => worker.removeEventListener("statechange", onStateChange));
2171
+ };
2172
+ const watchRegistration = (registration) => {
2173
+ if (registration.installing !== null) {
2174
+ watchInstallingWorker(registration.installing);
2175
+ }
2176
+ const onUpdateFound = () => {
2177
+ if (registration.installing !== null) {
2178
+ watchInstallingWorker(registration.installing);
2179
+ }
2180
+ };
2181
+ registration.addEventListener("updatefound", onUpdateFound);
2182
+ serviceWorkerListenerCleanups.push(() => registration.removeEventListener("updatefound", onUpdateFound));
2183
+ };
2184
+ const originalRegister = container.register;
2185
+ const wrappedRegister = async function(scriptURL, registrationOptions) {
2186
+ const endpointLabel = shortUrl(String(scriptURL));
2187
+ try {
2188
+ const registration = await originalRegister.call(this, scriptURL, registrationOptions);
2189
+ watchRegistration(registration);
2190
+ return registration;
2191
+ } catch (error) {
2192
+ reportServiceWorkerFailure(endpointLabel, "registration", toError(error));
2193
+ throw error;
2194
+ }
2195
+ };
2196
+ container.register = wrappedRegister;
2197
+ const onMessageError = () => reportServiceWorkerFailure("service-worker", "messageerror");
2198
+ container.addEventListener("messageerror", onMessageError);
2199
+ cleanups.push(() => {
2200
+ container.removeEventListener("messageerror", onMessageError);
2201
+ for (const cleanup of serviceWorkerListenerCleanups.splice(0, serviceWorkerListenerCleanups.length)) {
2202
+ cleanup();
2203
+ }
2204
+ if (container.register === wrappedRegister) {
2205
+ container.register = originalRegister;
2206
+ }
2207
+ });
2208
+ } catch {}
2209
+ }
1777
2210
  if (signals !== null && signals.reloadLoops !== false && typeof sessionStorage !== "undefined") {
1778
2211
  try {
1779
2212
  const now = Date.now();
@@ -2036,5 +2469,5 @@ export {
2036
2469
  BEACON_ATTRIBUTE
2037
2470
  };
2038
2471
 
2039
- //# debugId=9933C27D67CFEF2364756E2164756E21
2472
+ //# debugId=9FE1CDE5E81701FA64756E2164756E21
2040
2473
  //# sourceMappingURL=index.js.map