@libo11y/rum 0.0.0-stage → 0.6.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 +478 -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 +103 -0
  26. package/dist/config/remote.js +241 -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 +82 -0
  30. package/dist/contracts/binding.js +1 -0
  31. package/dist/contracts/retention.d.ts +32 -0
  32. package/dist/contracts/retention.js +1 -0
  33. package/dist/contracts/runtime.d.ts +164 -0
  34. package/dist/contracts/runtime.js +1 -0
  35. package/dist/contracts/session.d.ts +68 -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 +121 -0
  42. package/dist/core-setup.js +1117 -0
  43. package/dist/core.d.ts +46 -0
  44. package/dist/core.js +36 -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 +34 -0
  60. package/dist/internal.js +25 -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 +29 -0
  74. package/dist/retention/buffer.js +130 -0
  75. package/dist/retention/exporters.d.ts +71 -0
  76. package/dist/retention/exporters.js +281 -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 +42 -0
  90. package/dist/setup.js +57 -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 +30 -0
  94. package/dist/summary/accumulator.js +128 -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 +286 -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 +37 -0
  106. package/dist/views/tracker.js +114 -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 +18 -0
  116. package/dist/webext/config-storage.js +98 -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 +104 -0
  123. package/dist/webext/setup.d.ts +74 -0
  124. package/dist/webext/setup.js +206 -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 +60 -4
@@ -0,0 +1,241 @@
1
+ /**
2
+ * The remote configuration client. It fetches the gateway's
3
+ * GET /_o11y/v1/config?service=<service.name> with credentials omitted, cache no-cache and no referrer, sending
4
+ * If-None-Match with the cached ETag. A 200 whose body parseRemoteConfig accepts is the newest
5
+ * document; a 304 changes nothing; a 404 means the app has no configuration any more; anything
6
+ * else (a failure, a bad body, a request that takes longer than REQUEST_TIMEOUT_MILLIS) keeps what
7
+ * the client has.
8
+ *
9
+ * The newest document and the one before it are cached in localStorage under CONFIG_STORAGE_KEY,
10
+ * and the documents running sessions were pinned to (pin) under CONFIG_PINNED_STORAGE_KEY, so a
11
+ * later page or another tab can apply the document of the session it resumes (find) even after
12
+ * newer documents arrived. A fetch writes only the first and a pin only the second, so neither
13
+ * overwrites what another tab wrote to the other. setupRum creates the client only once consent is
14
+ * granted, so nothing is stored before. clear (on revoke) removes both, and a response still in
15
+ * flight is then not cached.
16
+ */
17
+ import { O11yError } from "@libo11y/core";
18
+ import { clampConfig, parseRemoteConfig, resolveLimits, } from "./clamp.js";
19
+ export const CONFIG_STORAGE_KEY = "libo11y.rum.config";
20
+ /** The pinned documents, pinned longest ago first. */
21
+ export const CONFIG_PINNED_STORAGE_KEY = "libo11y.rum.config.pinned";
22
+ /** A config request that has not answered by then counts as failed. */
23
+ export const REQUEST_TIMEOUT_MILLIS = 10_000;
24
+ /** The default refresh interval while the page is visible. */
25
+ export const DEFAULT_REFRESH_MILLIS = 300_000;
26
+ /** The most documents pin keeps. Past it the one pinned longest ago is dropped first. */
27
+ export const PINNED_MAX = 8;
28
+ const wire = (d) => {
29
+ const { version, ...config } = d;
30
+ return { version, config };
31
+ };
32
+ /** The document of version in s, if s has one. */
33
+ const known = (s, version) => [s.doc, s.prior, ...s.pinned].find((d) => d?.version === version);
34
+ /** pinned with doc added last, in place of a document of its version, the newest PINNED_MAX kept. */
35
+ const pinning = (pinned, doc) => [...pinned.filter((d) => d.version !== doc.version), doc].slice(-PINNED_MAX);
36
+ const NONE = { pinned: [] };
37
+ /** The JSON value raw reads, undefined when reading fails or it is bad JSON. */
38
+ const parse = (raw) => {
39
+ try {
40
+ // JSON.parse(null) is null, and JSON.parse(undefined) throws.
41
+ return JSON.parse(raw());
42
+ }
43
+ catch { }
44
+ };
45
+ export function createRemoteConfig(o) {
46
+ let state;
47
+ /** Bumped by clear and stop, so a response that outlives them is not used. */
48
+ let generation = 0;
49
+ /** The request in flight, and the generation it belongs to. */
50
+ let inflight;
51
+ /** The pinned documents in raw, the pin entry. */
52
+ const pinsOf = (raw) => [parse(raw)]
53
+ .flat()
54
+ .map(parseRemoteConfig)
55
+ .filter((d) => d !== undefined)
56
+ .reduce(pinning, []);
57
+ /** What storage holds now, without touching the state in memory. */
58
+ const readStorage = () => {
59
+ const cache = (parse(() => o.storage?.getItem(CONFIG_STORAGE_KEY)) ?? {});
60
+ const doc = parseRemoteConfig(cache.body);
61
+ return {
62
+ etag: doc !== undefined && typeof cache.etag === "string" ? cache.etag : undefined,
63
+ doc,
64
+ prior: parseRemoteConfig(cache.prior),
65
+ pinned: pinsOf(() => o.storage?.getItem(CONFIG_PINNED_STORAGE_KEY)),
66
+ };
67
+ };
68
+ const load = () => (state ??= readStorage());
69
+ /**
70
+ * Saves a fetched s as the state, and its documents as the cache. The pins are another entry, so
71
+ * a fetch never brings back a pin evicted since, displaces a newer one or drops one this tab could
72
+ * not store.
73
+ */
74
+ const save = (s) => {
75
+ state = s;
76
+ // JSON.stringify leaves out the fields that are undefined.
77
+ const cache = { etag: s.etag, body: s.doc && wire(s.doc), prior: s.prior && wire(s.prior) };
78
+ try {
79
+ o.storage?.setItem(CONFIG_STORAGE_KEY, JSON.stringify(cache));
80
+ }
81
+ catch {
82
+ // A full or blocked storage keeps the document in memory for this page only.
83
+ }
84
+ };
85
+ const fetchOnce = async (gen) => {
86
+ const s = load();
87
+ const headers = s.etag === undefined ? {} : { "If-None-Match": s.etag };
88
+ const abort = typeof AbortController === "function" ? new AbortController() : undefined;
89
+ let timer;
90
+ // The timeout covers the headers and the body, so a stalled body cannot hold the client.
91
+ const answer = async () => {
92
+ const res = await o.fetch(o.url, {
93
+ credentials: "omit",
94
+ cache: "no-cache",
95
+ // No Referer: from a content script it would be the host page's URL.
96
+ referrerPolicy: "no-referrer",
97
+ headers,
98
+ ...(abort === undefined ? {} : { signal: abort.signal }),
99
+ });
100
+ if (res.status !== 200)
101
+ return { status: res.status };
102
+ return { status: 200, etag: res.headers.get("ETag"), body: await res.json() };
103
+ };
104
+ let got;
105
+ try {
106
+ got = await Promise.race([
107
+ answer(),
108
+ new Promise((_, reject) => {
109
+ timer = o.timers.setTimeout(() => {
110
+ abort?.abort();
111
+ reject(new Error("timeout"));
112
+ }, REQUEST_TIMEOUT_MILLIS);
113
+ }),
114
+ ]);
115
+ }
116
+ catch {
117
+ return false;
118
+ }
119
+ finally {
120
+ o.timers.clearTimeout(timer);
121
+ }
122
+ if (gen !== generation)
123
+ return false;
124
+ // What the client holds now: documents may have been pinned while the request ran.
125
+ const cur = load();
126
+ if (got.status === 404) {
127
+ if (cur.doc === undefined)
128
+ return false;
129
+ save({ prior: cur.doc, pinned: cur.pinned });
130
+ return true;
131
+ }
132
+ if (got.status !== 200)
133
+ return false;
134
+ const doc = parseRemoteConfig(got.body);
135
+ if (doc === undefined)
136
+ return false;
137
+ const etag = got.etag ?? `"${doc.version}"`;
138
+ const changed = doc.version !== cur.doc?.version;
139
+ save(changed ? { etag, doc, prior: cur.doc ?? cur.prior, pinned: cur.pinned } : { ...cur, etag });
140
+ return changed;
141
+ };
142
+ const refresh = () => {
143
+ // A request from before a clear or stop is not reused: its answer is dropped.
144
+ if (inflight?.gen === generation)
145
+ return inflight.done;
146
+ const mine = {
147
+ gen: generation,
148
+ done: fetchOnce(generation).finally(() => {
149
+ if (inflight === mine)
150
+ inflight = undefined;
151
+ }),
152
+ };
153
+ inflight = mine;
154
+ return mine.done;
155
+ };
156
+ return {
157
+ current: () => load().doc,
158
+ find(version) {
159
+ // A version undefined matches only an absent document, which is undefined too.
160
+ // Another tab may have cached the document a session it started runs under. What storage
161
+ // holds is only read: the live document and its ETag change by a fetch alone, which reports
162
+ // the change to onChange.
163
+ return known(load(), version) ?? known(readStorage(), version);
164
+ },
165
+ pin(doc) {
166
+ const s = load();
167
+ state = { ...s, pinned: pinning(s.pinned, doc) };
168
+ // Adds the pin to the pins storage holds, every tab's, in the order they were pinned.
169
+ const add = (raw) => JSON.stringify(pinning(pinsOf(() => raw), doc).map(wire));
170
+ const st = o.storage;
171
+ try {
172
+ st?.updateItem
173
+ ? st.updateItem(CONFIG_PINNED_STORAGE_KEY, add)
174
+ : st?.setItem(CONFIG_PINNED_STORAGE_KEY, add(st.getItem(CONFIG_PINNED_STORAGE_KEY)));
175
+ }
176
+ catch {
177
+ // A full or blocked storage keeps the pin in memory for this page only.
178
+ }
179
+ },
180
+ refresh,
181
+ start(onChange, onRefresh) {
182
+ const gen = generation;
183
+ let timer;
184
+ const run = () => {
185
+ void refresh().then((changed) => {
186
+ if (gen === generation)
187
+ changed ? onChange(load().doc) : onRefresh?.();
188
+ });
189
+ };
190
+ const tick = () => {
191
+ timer = o.timers.setTimeout(() => {
192
+ if (gen !== generation)
193
+ return;
194
+ if (o.visible())
195
+ run();
196
+ tick();
197
+ }, o.refreshMillis);
198
+ };
199
+ run();
200
+ tick();
201
+ return () => {
202
+ if (gen === generation)
203
+ generation++;
204
+ o.timers.clearTimeout(timer);
205
+ };
206
+ },
207
+ clear() {
208
+ generation++;
209
+ state = NONE;
210
+ try {
211
+ o.storage?.removeItem(CONFIG_STORAGE_KEY);
212
+ o.storage?.removeItem(CONFIG_PINNED_STORAGE_KEY);
213
+ }
214
+ catch {
215
+ // Nothing more can be done.
216
+ }
217
+ },
218
+ };
219
+ }
220
+ /**
221
+ * Remote configuration from the RUM gateway (GET /_o11y/v1/config). A fetched document applies to
222
+ * the next session, except that enabled false switches RUM off at once and enabled true switches it
223
+ * back on. Remote values never go beyond the limits given here, and never switch on a collector the
224
+ * app did not install. Throws O11yError INVALID_OPTION for invalid limits or refreshMillis.
225
+ */
226
+ export function remoteConfig(opts = {}) {
227
+ const refreshMillis = opts.refreshMillis ?? DEFAULT_REFRESH_MILLIS;
228
+ if (!(Number.isFinite(refreshMillis) && refreshMillis > 0)) {
229
+ throw new O11yError("INVALID_OPTION", "rum.remoteConfig.refreshMillis must be a positive number");
230
+ }
231
+ resolveLimits(0, opts.limits);
232
+ return {
233
+ ...(opts.url === undefined ? {} : { url: opts.url }),
234
+ open(o) {
235
+ return {
236
+ ...createRemoteConfig({ ...o, refreshMillis }),
237
+ apply: (code, doc) => clampConfig(code, doc, resolveLimits(code.sessionSampleRate, opts.limits)),
238
+ };
239
+ },
240
+ };
241
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Parents requests to the open action. When the inner context manager has no active
3
+ * span, the open action's context is active, so fetch and XHR spans a click handler starts, even
4
+ * after an await the StackContextManager cannot follow, become the action's children. An action
5
+ * that has ended is never active.
6
+ */
7
+ import { type ContextManager, type Span } from "@opentelemetry/api";
8
+ export declare function rumContextManager(inner: ContextManager, action: () => Span | undefined): ContextManager;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Parents requests to the open action. When the inner context manager has no active
3
+ * span, the open action's context is active, so fetch and XHR spans a click handler starts, even
4
+ * after an await the StackContextManager cannot follow, become the action's children. An action
5
+ * that has ended is never active.
6
+ */
7
+ import { trace } from "@opentelemetry/api";
8
+ export function rumContextManager(inner, action) {
9
+ const cm = {
10
+ active() {
11
+ const ctx = inner.active();
12
+ if (trace.getSpan(ctx) !== undefined)
13
+ return ctx;
14
+ const a = action();
15
+ return a === undefined || !a.isRecording() ? ctx : trace.setSpan(ctx, a);
16
+ },
17
+ with: (ctx, fn, thisArg, ...args) => inner.with(ctx, fn, thisArg, ...args),
18
+ bind: (ctx, target) => inner.bind(ctx, target),
19
+ enable() {
20
+ inner.enable();
21
+ return cm;
22
+ },
23
+ disable() {
24
+ inner.disable();
25
+ return cm;
26
+ },
27
+ };
28
+ return cm;
29
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * A platform binding: what setupRumCore hands the platform it runs
3
+ * on, and what the platform reports back. The web binding (bind.ts) runs @libo11y/web's setup, the
4
+ * extension binding @libo11y/webext's content script setup. A binding runs nothing at module
5
+ * evaluation and needs no browser global of its own, so a platform without a DOM can supply one.
6
+ */
7
+ import type { ExporterSet, Telemetry } from "@libo11y/core";
8
+ import type { ConsentController, Delivery, HttpTransportOptions, SendMode, SignalEndpoints, UrlMatcher } from "@libo11y/web/portable";
9
+ import type { ContextManager } from "@opentelemetry/api";
10
+ import type { LogRecordExporter } from "@opentelemetry/sdk-logs";
11
+ import type { SpanExporter, SpanProcessor } from "@opentelemetry/sdk-trace";
12
+ import type { RequestStartHook } from "./runtime.ts";
13
+ /** The parts of a platform's setup options RUM reads. WebSetupOptions has every one. */
14
+ export interface RumPlatformOptions {
15
+ readonly hermetic?: boolean;
16
+ readonly spanExporter?: SpanExporter;
17
+ readonly spanProcessor?: SpanProcessor;
18
+ readonly logExporter?: LogRecordExporter;
19
+ readonly contextManager?: () => ContextManager;
20
+ readonly transport?: {
21
+ readonly timeoutMillis?: number;
22
+ };
23
+ readonly instrumentations?: {
24
+ readonly ignoreUrls?: readonly UrlMatcher[];
25
+ };
26
+ }
27
+ /** What a platform reports once it built its delivery, before core builds anything. */
28
+ export interface RumPlatformInfo {
29
+ readonly endpoints: SignalEndpoints;
30
+ readonly delivery: Delivery;
31
+ /** The send mode, for the exporters' unload splitting. Default `() => "normal"`. */
32
+ readonly mode?: () => SendMode;
33
+ }
34
+ /** What the RUM core hands a platform binding, to wrap the parts of the platform's setup RUM needs. */
35
+ export interface RumWrappers {
36
+ /** Takes the consent controller the platform built; RUM's gate. Returns the controller to use. */
37
+ readonly consentController: (c: ConsentController) => ConsentController;
38
+ /**
39
+ * Takes the platform's delivery and endpoints, and the OTEL_* variables it reports, before core
40
+ * builds anything, for RUM's span exporter and retention flush.
41
+ */
42
+ readonly platform: (info: RumPlatformInfo, env: Readonly<Record<string, string>>) => void;
43
+ /** Routes the platform's exporter set by session. Build it with delta metric temporality, as the gateway needs. */
44
+ readonly exporterSet: (set: ExporterSet) => ExporterSet;
45
+ /** RUM's hook, for the fetch and XHR instrumentation's onStart. */
46
+ readonly onRequestStart: RequestStartHook;
47
+ /** Adds the gateway wire parameters to an HTTP transport, for a binding that sends over HTTP. */
48
+ readonly transportOptions: (o: HttpTransportOptions) => HttpTransportOptions;
49
+ }
50
+ /**
51
+ * Runs a platform's setup with RUM's wrappers. options are the platform's own, with RUM's span
52
+ * processor, context manager and forwarding span exporter in place.
53
+ */
54
+ export type RumBind<O extends RumPlatformOptions, T extends Telemetry> = (options: O, wrappers: RumWrappers) => Promise<T>;
55
+ /**
56
+ * What RUM does on the platform's lifecycle signals. Each is called unbound, with any arguments
57
+ * ignored, so a binding may add one as an event listener directly.
58
+ */
59
+ export interface RumLifecycleHandlers {
60
+ /**
61
+ * The page or app is being hidden. One hide may signal more than once, as a page's pagehide and
62
+ * then visibilitychange: RUM runs its hide hooks on the first and sends what is pending on each.
63
+ */
64
+ readonly hide: () => void;
65
+ /** Visible again after a hide. */
66
+ readonly show: () => void;
67
+ /** A page hidden into the back/forward cache is back: its next hide is a new hide, even without a show. */
68
+ readonly restore: () => void;
69
+ }
70
+ /** When the page or app is on screen, as its platform reports it. RUM calls each member unbound. */
71
+ export interface RumLifecycle {
72
+ /** False while the page is hidden or the app is in the background. */
73
+ readonly visible: () => boolean;
74
+ /**
75
+ * Calls handlers on the platform's lifecycle signals. RUM subscribes before the binding runs the
76
+ * platform's setup, so RUM's hide work runs before a flush on hide the platform subscribes.
77
+ * Returns the function that unsubscribes.
78
+ */
79
+ readonly subscribe: (handlers: RumLifecycleHandlers) => () => void;
80
+ /** Calls listener on user activity, which keeps the session alive. Returns the function that unsubscribes. */
81
+ readonly activity?: (listener: () => void) => () => void;
82
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,32 @@
1
+ /** The retention buffer for sessions not yet kept. */
2
+ import type { Delivery, OtlpBatch, QueueSize } from "@libo11y/web/internal";
3
+ import type { SessionDecision } from "./session.ts";
4
+ export interface RetentionBuffer {
5
+ /** Stores a batch. Never rejects: a storage failure is reported through diag and the batch is lost. */
6
+ put(batch: OtlpBatch): Promise<void>;
7
+ /**
8
+ * Sends every stored batch that keep accepts (default every batch) through delivery, and removes
9
+ * each once it is handed over. A batch keep refuses, as one of another session not kept yet, stays
10
+ * in the buffer, claimable by another flush meanwhile. The flush stops before its next step once
11
+ * allowed (default always true) is false, or a clear or close ran since it began, so no batch it
12
+ * claimed before a consent revoke is handed over. Resolves with the batches handed over. Never
13
+ * rejects.
14
+ */
15
+ flush(delivery: Delivery, keep?: (batch: OtlpBatch) => boolean, allowed?: () => boolean): Promise<number>;
16
+ /** Removes every stored batch. Never rejects. */
17
+ clear(): Promise<void>;
18
+ /**
19
+ * Removes the stored batches match accepts, leaving the others claimable at once, so an ended
20
+ * unkept session removes its own records and no other tab's. Batches another context is sending
21
+ * are not seen. Resolves with the batches removed. Never rejects.
22
+ */
23
+ discard(match: (batch: OtlpBatch) => boolean): Promise<number>;
24
+ size(): Promise<QueueSize>;
25
+ close(): void;
26
+ }
27
+ /** What the retaining exporters ask. */
28
+ export interface RetentionRouting {
29
+ decide(sessionId: string | undefined): SessionDecision;
30
+ /** Hands a serialized batch of buffered records to the retention buffer. */
31
+ buffer(batch: OtlpBatch): void;
32
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,164 @@
1
+ /**
2
+ * What every collector receives. Collectors are created by factories such
3
+ * as views() and run only while consent is granted: start is called on grant, the returned stop
4
+ * on revoke and shutdown.
5
+ */
6
+ import type { LogAttributes, RecordingGate, Telemetry } from "@libo11y/core";
7
+ import type { RUMErrorSource, RUMFrustrationType, RUMPlatform } from "@libo11y/spec";
8
+ import type { HttpRequestInfo } from "@libo11y/web";
9
+ import type { Attributes, Context, Span, Tracer } from "@opentelemetry/api";
10
+ import type { BootstrapEntry } from "../bootstrap/buffer.ts";
11
+ import type { RemoteConfigDocument } from "../config/clamp.ts";
12
+ import type { SessionManager } from "./session.ts";
13
+ import type { SummaryAccumulator } from "./summary.ts";
14
+ import type { ViewTracker } from "./views.ts";
15
+ export type CollectorName = "views" | "actions" | "errors" | "vitals" | "resources" | "long_animation_frames" | "replay";
16
+ /** Internal signals between collectors. at is performance.now(). */
17
+ export type RumSignal = {
18
+ readonly type: "error";
19
+ readonly source: RUMErrorSource;
20
+ readonly at: number;
21
+ } | {
22
+ readonly type: "frustration";
23
+ readonly frustration: RUMFrustrationType;
24
+ readonly selector?: string;
25
+ readonly at: number;
26
+ } | {
27
+ readonly type: "request-start";
28
+ readonly spanId: string;
29
+ readonly parentSpanId?: string;
30
+ readonly method: string;
31
+ readonly url: string;
32
+ readonly at: number;
33
+ } | {
34
+ readonly type: "request-end";
35
+ readonly spanId: string;
36
+ readonly status?: number;
37
+ /** The span's error.type when it ended without a response, such as AbortError or abort. */
38
+ readonly errorType?: string;
39
+ readonly at: number;
40
+ } | {
41
+ readonly type: "mutation";
42
+ readonly at: number;
43
+ } | {
44
+ readonly type: "breadcrumb";
45
+ readonly kind: string;
46
+ readonly label: string;
47
+ readonly at: number;
48
+ /** Lets a later rename relabel it: a view start carries its view ID. */
49
+ readonly key?: string;
50
+ }
51
+ /** An event the bootstrap buffered before RUM loaded, replayed once the collectors started. */
52
+ | {
53
+ readonly type: "bootstrap";
54
+ readonly entry: BootstrapEntry;
55
+ }
56
+ /** Remote configuration changed the current session's settings, as when its own document arrived. */
57
+ | {
58
+ readonly type: "config";
59
+ };
60
+ /** A log record body: the semconv browser.web_vital event carries its fields in one. */
61
+ export type EventBody = Readonly<Record<string, string | number>>;
62
+ export interface RumBus {
63
+ publish(signal: RumSignal): void;
64
+ subscribe(listener: (signal: RumSignal) => void): () => void;
65
+ }
66
+ export type RequestStartHook = (span: Span, request: HttpRequestInfo) => void;
67
+ /** The options and remote configuration after clamping. */
68
+ export interface RumSettings {
69
+ readonly sessionSampleRate: number;
70
+ readonly sessionIdleMillis: number;
71
+ readonly sessionMaxMillis: number;
72
+ readonly queryAllowList: ReadonlySet<string>;
73
+ /** Collectors the app installed and remote configuration left on. */
74
+ readonly enabled: ReadonlySet<CollectorName>;
75
+ readonly configVersion?: string;
76
+ readonly viewName: (url: URL) => string;
77
+ /** The app's public client token, sent as client_token on every gateway request. */
78
+ readonly clientToken?: string;
79
+ }
80
+ /**
81
+ * What a context limits the collectors to. Unset fields limit nothing. setupRumExtension sets
82
+ * them in a content script, whose document is the host page's.
83
+ */
84
+ export interface RumScope {
85
+ /** actions() records only the click, keydown and submit events this accepts. */
86
+ readonly action?: (event: Event) => boolean;
87
+ /** errors() records only the error, unhandledrejection and securitypolicyviolation events this accepts. */
88
+ readonly error?: (event: Event) => boolean;
89
+ /** views() follows no URL change, so the context keeps one view. */
90
+ readonly fixedView?: boolean;
91
+ /** Attributes every view span carries, such as url.domain in a content script. */
92
+ readonly viewAttributes?: Attributes;
93
+ }
94
+ export interface RumRuntime {
95
+ readonly platform: RUMPlatform;
96
+ /** The context's limits on what collectors record. Absent on the web. */
97
+ readonly scope?: RumScope;
98
+ readonly telemetry: Telemetry;
99
+ readonly tracer: Tracer;
100
+ readonly gate: RecordingGate;
101
+ readonly session: SessionManager;
102
+ readonly views: ViewTracker;
103
+ readonly summary: SummaryAccumulator;
104
+ readonly bus: RumBus;
105
+ settings(): RumSettings;
106
+ /** performance.now(). */
107
+ now(): number;
108
+ /**
109
+ * The epoch milliseconds now() counts from (performance.timeOrigin on the web), so a span
110
+ * placed at a now() time needs no performance global of its own.
111
+ */
112
+ readonly timeOrigin: number;
113
+ /**
114
+ * Emits event name with session.id and o11y.rum.view.id of the current session and view added
115
+ * (attrs win). Dropped while the gate is closed. With body, the record carries it as its body
116
+ * for upstream events such as semconv's browser.web_vital that define one.
117
+ */
118
+ emit(name: string, attrs?: LogAttributes, ctx?: Context, body?: EventBody): void;
119
+ /** Adds a hook run on every fetch and XHR client span right after it starts. */
120
+ onRequestStart(hook: RequestStartHook): () => void;
121
+ /** The open action's span, while one is open. Requests started meanwhile become its children. */
122
+ activeAction(): Span | undefined;
123
+ setActiveAction(span: Span | undefined): void;
124
+ /** The last breadcrumbs, oldest first, as "<kind> <label> -<age>ms". */
125
+ breadcrumbs(): readonly string[];
126
+ /**
127
+ * Whether url is RUM's own traffic or one the app told the instrumentation to ignore: the OTLP
128
+ * endpoints and instrumentations.ignoreUrls. Resource spans skip these.
129
+ */
130
+ ignored(url: string): boolean;
131
+ /**
132
+ * Adds a hook run when the page is hidden (the first of visibilitychange to hidden and pagehide,
133
+ * once per hide), before the summaries are emitted and exported. Returns a function that
134
+ * removes it.
135
+ */
136
+ onHide(hook: () => void): () => void;
137
+ /**
138
+ * The remote configuration document the current session started under, if any: the one
139
+ * settings() applies, for a collector that reads keys of its own, such as replay.
140
+ */
141
+ remoteDocument(): RemoteConfigDocument | undefined;
142
+ /**
143
+ * Adds attributes to every event of the given names that emit sends. attrs runs at each
144
+ * emit; undefined adds nothing, and the caller's attributes win on a conflict. Returns a
145
+ * function that removes it.
146
+ */
147
+ addEventAttributes(names: readonly string[], attrs: () => LogAttributes | undefined): () => void;
148
+ /**
149
+ * Counts url as RUM's own traffic, whatever its query and fragment, so ignored is true for it,
150
+ * as for the OTLP endpoints. Returns a function that removes it.
151
+ */
152
+ ignoreUrl(url: string): () => void;
153
+ }
154
+ export interface RumCollector {
155
+ readonly name: CollectorName;
156
+ /** Starts collecting. Returns the function that stops it. */
157
+ start(runtime: RumRuntime): () => void;
158
+ /**
159
+ * Removes what the collector stored, in this page or an earlier one. RUM calls it whenever it
160
+ * erases its own storage (a denied start, a revoke), whether or not the collector ever started.
161
+ * Optional.
162
+ */
163
+ readonly clear?: () => void | Promise<void>;
164
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The session: one per user visit, shared by every tab of an origin (and
3
+ * every context of an extension), ending after sessionIdleMillis without activity or after
4
+ * sessionMaxMillis.
5
+ */
6
+ import type { RUMSessionRetained } from "@libo11y/spec";
7
+ /** The shared session record, as stored. Times are epoch milliseconds. */
8
+ export interface SessionState {
9
+ readonly id: string;
10
+ readonly startedAt: number;
11
+ readonly lastActivityAt: number;
12
+ /** The head-sampling decision: sessionSampled(id, rate) at creation. */
13
+ readonly sampled: boolean;
14
+ /** Why the session is kept, once it is. head_sampled from creation when sampled. */
15
+ readonly retained?: RUMSessionRetained;
16
+ /** The remote configuration version the session started under. */
17
+ readonly configVersion?: string;
18
+ }
19
+ /** Where the session is shared. localStorage plus BroadcastChannel on the web, chrome.storage.session in extensions. */
20
+ export interface SessionStore {
21
+ /** Reads the stored session. Resolves undefined when there is none or it is unreadable. Never rejects. */
22
+ load(): Promise<SessionState | undefined>;
23
+ /** Stores state (undefined removes it) and tells the other contexts. Never throws. */
24
+ save(state: SessionState | undefined): void;
25
+ /**
26
+ * Resolves once every earlier save reached storage. Never rejects. A store that writes
27
+ * asynchronously, as chrome.storage.session does, has it; one that writes at once needs none.
28
+ */
29
+ flush?(): Promise<void>;
30
+ /** Calls listener when another context saves. Returns a function that unsubscribes. */
31
+ onChange(listener: (state: SessionState | undefined) => void): () => void;
32
+ close(): void;
33
+ }
34
+ /** What the retention router does with a record of a session. */
35
+ export type SessionDecision = "send" | "buffer" | "drop";
36
+ /** local is true when this context caused the change. */
37
+ export type SessionEvent = {
38
+ readonly type: "start";
39
+ readonly session: SessionState;
40
+ readonly previous?: SessionState;
41
+ readonly local: boolean;
42
+ } | {
43
+ readonly type: "end";
44
+ readonly session: SessionState;
45
+ readonly local: boolean;
46
+ } | {
47
+ readonly type: "kept";
48
+ readonly session: SessionState;
49
+ readonly local: boolean;
50
+ };
51
+ export interface SessionManager {
52
+ /** Loads the shared session and starts listening. Called when consent is granted. */
53
+ start(): Promise<void>;
54
+ /** The live session, rotating an expired one. Undefined before start and after clear. */
55
+ current(): SessionState | undefined;
56
+ /** User activity: extends the session, or rotates it when it expired. */
57
+ touch(): void;
58
+ /** Whether the current session is kept (head-sampled or retained). */
59
+ kept(): boolean;
60
+ /** Keeps the current session for reason. True when this call changed it from unkept to kept. */
61
+ retain(reason: "error" | "frustration"): boolean;
62
+ /** send for a kept session, buffer for the current unkept one, drop for an old unkept one. */
63
+ decide(sessionId: string | undefined): SessionDecision;
64
+ /** Forgets the session and removes it from the store (consent revoked). */
65
+ clear(): void;
66
+ subscribe(listener: (event: SessionEvent) => void): () => void;
67
+ close(): void;
68
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,28 @@
1
+ /** The per-view counters behind o11y.rum.view.summary. */
2
+ import type { RUMErrorSource, RUMFrustrationType, RUMViewKind } from "@libo11y/spec";
3
+ export type SummaryCountKey = `errors.${RUMErrorSource}` | `frustrations.${RUMFrustrationType}` | "requests" | "long_animation_frames";
4
+ export type VitalName = "lcp" | "inp" | "cls" | "fcp" | "ttfb";
5
+ export interface SummaryView {
6
+ readonly id: string;
7
+ readonly name: string;
8
+ readonly kind: RUMViewKind;
9
+ readonly sessionId: string;
10
+ }
11
+ export interface SummaryAccumulator {
12
+ /** Tracks view as the current view; its time on view runs while the page is visible. */
13
+ open(view: SummaryView): void;
14
+ /** Sends the view's summary (at least once) and stops its clock. Late vitals still reach it. */
15
+ close(viewId: string): void;
16
+ rename(viewId: string, name: string): void;
17
+ /** Adds n (default 1) to a count of the current view. */
18
+ count(key: SummaryCountKey, n?: number): void;
19
+ /** Records a vital of a view once; later values for the same view and vital are ignored. Seconds, CLS unitless. */
20
+ vital(viewId: string, name: VitalName, value: number): void;
21
+ visibility(visible: boolean): void;
22
+ /** Pins a view: while pinned, a closed view is not forgotten, so vitals held for it still reach it. */
23
+ pin(viewId: string, pinned: boolean): void;
24
+ /** Sends a summary for every view with unsent data. */
25
+ flush(): void;
26
+ /** Drops everything unsent (consent revoked). */
27
+ reset(): void;
28
+ }
@@ -0,0 +1 @@
1
+ export {};