@libo11y/rum 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +461 -2
  3. package/dist/actions/collector.d.ts +29 -0
  4. package/dist/actions/collector.js +260 -0
  5. package/dist/actions/naming.d.ts +15 -0
  6. package/dist/actions/naming.js +65 -0
  7. package/dist/actions/record.d.ts +13 -0
  8. package/dist/actions/record.js +28 -0
  9. package/dist/actions/settle.d.ts +28 -0
  10. package/dist/actions/settle.js +53 -0
  11. package/dist/attrs.d.ts +10 -0
  12. package/dist/attrs.js +12 -0
  13. package/dist/bind.d.ts +23 -0
  14. package/dist/bind.js +55 -0
  15. package/dist/bootstrap/buffer.d.ts +72 -0
  16. package/dist/bootstrap/buffer.js +95 -0
  17. package/dist/bootstrap/replay.d.ts +10 -0
  18. package/dist/bootstrap/replay.js +11 -0
  19. package/dist/bootstrap.d.ts +17 -0
  20. package/dist/bootstrap.js +33 -0
  21. package/dist/bus.d.ts +3 -0
  22. package/dist/bus.js +21 -0
  23. package/dist/config/clamp.d.ts +34 -0
  24. package/dist/config/clamp.js +79 -0
  25. package/dist/config/remote.d.ts +80 -0
  26. package/dist/config/remote.js +209 -0
  27. package/dist/context-manager.d.ts +8 -0
  28. package/dist/context-manager.js +29 -0
  29. package/dist/contracts/binding.d.ts +80 -0
  30. package/dist/contracts/binding.js +1 -0
  31. package/dist/contracts/retention.d.ts +28 -0
  32. package/dist/contracts/retention.js +1 -0
  33. package/dist/contracts/runtime.d.ts +154 -0
  34. package/dist/contracts/runtime.js +1 -0
  35. package/dist/contracts/session.d.ts +63 -0
  36. package/dist/contracts/session.js +1 -0
  37. package/dist/contracts/summary.d.ts +28 -0
  38. package/dist/contracts/summary.js +1 -0
  39. package/dist/contracts/views.d.ts +71 -0
  40. package/dist/contracts/views.js +1 -0
  41. package/dist/core-setup.d.ts +86 -0
  42. package/dist/core-setup.js +902 -0
  43. package/dist/core.d.ts +42 -0
  44. package/dist/core.js +35 -0
  45. package/dist/errors/breadcrumbs.d.ts +16 -0
  46. package/dist/errors/breadcrumbs.js +27 -0
  47. package/dist/errors/collector.d.ts +17 -0
  48. package/dist/errors/collector.js +186 -0
  49. package/dist/errors/normalize.d.ts +7 -0
  50. package/dist/errors/normalize.js +31 -0
  51. package/dist/errors/record.d.ts +20 -0
  52. package/dist/errors/record.js +46 -0
  53. package/dist/frustration/detect.d.ts +38 -0
  54. package/dist/frustration/detect.js +62 -0
  55. package/dist/ids.d.ts +2 -0
  56. package/dist/ids.js +2 -0
  57. package/dist/index.d.ts +19 -0
  58. package/dist/index.js +12 -0
  59. package/dist/internal.d.ts +28 -0
  60. package/dist/internal.js +26 -0
  61. package/dist/loaf.d.ts +15 -0
  62. package/dist/loaf.js +27 -0
  63. package/dist/options.d.ts +84 -0
  64. package/dist/options.js +1 -0
  65. package/dist/pending-spans.d.ts +29 -0
  66. package/dist/pending-spans.js +92 -0
  67. package/dist/query.d.ts +2 -0
  68. package/dist/query.js +19 -0
  69. package/dist/resources/collector.d.ts +76 -0
  70. package/dist/resources/collector.js +270 -0
  71. package/dist/resources/server-timing.d.ts +18 -0
  72. package/dist/resources/server-timing.js +21 -0
  73. package/dist/retention/buffer.d.ts +25 -0
  74. package/dist/retention/buffer.js +104 -0
  75. package/dist/retention/exporters.d.ts +17 -0
  76. package/dist/retention/exporters.js +67 -0
  77. package/dist/retention/sessions.d.ts +4 -0
  78. package/dist/retention/sessions.js +30 -0
  79. package/dist/session/local-store.d.ts +25 -0
  80. package/dist/session/local-store.js +91 -0
  81. package/dist/session/manager.d.ts +36 -0
  82. package/dist/session/manager.js +169 -0
  83. package/dist/session/sampling.d.ts +4 -0
  84. package/dist/session/sampling.js +20 -0
  85. package/dist/session/state.d.ts +4 -0
  86. package/dist/session/state.js +28 -0
  87. package/dist/settings.d.ts +8 -0
  88. package/dist/settings.js +36 -0
  89. package/dist/setup.d.ts +40 -0
  90. package/dist/setup.js +49 -0
  91. package/dist/span-processor.d.ts +38 -0
  92. package/dist/span-processor.js +125 -0
  93. package/dist/summary/accumulator.d.ts +25 -0
  94. package/dist/summary/accumulator.js +126 -0
  95. package/dist/version.d.ts +2 -0
  96. package/dist/version.js +2 -0
  97. package/dist/views/collector.d.ts +40 -0
  98. package/dist/views/collector.js +285 -0
  99. package/dist/views/history.d.ts +18 -0
  100. package/dist/views/history.js +42 -0
  101. package/dist/views/naming.d.ts +6 -0
  102. package/dist/views/naming.js +12 -0
  103. package/dist/views/paint.d.ts +12 -0
  104. package/dist/views/paint.js +15 -0
  105. package/dist/views/tracker.d.ts +28 -0
  106. package/dist/views/tracker.js +117 -0
  107. package/dist/vitals/attribution.d.ts +14 -0
  108. package/dist/vitals/attribution.js +60 -0
  109. package/dist/vitals/collector.d.ts +24 -0
  110. package/dist/vitals/collector.js +232 -0
  111. package/dist/vitals/lcp.d.ts +32 -0
  112. package/dist/vitals/lcp.js +49 -0
  113. package/dist/webext/chrome.d.ts +45 -0
  114. package/dist/webext/chrome.js +13 -0
  115. package/dist/webext/config-storage.d.ts +7 -0
  116. package/dist/webext/config-storage.js +47 -0
  117. package/dist/webext/scope.d.ts +22 -0
  118. package/dist/webext/scope.js +50 -0
  119. package/dist/webext/session-access.d.ts +13 -0
  120. package/dist/webext/session-access.js +9 -0
  121. package/dist/webext/session-store.d.ts +5 -0
  122. package/dist/webext/session-store.js +94 -0
  123. package/dist/webext/setup.d.ts +71 -0
  124. package/dist/webext/setup.js +193 -0
  125. package/dist/webext.d.ts +10 -0
  126. package/dist/webext.js +8 -0
  127. package/dist/wire.d.ts +13 -0
  128. package/dist/wire.js +30 -0
  129. package/package.json +57 -4
package/dist/core.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @libo11y/rum/core: the RUM core without the web, for a platform binding that is not a page, such
3
+ * as React Native's. setupRumCore runs RUM over a binding (contracts/binding.ts); the building
4
+ * blocks it composes are here for the binding's own collectors and stores. Nothing reachable from
5
+ * here imports a browser-only module or reads a browser global at module evaluation (core.test.ts
6
+ * enforces both), so a bundler that does not tree-shake, such as Metro, pulls in nothing a phone
7
+ * cannot run. For libo11y packages only: it follows the package version, carries no compatibility
8
+ * promise and has no API report.
9
+ */
10
+ export { actionSpanName, actionSpanStart, recordInstantAction } from "./actions/record.ts";
11
+ export { createSettleTracker, type SettleOptions, type SettleTimers, type SettleTracker, } from "./actions/settle.ts";
12
+ export { ATTR_SESSION_ID, ATTR_USER_ID, summaryCountKey, summaryVitalKey } from "./attrs.ts";
13
+ export { createBus } from "./bus.ts";
14
+ export { clampConfig, parseRemoteConfig, type RemoteConfigDocument, resolveLimits, } from "./config/clamp.ts";
15
+ export { CONFIG_STORAGE_KEY, createRemoteConfig, type RemoteConfig, type RemoteConfigConnection, remoteConfig, } from "./config/remote.ts";
16
+ export { rumContextManager } from "./context-manager.ts";
17
+ export type { RumBind, RumLifecycle, RumLifecycleHandlers, RumPlatformInfo, RumPlatformOptions, RumWrappers, } from "./contracts/binding.ts";
18
+ export type { RetentionBuffer, RetentionRouting } from "./contracts/retention.ts";
19
+ export type { CollectorName, EventBody, RequestStartHook, RumBus, RumCollector, RumRuntime, RumScope, RumSettings, RumSignal, } from "./contracts/runtime.ts";
20
+ export type { SessionDecision, SessionEvent, SessionManager, SessionState, SessionStore, } from "./contracts/session.ts";
21
+ export type { SummaryAccumulator, SummaryCountKey, SummaryView, VitalName } from "./contracts/summary.ts";
22
+ export type { ViewEvent, ViewStartOptions, ViewState, ViewTracker } from "./contracts/views.ts";
23
+ export { type ConfigCacheStorage, type RumCoreDeps, runtimeOf, SESSION_END_ELECTION_MILLIS, setupRumCore, } from "./core-setup.ts";
24
+ export { createBreadcrumbs } from "./errors/breadcrumbs.ts";
25
+ export { normalizeError } from "./errors/normalize.ts";
26
+ export { recordError, wasRecorded } from "./errors/record.ts";
27
+ export { createFrustrationDetector } from "./frustration/detect.ts";
28
+ export { randomUuid } from "./ids.ts";
29
+ export type { AddErrorOptions, Rum, RumOptions } from "./options.ts";
30
+ export { stripQuery } from "./query.ts";
31
+ export { createRetentionBuffer, RETENTION_QUEUE_DEFAULTS } from "./retention/buffer.ts";
32
+ export { retainingLogExporter, retainingSpanExporter, withRetention } from "./retention/exporters.ts";
33
+ export { sessionsIn } from "./retention/sessions.ts";
34
+ export { createSessionManager, type SessionManagerOptions } from "./session/manager.ts";
35
+ export { fnv1a32, sessionSampled } from "./session/sampling.ts";
36
+ export { parseSessionState, SESSION_STORAGE_KEY } from "./session/state.ts";
37
+ export { type ResolvedRum, resolveSettings } from "./settings.ts";
38
+ export { APP_LOAD_SPAN, type RumSpanProcessorOptions, rumSpanProcessor } from "./span-processor.ts";
39
+ export { createSummaryAccumulator, type SummaryOptions } from "./summary/accumulator.ts";
40
+ export { afterNextPaint, type PaintHost } from "./views/paint.ts";
41
+ export { createViewTracker, type ViewTrackerOptions } from "./views/tracker.ts";
42
+ export { gatewayTransportOptions, withWireParams } from "./wire.ts";
package/dist/core.js ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @libo11y/rum/core: the RUM core without the web, for a platform binding that is not a page, such
3
+ * as React Native's. setupRumCore runs RUM over a binding (contracts/binding.ts); the building
4
+ * blocks it composes are here for the binding's own collectors and stores. Nothing reachable from
5
+ * here imports a browser-only module or reads a browser global at module evaluation (core.test.ts
6
+ * enforces both), so a bundler that does not tree-shake, such as Metro, pulls in nothing a phone
7
+ * cannot run. For libo11y packages only: it follows the package version, carries no compatibility
8
+ * promise and has no API report.
9
+ */
10
+ export { actionSpanName, actionSpanStart, recordInstantAction } from "./actions/record.js";
11
+ export { createSettleTracker, } from "./actions/settle.js";
12
+ export { ATTR_SESSION_ID, ATTR_USER_ID, summaryCountKey, summaryVitalKey } from "./attrs.js";
13
+ export { createBus } from "./bus.js";
14
+ export { clampConfig, parseRemoteConfig, resolveLimits, } from "./config/clamp.js";
15
+ export { CONFIG_STORAGE_KEY, createRemoteConfig, remoteConfig, } from "./config/remote.js";
16
+ export { rumContextManager } from "./context-manager.js";
17
+ export { runtimeOf, SESSION_END_ELECTION_MILLIS, setupRumCore, } from "./core-setup.js";
18
+ export { createBreadcrumbs } from "./errors/breadcrumbs.js";
19
+ export { normalizeError } from "./errors/normalize.js";
20
+ export { recordError, wasRecorded } from "./errors/record.js";
21
+ export { createFrustrationDetector } from "./frustration/detect.js";
22
+ export { randomUuid } from "./ids.js";
23
+ export { stripQuery } from "./query.js";
24
+ export { createRetentionBuffer, RETENTION_QUEUE_DEFAULTS } from "./retention/buffer.js";
25
+ export { retainingLogExporter, retainingSpanExporter, withRetention } from "./retention/exporters.js";
26
+ export { sessionsIn } from "./retention/sessions.js";
27
+ export { createSessionManager } from "./session/manager.js";
28
+ export { fnv1a32, sessionSampled } from "./session/sampling.js";
29
+ export { parseSessionState, SESSION_STORAGE_KEY } from "./session/state.js";
30
+ export { resolveSettings } from "./settings.js";
31
+ export { APP_LOAD_SPAN, rumSpanProcessor } from "./span-processor.js";
32
+ export { createSummaryAccumulator } from "./summary/accumulator.js";
33
+ export { afterNextPaint } from "./views/paint.js";
34
+ export { createViewTracker } from "./views/tracker.js";
35
+ export { gatewayTransportOptions, withWireParams } from "./wire.js";
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The breadcrumb ring (decision P18): the last actions, view changes and requests, which every
3
+ * o11y.rum.error carries as o11y.rum.error.breadcrumbs, one per line, oldest first.
4
+ */
5
+ /** The default number of breadcrumbs kept. */
6
+ export declare const BREADCRUMBS_MAX = 20;
7
+ export interface Breadcrumbs {
8
+ /** at is performance.now() when it happened. key lets relabel find the entry later. */
9
+ add(kind: string, label: string, at: number, key?: string): void;
10
+ /** Gives every entry added with key the label, such as a view start after the view was renamed. */
11
+ relabel(key: string, label: string): void;
12
+ /** The entries, oldest first, as "<kind> <label> -<age>ms" relative to now. */
13
+ snapshot(now: number): string[];
14
+ clear(): void;
15
+ }
16
+ export declare function createBreadcrumbs(max?: number): Breadcrumbs;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The breadcrumb ring (decision P18): the last actions, view changes and requests, which every
3
+ * o11y.rum.error carries as o11y.rum.error.breadcrumbs, one per line, oldest first.
4
+ */
5
+ /** The default number of breadcrumbs kept. */
6
+ export const BREADCRUMBS_MAX = 20;
7
+ /** One line per breadcrumb, so a line break in a label is a space. */
8
+ const oneLine = (s) => s.replace(/[\r\n]+/g, " ");
9
+ export function createBreadcrumbs(max = BREADCRUMBS_MAX) {
10
+ const ring = [];
11
+ return {
12
+ add(kind, label, at, key) {
13
+ ring.push({ kind: oneLine(kind), label: oneLine(label), at, ...(key === undefined ? {} : { key }) });
14
+ if (ring.length > max)
15
+ ring.shift();
16
+ },
17
+ relabel(key, label) {
18
+ for (const c of ring)
19
+ if (c.key === key)
20
+ c.label = oneLine(label);
21
+ },
22
+ snapshot: (now) => ring.map((c) => `${c.kind} ${c.label} -${Math.max(0, Math.round(now - c.at))}ms`),
23
+ clear() {
24
+ ring.length = 0;
25
+ },
26
+ };
27
+ }
@@ -0,0 +1,17 @@
1
+ import type { RumCollector } from "../contracts/runtime.ts";
2
+ export interface ErrorsOptions {
3
+ /** Capture console.error calls as errors with source console. Default false. */
4
+ readonly console?: boolean;
5
+ }
6
+ /** What errors() needs from the page. Internal: tests inject a fake. */
7
+ export interface ErrorsEnv {
8
+ readonly window: EventTarget;
9
+ readonly console?: {
10
+ error(...args: unknown[]): void;
11
+ };
12
+ /** Defers a console.error that logs an error object. Default the global setTimeout. */
13
+ readonly setTimeout?: (cb: () => void, ms: number) => unknown;
14
+ }
15
+ export declare function errorsWith(opts: ErrorsOptions, env: ErrorsEnv): RumCollector;
16
+ /** The errors collector: uncaught errors, unhandled rejections, resource, CSP and network failures, and optionally console.error. */
17
+ export declare function errors(opts?: ErrorsOptions): RumCollector;
@@ -0,0 +1,186 @@
1
+ import { normalizeError } from "./normalize.js";
2
+ import { recordError, wasRecorded } from "./record.js";
3
+ /** The error.type values of a request the app aborted, which is not a failure. */
4
+ const ABORTED = new Set(["AbortError", "abort"]);
5
+ /** An Error-like value recordError reads as is, so the type and message are exactly these. */
6
+ class Described extends Error {
7
+ constructor(name, message, stack) {
8
+ super(message);
9
+ this.name = name;
10
+ this.stack = stack ?? "";
11
+ }
12
+ }
13
+ function isElement(v) {
14
+ return typeof v === "object" && v !== null && typeof v.tagName === "string";
15
+ }
16
+ function bare(raw) {
17
+ try {
18
+ const u = new URL(raw);
19
+ return `${u.origin}${u.pathname}`;
20
+ }
21
+ catch {
22
+ return raw.replace(/[?#].*$/, "");
23
+ }
24
+ }
25
+ function host(raw) {
26
+ try {
27
+ return new URL(raw).hostname;
28
+ }
29
+ catch {
30
+ return "";
31
+ }
32
+ }
33
+ function blocked(uri) {
34
+ try {
35
+ const u = new URL(uri);
36
+ return u.origin === "null" ? u.protocol.replace(/:$/, "") : u.origin;
37
+ }
38
+ catch {
39
+ return uri; // inline, eval, wasm-eval, trusted-types-sink and the like
40
+ }
41
+ }
42
+ function resourceUrl(el) {
43
+ const e = el;
44
+ for (const v of [e.currentSrc, e.src, e.href, el.getAttribute?.("src"), el.getAttribute?.("href")]) {
45
+ if (typeof v === "string" && v !== "")
46
+ return bare(v);
47
+ }
48
+ return "";
49
+ }
50
+ function consoleError(args) {
51
+ let first;
52
+ const parts = args.map((a) => {
53
+ if (a instanceof Error) {
54
+ const n = normalizeError(a);
55
+ first ??= n;
56
+ return n.message;
57
+ }
58
+ try {
59
+ return String(a);
60
+ }
61
+ catch {
62
+ return "[object]";
63
+ }
64
+ });
65
+ return new Described(first?.type ?? "ConsoleError", parts.join(" "), first?.stack);
66
+ }
67
+ export function errorsWith(opts, env) {
68
+ return {
69
+ name: "errors",
70
+ start(rt) {
71
+ let stopped = false;
72
+ let recording = false;
73
+ const record = (source, error, at) => {
74
+ if (stopped || recording)
75
+ return;
76
+ recording = true;
77
+ try {
78
+ recordError(rt, source, error, at === undefined ? {} : { at });
79
+ }
80
+ finally {
81
+ recording = false;
82
+ }
83
+ };
84
+ const stamp = (e) => Number.isFinite(e.timeStamp) && e.timeStamp > 0 && e.timeStamp <= rt.now() ? e.timeStamp : undefined;
85
+ // A scope (a content script) limits errors to the events it accepts, such as its own scripts'.
86
+ const refused = (e) => rt.scope?.error?.(e) === false;
87
+ const onError = (e) => {
88
+ if (refused(e))
89
+ return;
90
+ if (isElement(e.target)) {
91
+ const tag = e.target.tagName.toLowerCase();
92
+ record("resource", new Described("ResourceError", `${tag} failed to load: ${resourceUrl(e.target)}`), stamp(e));
93
+ return;
94
+ }
95
+ const ev = e;
96
+ record("uncaught", ev.error ?? new Described("Error", String(ev.message ?? "")), stamp(e));
97
+ };
98
+ const onRejection = (e) => {
99
+ if (refused(e))
100
+ return;
101
+ record("unhandled_rejection", e.reason, stamp(e));
102
+ };
103
+ const onCsp = (e) => {
104
+ if (refused(e))
105
+ return;
106
+ const v = e;
107
+ record("csp", new Described("CSPViolation", `${v.effectiveDirective} blocked ${blocked(String(v.blockedURI ?? ""))}`), stamp(e));
108
+ };
109
+ // Errors the bootstrap buffered before RUM loaded.
110
+ const replay = (entry) => {
111
+ if (entry.kind === "error") {
112
+ record("uncaught", entry.error ?? new Described("Error", entry.message), entry.at);
113
+ }
114
+ else if (entry.kind === "rejection")
115
+ record("unhandled_rejection", entry.reason, entry.at);
116
+ else if (entry.kind === "csp") {
117
+ record("csp", new Described("CSPViolation", `${entry.directive} blocked ${blocked(entry.blocked)}`), entry.at);
118
+ }
119
+ };
120
+ env.window.addEventListener("error", onError, { capture: true });
121
+ env.window.addEventListener("unhandledrejection", onRejection);
122
+ env.window.addEventListener("securitypolicyviolation", onCsp);
123
+ // Requests in flight, so a failed one can be described by its method and host.
124
+ const requests = new Map();
125
+ const offBus = rt.bus.subscribe((s) => {
126
+ if (s.type === "bootstrap")
127
+ replay(s.entry);
128
+ else if (s.type === "request-start")
129
+ requests.set(s.spanId, { method: s.method, url: s.url });
130
+ else if (s.type === "request-end") {
131
+ const r = requests.get(s.spanId);
132
+ requests.delete(s.spanId);
133
+ if (r !== undefined && s.status === undefined && !ABORTED.has(s.errorType ?? "")) {
134
+ record("network", new Described("NetworkError", `${r.method} ${host(r.url)} failed`), s.at);
135
+ }
136
+ }
137
+ });
138
+ const con = opts.console === true ? env.console : undefined;
139
+ const original = con?.error;
140
+ const wrapper = con === undefined || original === undefined
141
+ ? undefined
142
+ : (...args) => {
143
+ try {
144
+ const logged = args.filter((a) => typeof a === "object" && a !== null);
145
+ // A console.error made while an error is being recorded is not recorded, deferred or not.
146
+ if (recording)
147
+ return;
148
+ if (logged.length === 0)
149
+ record("console", consoleError(args));
150
+ else if (!logged.some((a) => wasRecorded(rt, a))) {
151
+ // React 19 logs an error a boundary caught before componentDidCatch records it with
152
+ // its component stack, so the console record waits a task and yields to that one.
153
+ const at = rt.now();
154
+ const later = env.setTimeout ?? ((cb, ms) => setTimeout(cb, ms));
155
+ later(() => {
156
+ if (!logged.some((a) => wasRecorded(rt, a)))
157
+ record("console", consoleError(args), at);
158
+ }, 0);
159
+ }
160
+ }
161
+ finally {
162
+ original.apply(con, args);
163
+ }
164
+ };
165
+ if (con !== undefined && wrapper !== undefined)
166
+ con.error = wrapper;
167
+ return () => {
168
+ stopped = true;
169
+ env.window.removeEventListener("error", onError, { capture: true });
170
+ env.window.removeEventListener("unhandledrejection", onRejection);
171
+ env.window.removeEventListener("securitypolicyviolation", onCsp);
172
+ offBus();
173
+ requests.clear();
174
+ if (con !== undefined && original !== undefined && con.error === wrapper)
175
+ con.error = original;
176
+ };
177
+ },
178
+ };
179
+ }
180
+ /** The errors collector: uncaught errors, unhandled rejections, resource, CSP and network failures, and optionally console.error. */
181
+ export function errors(opts = {}) {
182
+ return {
183
+ name: "errors",
184
+ start: (rt) => errorsWith(opts, { window: globalThis, console: globalThis.console }).start(rt),
185
+ };
186
+ }
@@ -0,0 +1,7 @@
1
+ /** Reads any thrown value into exception.type, exception.message and exception.stacktrace. */
2
+ export interface NormalizedError {
3
+ readonly type: string;
4
+ readonly message: string;
5
+ readonly stack?: string;
6
+ }
7
+ export declare function normalizeError(value: unknown): NormalizedError;
@@ -0,0 +1,31 @@
1
+ /** Reads any thrown value into exception.type, exception.message and exception.stacktrace. */
2
+ const MAX_MESSAGE = 1024;
3
+ const cut = (s) => (s.length > MAX_MESSAGE ? s.slice(0, MAX_MESSAGE) : s);
4
+ function text(v) {
5
+ try {
6
+ return String(v);
7
+ }
8
+ catch {
9
+ return "[object]";
10
+ }
11
+ }
12
+ export function normalizeError(value) {
13
+ if (value instanceof Error) {
14
+ return {
15
+ type: value.name || "Error",
16
+ message: cut(text(value.message)),
17
+ ...(typeof value.stack === "string" && value.stack !== "" ? { stack: value.stack } : {}),
18
+ };
19
+ }
20
+ if (typeof value === "string")
21
+ return { type: "Error", message: cut(value) };
22
+ if (typeof value === "object" && value !== null && "message" in value) {
23
+ const v = value;
24
+ return {
25
+ type: typeof v.name === "string" && v.name !== "" ? v.name : "Error",
26
+ message: cut(text(v.message)),
27
+ ...(typeof v.stack === "string" && v.stack !== "" ? { stack: v.stack } : {}),
28
+ };
29
+ }
30
+ return { type: value === null ? "null" : typeof value, message: cut(text(value)) };
31
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The one path every error takes, from the errors() collector and from rum.addError: it is counted
3
+ * in the current view's summary for every consented session, published on the bus for frustration
4
+ * detection, retains the session (decision P12), and is emitted as o11y.rum.error (detail, so it is
5
+ * buffered for an unkept session) with the breadcrumbs, at most 100 events per view. An error while
6
+ * an action is open is emitted in the action's context.
7
+ */
8
+ import { type RUMErrorSource } from "@libo11y/spec";
9
+ import type { RumRuntime } from "../contracts/runtime.ts";
10
+ /** The most o11y.rum.error events one view emits. Later errors still count in its summary. */
11
+ export declare const MAX_ERROR_EVENTS_PER_VIEW = 100;
12
+ /** Whether recordError already recorded this error object, so a console.error of it is not recorded twice. */
13
+ export declare function wasRecorded(rt: RumRuntime, error: object): boolean;
14
+ export interface ErrorExtra {
15
+ /** A UI framework's component stack, appended to the stack. */
16
+ readonly componentStack?: string;
17
+ /** performance.now() when it happened. Default now. */
18
+ readonly at?: number;
19
+ }
20
+ export declare function recordError(rt: RumRuntime, source: RUMErrorSource, error: unknown, extra?: ErrorExtra): void;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The one path every error takes, from the errors() collector and from rum.addError: it is counted
3
+ * in the current view's summary for every consented session, published on the bus for frustration
4
+ * detection, retains the session (decision P12), and is emitted as o11y.rum.error (detail, so it is
5
+ * buffered for an unkept session) with the breadcrumbs, at most 100 events per view. An error while
6
+ * an action is open is emitted in the action's context.
7
+ */
8
+ import { ATTR_RUM_ERROR_BREADCRUMBS, ATTR_RUM_ERROR_SOURCE, EVENT_RUM_ERROR, } from "@libo11y/spec";
9
+ import { context, trace } from "@opentelemetry/api";
10
+ import { normalizeError } from "./normalize.js";
11
+ /** The most o11y.rum.error events one view emits. Later errors still count in its summary. */
12
+ export const MAX_ERROR_EVENTS_PER_VIEW = 100;
13
+ const emitted = new WeakMap();
14
+ const recorded = new WeakMap();
15
+ /** Whether recordError already recorded this error object, so a console.error of it is not recorded twice. */
16
+ export function wasRecorded(rt, error) {
17
+ return recorded.get(rt)?.has(error) === true;
18
+ }
19
+ export function recordError(rt, source, error, extra = {}) {
20
+ const at = extra.at ?? rt.now();
21
+ if (typeof error === "object" && error !== null) {
22
+ const set = recorded.get(rt) ?? new WeakSet();
23
+ recorded.set(rt, set);
24
+ set.add(error);
25
+ }
26
+ rt.summary.count(`errors.${source}`);
27
+ rt.bus.publish({ type: "error", source, at });
28
+ rt.session.retain("error");
29
+ const viewId = rt.views.current()?.id ?? "";
30
+ const seen = emitted.get(rt);
31
+ const n = seen?.viewId === viewId ? seen.n : 0;
32
+ if (n >= MAX_ERROR_EVENTS_PER_VIEW)
33
+ return;
34
+ emitted.set(rt, { viewId, n: n + 1 });
35
+ const e = normalizeError(error);
36
+ const stack = extra.componentStack === undefined ? e.stack : `${e.stack ?? ""}\n${extra.componentStack}`;
37
+ const crumbs = rt.breadcrumbs();
38
+ const action = rt.activeAction();
39
+ rt.emit(EVENT_RUM_ERROR, {
40
+ [ATTR_RUM_ERROR_SOURCE]: source,
41
+ "exception.type": e.type,
42
+ "exception.message": e.message,
43
+ ...(stack === undefined ? {} : { "exception.stacktrace": stack }),
44
+ ...(crumbs.length === 0 ? {} : { [ATTR_RUM_ERROR_BREADCRUMBS]: crumbs.join("\n") }),
45
+ }, action === undefined ? undefined : trace.setSpan(context.active(), action));
46
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Frustration signals (decision P11).
3
+ *
4
+ * Rage: rageClicks or more clicks on the same element selector within rageWindowMillis, reported
5
+ * once per burst, on the click that reaches the count. A burst ends when a click on that selector
6
+ * comes more than the window after the previous one.
7
+ *
8
+ * Dead: an eligible click followed by no activity (a request, a DOM mutation or a view change)
9
+ * within deadWindowMillis. The collector decides eligibility: form fields, labels, contenteditable
10
+ * and clicks inside a text selection are not.
11
+ *
12
+ * Error: an error within errorWindowMillis of the last click, or while that click's action is
13
+ * still open, reported once per click.
14
+ */
15
+ import type { RUMFrustrationType } from "@libo11y/spec";
16
+ import type { SettleTimers } from "../actions/settle.ts";
17
+ export interface FrustrationDetectorOptions {
18
+ /** Default 3. */
19
+ readonly rageClicks?: number;
20
+ /** Default 1000. */
21
+ readonly rageWindowMillis?: number;
22
+ /** Default 1000. */
23
+ readonly deadWindowMillis?: number;
24
+ /** Default 1000. */
25
+ readonly errorWindowMillis?: number;
26
+ readonly timers: SettleTimers;
27
+ readonly onSignal: (type: RUMFrustrationType, selector: string, at: number) => void;
28
+ }
29
+ export interface FrustrationDetector {
30
+ /** at is performance.now(). deadEligible is false for form fields, labels, contenteditable and clicks inside a selection. */
31
+ click(selector: string, at: number, deadEligible: boolean): void;
32
+ /** A request, mutation or view change. */
33
+ activity(at: number): void;
34
+ /** An error; actionOpen is true while the last click's action is still open. */
35
+ error(at: number, actionOpen?: boolean): void;
36
+ stop(): void;
37
+ }
38
+ export declare function createFrustrationDetector(o: FrustrationDetectorOptions): FrustrationDetector;
@@ -0,0 +1,62 @@
1
+ export function createFrustrationDetector(o) {
2
+ const rageClicks = o.rageClicks ?? 3;
3
+ const rageWindow = o.rageWindowMillis ?? 1000;
4
+ const deadWindow = o.deadWindowMillis ?? 1000;
5
+ const errorWindow = o.errorWindowMillis ?? 1000;
6
+ const bursts = new Map();
7
+ const dead = new Map();
8
+ let lastClick;
9
+ const rage = (selector, at) => {
10
+ for (const [s, b] of bursts)
11
+ if (at - b.last > rageWindow)
12
+ bursts.delete(s);
13
+ let b = bursts.get(selector);
14
+ if (b === undefined) {
15
+ b = { times: [], last: at, signalled: false };
16
+ bursts.set(selector, b);
17
+ }
18
+ b.last = at;
19
+ b.times = [...b.times.filter((t) => at - t <= rageWindow), at];
20
+ if (!b.signalled && b.times.length >= rageClicks) {
21
+ b.signalled = true;
22
+ o.onSignal("rage", selector, at);
23
+ }
24
+ };
25
+ return {
26
+ click(selector, at, deadEligible) {
27
+ lastClick = { selector, at, errored: false };
28
+ rage(selector, at);
29
+ if (!deadEligible)
30
+ return;
31
+ const h = o.timers.setTimeout(() => {
32
+ dead.delete(h);
33
+ o.onSignal("dead", selector, at);
34
+ }, deadWindow);
35
+ dead.set(h, { selector, at });
36
+ },
37
+ activity(at) {
38
+ for (const [h, c] of dead) {
39
+ if (at < c.at)
40
+ continue;
41
+ o.timers.clearTimeout(h);
42
+ dead.delete(h);
43
+ }
44
+ },
45
+ error(at, actionOpen = false) {
46
+ const c = lastClick;
47
+ if (c === undefined || c.errored || at < c.at)
48
+ return;
49
+ if (!actionOpen && at - c.at > errorWindow)
50
+ return;
51
+ c.errored = true;
52
+ o.onSignal("error", c.selector, at);
53
+ },
54
+ stop() {
55
+ for (const h of dead.keys())
56
+ o.timers.clearTimeout(h);
57
+ dead.clear();
58
+ bursts.clear();
59
+ lastClick = undefined;
60
+ },
61
+ };
62
+ }
package/dist/ids.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Random IDs for sessions and views: web's randomUuid, which also runs where there is no Web Crypto. */
2
+ export { randomUuid } from "@libo11y/web/portable";
package/dist/ids.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Random IDs for sessions and views: web's randomUuid, which also runs where there is no Web Crypto. */
2
+ export { randomUuid } from "@libo11y/web/portable";
@@ -0,0 +1,19 @@
1
+ /**
2
+ * libo11y RUM for browsers: setupRum over @libo11y/web, and the collectors it runs.
3
+ */
4
+ export { type ActionsOptions, actions } from "./actions/collector.ts";
5
+ export type { BootstrapEntry } from "./bootstrap/buffer.ts";
6
+ export type { RemoteConfigDocument, RemoteConfigLimits } from "./config/clamp.ts";
7
+ export { type RemoteConfig, type RemoteConfigClient, type RemoteConfigConnection, type RemoteConfigOpenOptions, type RemoteConfigOptions, type RemoteConfigTimers, remoteConfig, } from "./config/remote.ts";
8
+ export type * from "./contracts/runtime.ts";
9
+ export type { SessionDecision, SessionEvent, SessionManager, SessionState, } from "./contracts/session.ts";
10
+ export type { SummaryAccumulator, SummaryCountKey, SummaryView, VitalName } from "./contracts/summary.ts";
11
+ export type { ViewEvent, ViewStartOptions, ViewState, ViewTracker } from "./contracts/views.ts";
12
+ export { type ErrorsOptions, errors } from "./errors/collector.ts";
13
+ export { longAnimationFrames } from "./loaf.ts";
14
+ export type { AddErrorOptions, HttpRequestInfo, Rum, RumOptions, RumSetupOptions, RumTelemetry, } from "./options.ts";
15
+ export { type ResourcesOptions, resources } from "./resources/collector.ts";
16
+ export { setupRum } from "./setup.ts";
17
+ export { VERSION } from "./version.ts";
18
+ export { type ViewsOptions, views } from "./views/collector.ts";
19
+ export { vitals } from "./vitals/collector.ts";
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * libo11y RUM for browsers: setupRum over @libo11y/web, and the collectors it runs.
3
+ */
4
+ export { actions } from "./actions/collector.js";
5
+ export { remoteConfig, } from "./config/remote.js";
6
+ export { errors } from "./errors/collector.js";
7
+ export { longAnimationFrames } from "./loaf.js";
8
+ export { resources } from "./resources/collector.js";
9
+ export { setupRum } from "./setup.js";
10
+ export { VERSION } from "./version.js";
11
+ export { views } from "./views/collector.js";
12
+ export { vitals } from "./vitals/collector.js";
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @libo11y/rum/internal: what the RUM adapter packages and the browser fixtures compose. For
3
+ * libo11y packages only. It follows the package version, carries no compatibility promise and has
4
+ * no API report.
5
+ */
6
+ export { actionName, actionTarget, elementSelector } from "./actions/naming.ts";
7
+ export { ATTR_SESSION_ID, ATTR_USER_ID, summaryCountKey, summaryVitalKey } from "./attrs.ts";
8
+ export { afterLoadOn, BOOTSTRAP_KEY, bootstrapBuffer, installRumBootstrapOn, takeBootstrap, } from "./bootstrap/buffer.ts";
9
+ export { replayBootstrap } from "./bootstrap/replay.ts";
10
+ export { createBus } from "./bus.ts";
11
+ export { clampConfig, parseRemoteConfig, resolveLimits } from "./config/clamp.ts";
12
+ export { CONFIG_STORAGE_KEY, createRemoteConfig } from "./config/remote.ts";
13
+ export type { RetentionBuffer, RetentionRouting } from "./contracts/retention.ts";
14
+ export type { SessionStore } from "./contracts/session.ts";
15
+ export { randomUuid } from "./ids.ts";
16
+ export { stripQuery } from "./query.ts";
17
+ export { createRetentionBuffer, RETENTION_QUEUE_DEFAULTS } from "./retention/buffer.ts";
18
+ export { retainingLogExporter, retainingSpanExporter, withRetention } from "./retention/exporters.ts";
19
+ export { type BroadcastChannelLike, localStorageSessionStore, parseSessionState, SESSION_CHANNEL, SESSION_STORAGE_KEY, } from "./session/local-store.ts";
20
+ export { createSessionManager, type SessionManagerOptions } from "./session/manager.ts";
21
+ export { fnv1a32, sessionSampled } from "./session/sampling.ts";
22
+ export { type ResolvedRum, resolveSettings } from "./settings.ts";
23
+ export { defaultRumDeps, type RumDeps, runtimeOf, setupRumWith } from "./setup.ts";
24
+ export { APP_LOAD_SPAN, type RumSpanProcessorOptions, rumSpanProcessor } from "./span-processor.ts";
25
+ export { createSummaryAccumulator, type SummaryOptions } from "./summary/accumulator.ts";
26
+ export { defaultViewName } from "./views/naming.ts";
27
+ export { createViewTracker, type ViewTrackerOptions } from "./views/tracker.ts";
28
+ export { gatewayTransportOptions, withWireParams } from "./wire.ts";
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @libo11y/rum/internal: what the RUM adapter packages and the browser fixtures compose. For
3
+ * libo11y packages only. It follows the package version, carries no compatibility promise and has
4
+ * no API report.
5
+ */
6
+ export { actionName, actionTarget, elementSelector } from "./actions/naming.js";
7
+ export { ATTR_SESSION_ID, ATTR_USER_ID, summaryCountKey, summaryVitalKey } from "./attrs.js";
8
+ export { afterLoadOn, BOOTSTRAP_KEY, bootstrapBuffer, installRumBootstrapOn, takeBootstrap, } from "./bootstrap/buffer.js";
9
+ export { replayBootstrap } from "./bootstrap/replay.js";
10
+ export { createBus } from "./bus.js";
11
+ export { clampConfig, parseRemoteConfig, resolveLimits } from "./config/clamp.js";
12
+ export { CONFIG_STORAGE_KEY, createRemoteConfig } from "./config/remote.js";
13
+ export { randomUuid } from "./ids.js";
14
+ export { stripQuery } from "./query.js";
15
+ export { createRetentionBuffer, RETENTION_QUEUE_DEFAULTS } from "./retention/buffer.js";
16
+ export { retainingLogExporter, retainingSpanExporter, withRetention } from "./retention/exporters.js";
17
+ export { localStorageSessionStore, parseSessionState, SESSION_CHANNEL, SESSION_STORAGE_KEY, } from "./session/local-store.js";
18
+ export { createSessionManager } from "./session/manager.js";
19
+ export { fnv1a32, sessionSampled } from "./session/sampling.js";
20
+ export { resolveSettings } from "./settings.js";
21
+ export { defaultRumDeps, runtimeOf, setupRumWith } from "./setup.js";
22
+ export { APP_LOAD_SPAN, rumSpanProcessor } from "./span-processor.js";
23
+ export { createSummaryAccumulator } from "./summary/accumulator.js";
24
+ export { defaultViewName } from "./views/naming.js";
25
+ export { createViewTracker } from "./views/tracker.js";
26
+ export { gatewayTransportOptions, withWireParams } from "./wire.js";