@libo11y/rum 0.4.0 → 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 (67) hide show
  1. package/README.md +37 -20
  2. package/dist/actions/collector.js +2 -2
  3. package/dist/actions/naming.d.ts +1 -1
  4. package/dist/actions/naming.js +1 -1
  5. package/dist/actions/record.d.ts +1 -1
  6. package/dist/actions/record.js +1 -1
  7. package/dist/actions/settle.d.ts +1 -1
  8. package/dist/actions/settle.js +1 -1
  9. package/dist/bind.d.ts +1 -1
  10. package/dist/bootstrap/buffer.d.ts +1 -1
  11. package/dist/bootstrap/buffer.js +1 -1
  12. package/dist/bootstrap/replay.d.ts +1 -1
  13. package/dist/config/clamp.d.ts +2 -2
  14. package/dist/config/clamp.js +2 -2
  15. package/dist/config/remote.d.ts +30 -7
  16. package/dist/config/remote.js +78 -46
  17. package/dist/context-manager.d.ts +1 -1
  18. package/dist/context-manager.js +1 -1
  19. package/dist/contracts/binding.d.ts +4 -2
  20. package/dist/contracts/retention.d.ts +7 -3
  21. package/dist/contracts/runtime.d.ts +24 -14
  22. package/dist/contracts/session.d.ts +6 -1
  23. package/dist/contracts/summary.d.ts +2 -2
  24. package/dist/contracts/views.d.ts +3 -3
  25. package/dist/core-setup.d.ts +43 -8
  26. package/dist/core-setup.js +286 -71
  27. package/dist/core.d.ts +13 -9
  28. package/dist/core.js +6 -5
  29. package/dist/errors/breadcrumbs.d.ts +1 -1
  30. package/dist/errors/breadcrumbs.js +1 -1
  31. package/dist/errors/record.d.ts +1 -1
  32. package/dist/errors/record.js +1 -1
  33. package/dist/frustration/detect.d.ts +1 -1
  34. package/dist/index.d.ts +1 -1
  35. package/dist/internal.d.ts +15 -9
  36. package/dist/internal.js +4 -5
  37. package/dist/pending-spans.d.ts +1 -1
  38. package/dist/query.d.ts +1 -1
  39. package/dist/query.js +1 -1
  40. package/dist/retention/buffer.d.ts +9 -5
  41. package/dist/retention/buffer.js +41 -15
  42. package/dist/retention/exporters.d.ts +56 -2
  43. package/dist/retention/exporters.js +214 -0
  44. package/dist/session/manager.js +1 -1
  45. package/dist/session/sampling.js +1 -1
  46. package/dist/setup.d.ts +3 -1
  47. package/dist/setup.js +14 -6
  48. package/dist/span-processor.d.ts +3 -3
  49. package/dist/span-processor.js +2 -2
  50. package/dist/summary/accumulator.d.ts +7 -2
  51. package/dist/summary/accumulator.js +4 -2
  52. package/dist/version.d.ts +1 -1
  53. package/dist/version.js +1 -1
  54. package/dist/views/collector.js +8 -7
  55. package/dist/views/naming.d.ts +1 -1
  56. package/dist/views/naming.js +1 -1
  57. package/dist/views/tracker.d.ts +15 -6
  58. package/dist/views/tracker.js +10 -13
  59. package/dist/vitals/collector.js +2 -2
  60. package/dist/webext/config-storage.d.ts +15 -4
  61. package/dist/webext/config-storage.js +78 -27
  62. package/dist/webext/scope.d.ts +1 -1
  63. package/dist/webext/session-store.js +12 -2
  64. package/dist/webext/setup.d.ts +5 -2
  65. package/dist/webext/setup.js +29 -16
  66. package/dist/webext.d.ts +1 -1
  67. package/package.json +11 -8
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @libo11y/rum
2
2
 
3
3
  Real user monitoring (RUM) for browsers, built on
4
- [`@libo11y/web`](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/web).
4
+ [`@libo11y/web`](https://github.com/libo11y/libo11y/tree/main/ts/packages/web).
5
5
  `setupRum()` runs the web platform with RUM wired in. It keeps one session
6
6
  across the tabs of an origin, samples sessions, and sends a summary of
7
7
  every view to the RUM gateway.
@@ -12,15 +12,9 @@ npm install @libo11y/rum
12
12
 
13
13
  ## Status
14
14
 
15
- The package first ships in `ts/v0.3.0`. It is not on npm yet. Until its
16
- first npm publish, install it from the tarball attached to the
17
- [`ts/v0.4.0` GitHub Release](https://github.com/jamesainslie/libo11y/releases/tag/ts/v0.4.0),
18
- whose notes list the exact URL:
19
-
20
- ```sh
21
- npm install \
22
- https://github.com/jamesainslie/libo11y/releases/download/ts/v0.4.0/libo11y-rum-0.4.0.tgz
23
- ```
15
+ The package first ships in `ts/v0.3.0` and is published on npm at `0.6.0`
16
+ (also attached as a tarball to the
17
+ [`ts/v0.6.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.6.0)).
24
18
 
25
19
  The package has the core (sessions, consent, sampling, the retention
26
20
  buffer and view summaries), the `views()`, `actions()`, `errors()`,
@@ -61,8 +55,20 @@ RUM gateway accepts only delta sums and histograms.
61
55
  Nothing is recorded, stored or sent before `telemetry.consent.grant()`.
62
56
  No session exists until then, and RUM writes nothing to `localStorage` or
63
57
  IndexedDB. `telemetry.consent.revoke()` stops RUM, removes the session
64
- from storage and empties the retention buffer. To start with consent
65
- already given, pass `consent: { initial: "granted" }`.
58
+ and the remote configuration cache from storage and empties the retention
59
+ buffer, also when consent was never granted in this page. The returned
60
+ promise resolves once the removals reached storage, `chrome.storage`
61
+ included. A page that starts denied, through `consent: { initial: "denied" }`
62
+ or a respected Do Not Track or Global Privacy Control signal, removes the
63
+ same before setup resolves, so a later grant starts a new session. A page
64
+ that starts pending touches none of it. To start with consent already
65
+ given, pass `consent: { initial: "granted" }`.
66
+
67
+ With `OTEL_SDK_DISABLED=true` in `env` (outside hermetic mode) RUM starts
68
+ no session, collector, remote configuration or bootstrap replay, even
69
+ after a grant. A denied start and `telemetry.consent.revoke()` still
70
+ remove previously stored RUM data, while a pending start touches none of
71
+ it.
66
72
 
67
73
  ## Sessions
68
74
 
@@ -90,6 +96,12 @@ most 2 MiB and 15 minutes old by default (`rum.retention`). When an error
90
96
  or a frustration signal keeps the session, the buffer is sent. A session
91
97
  that ends without being kept drops its buffer.
92
98
 
99
+ The buffer sends through RUM's own transport, so spans and log records
100
+ for an injected `spanExporter` or `logExporter`, as well as console-routed
101
+ traces and logs, wait in memory instead (at most 1000 spans and 1000 log
102
+ records), and go to their own exporter once the session is kept. A
103
+ reload, a revoke or shutdown drops them.
104
+
93
105
  ## Privacy
94
106
 
95
107
  Recorded URLs keep only the query parameters in `rum.queryAllowList`.
@@ -332,13 +344,18 @@ three keys inside `config` and ignores the rest:
332
344
 
333
345
  Code sets the limits. Without `limits.sessionSampleRate`, the range is
334
346
  `[rate, rate]`, so the rate does not move. A document applies to the next
335
- session, never to the running one, except for `enabled: false`. The
336
- newest document and the one before it are cached in `localStorage` under
337
- `libo11y.rum.config`, so a page that resumes a session keeps the document
338
- that session started under. A new session takes the newest. Each session
339
- records the version it started under as `o11y.rum.config.version` on its
340
- `o11y.rum.session.start` event and its view summaries. Revoking consent
341
- removes the cache.
347
+ session, never to the running one, except for kill-switch transitions
348
+ (`enabled: false` and back to `true`), which take effect at once, and a
349
+ resumed session that started on fallback settings, which adopts its own
350
+ pinned document if it arrives on a later refresh. The newest document and
351
+ the one before it are cached in `localStorage` under `libo11y.rum.config`,
352
+ and up to 8 pinned documents for active sessions are stored under
353
+ `libo11y.rum.config.pinned` (in `chrome.storage.local` in extensions), so
354
+ a reload or another tab resuming a session keeps the document that session
355
+ started under even after newer versions arrive. A new session takes the
356
+ newest. Each session records the version it started under as
357
+ `o11y.rum.config.version` on its `o11y.rum.session.start` event and its
358
+ view summaries. Revoking consent removes both keys.
342
359
 
343
360
  ## Loading
344
361
 
@@ -371,7 +388,7 @@ consent is granted later.
371
388
  ## Extensions
372
389
 
373
390
  `@libo11y/rum/webext` records RUM in Manifest V3 extensions, on top of
374
- [`@libo11y/webext`](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/webext).
391
+ [`@libo11y/webext`](https://github.com/libo11y/libo11y/tree/main/ts/packages/webext).
375
392
  Extension pages and content scripts record. The service worker sends
376
393
  their records to the gateway, so they need no endpoint.
377
394
 
@@ -11,11 +11,11 @@
11
11
  * Each new action ends the open one at its last activity, then starts the span "action <type>" as
12
12
  * a root at the event's time, with o11y.rum.span.shape action, the type, the name (actionName,
13
13
  * when there is one), o11y.rum.element.selector and the view ID, linked to the view span. It is
14
- * the open action until it settles (decision P10): the RUM context manager makes it the parent of
14
+ * the open action until it settles: the RUM context manager makes it the parent of
15
15
  * requests started meanwhile, and the requests whose parent it is, DOM mutations and view starts
16
16
  * are its activity. Its breadcrumb (type and name, else the tag) is published when it starts.
17
17
  *
18
- * Frustration (decision P11, frustration not false): clicks feed rage and dead detection, and
18
+ * Frustration (when frustration is not false): clicks feed rage and dead detection, and
19
19
  * errors feed error clicks. A click is not dead-eligible on a form field, label, contenteditable,
20
20
  * a link with an href, or inside a text selection. Requests, mutations and view starts within the
21
21
  * dead window count as activity, so the mutation observer stays connected while an action is open
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Action names and element selectors (design, Privacy). A name is the data-o11y label on the
2
+ * Action names and element selectors. A name is the data-o11y label on the
3
3
  * element or its closest ancestor, else the aria-label of an interactive element, never visible
4
4
  * text, and nothing inside [data-o11y-mask]. A selector identifies the element by structure: an ID
5
5
  * that is not ID-like, a data-o11y label, or a short path of tags, stable classes and positions.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Action names and element selectors (design, Privacy). A name is the data-o11y label on the
2
+ * Action names and element selectors. A name is the data-o11y label on the
3
3
  * element or its closest ancestor, else the aria-label of an interactive element, never visible
4
4
  * text, and nothing inside [data-o11y-mask]. A selector identifies the element by structure: an ID
5
5
  * that is not ID-like, a data-o11y label, or a short path of tags, stable classes and positions.
@@ -1,4 +1,4 @@
1
- /** Instant actions: custom actions (rum.addAction) and clicks replayed from the bootstrap (R3d). */
1
+ /** Instant actions: custom actions (rum.addAction) and clicks replayed from the bootstrap. */
2
2
  import { type RUMActionType } from "@libo11y/spec";
3
3
  import { type Attributes, type Link } from "@opentelemetry/api";
4
4
  import type { RumRuntime } from "../contracts/runtime.ts";
@@ -1,4 +1,4 @@
1
- /** Instant actions: custom actions (rum.addAction) and clicks replayed from the bootstrap (R3d). */
1
+ /** Instant actions: custom actions (rum.addAction) and clicks replayed from the bootstrap. */
2
2
  import { ATTR_RUM_ACTION_NAME, ATTR_RUM_ACTION_TYPE, ATTR_RUM_SPAN_SHAPE, ATTR_RUM_VIEW_ID, RUM_SPAN_SHAPE_VALUE_ACTION, } from "@libo11y/spec";
3
3
  import { ROOT_CONTEXT } from "@opentelemetry/api";
4
4
  /** The span name of an action: the type only, because span names bypass the sensitivity policy. */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The action settle rule (decision P10). An action ends at the time of its last activity (a
2
+ * The action settle rule. An action ends at the time of its last activity (a
3
3
  * request end or a DOM mutation it caused, or its start), detected once no request is pending and
4
4
  * idleMillis passed without activity, capped capMillis after it started. Its duration therefore
5
5
  * excludes the idle wait. end() settles at once, as when a new action starts.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The action settle rule (decision P10). An action ends at the time of its last activity (a
2
+ * The action settle rule. An action ends at the time of its last activity (a
3
3
  * request end or a DOM mutation it caused, or its start), detected once no request is pending and
4
4
  * idleMillis passed without activity, capped capMillis after it started. Its duration therefore
5
5
  * excludes the idle wait. end() settles at once, as when a new action starts.
package/dist/bind.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The web's platform binding and lifecycle (R3f, R5a). setupRumCore builds the RUM core, then hands
2
+ * The web's platform binding and lifecycle. setupRumCore builds the RUM core, then hands
3
3
  * a binding the setup options with RUM's span processor, context manager and forwarding span
4
4
  * exporter in place, and the wrappers (contracts/binding.ts). webBinding runs web's setupWithDeps
5
5
  * with them; @libo11y/rum/webext's contentBinding runs @libo11y/webext's setupContentScriptWith.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The bootstrap buffer (decision P9), shared by the tiny `@libo11y/rum/bootstrap` entry and the
2
+ * The bootstrap buffer, shared by the tiny `@libo11y/rum/bootstrap` entry and the
3
3
  * collectors through a global registered symbol, so the two meet even when bundled apart. It has no
4
4
  * imports.
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The bootstrap buffer (decision P9), shared by the tiny `@libo11y/rum/bootstrap` entry and the
2
+ * The bootstrap buffer, shared by the tiny `@libo11y/rum/bootstrap` entry and the
3
3
  * collectors through a global registered symbol, so the two meet even when bundled apart. It has no
4
4
  * imports.
5
5
  *
@@ -2,7 +2,7 @@
2
2
  * Replays the bootstrap buffer once the collectors started: each entry goes out on the bus as a
3
3
  * bootstrap signal with its original time, and the collector of its kind records it (errors()
4
4
  * the errors, actions() the clicks), so a kind whose collector the app did not install is dropped.
5
- * Nothing is replayed unless consent is granted (decision P9).
5
+ * Nothing is replayed unless consent is granted.
6
6
  */
7
7
  import type { RumRuntime } from "../contracts/runtime.ts";
8
8
  import type { BootstrapBuffer } from "./buffer.ts";
@@ -9,7 +9,7 @@ export interface RemoteConfigDocument {
9
9
  readonly sessionSampleRate?: number;
10
10
  /** false switches an installed collector off. true never switches on one the app did not install. */
11
11
  readonly collectors?: Readonly<Partial<Record<CollectorName, boolean>>>;
12
- /** Replay's remote settings, kept as an object for `@libo11y/rum-replay` to clamp (R6b). */
12
+ /** Replay's remote settings, kept as an object for `@libo11y/rum-replay` to clamp. */
13
13
  readonly replay?: Readonly<Record<string, unknown>>;
14
14
  }
15
15
  /** The range remote configuration may move a value within. */
@@ -23,7 +23,7 @@ export interface ResolvedLimits {
23
23
  }
24
24
  /**
25
25
  * The limits for a code sample rate. The default range is [rate, rate]: no change. Throws O11yError
26
- * INVALID_OPTION unless 0 <= min <= max <= 1.
26
+ * INVALID_OPTION unless `0 <= min <= max <= 1`.
27
27
  */
28
28
  export declare function resolveLimits(rate: number, limits: RemoteConfigLimits | undefined): ResolvedLimits;
29
29
  /** The document in a config endpoint body, or undefined when the body is not one. */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Remote configuration against the limits code sets (decision P16). The gateway serves
2
+ * Remote configuration against the limits code sets. The gateway serves
3
3
  * GET /_o11y/v1/config?service=<service.name> as {"version": "...", "config": {...}}; RUM owns
4
4
  * the keys inside config: enabled, sessionSampleRate, collectors and replay, whose object
5
5
  * `@libo11y/rum-replay` clamps itself. Unknown keys are ignored, so
@@ -22,7 +22,7 @@ function isObject(v) {
22
22
  }
23
23
  /**
24
24
  * The limits for a code sample rate. The default range is [rate, rate]: no change. Throws O11yError
25
- * INVALID_OPTION unless 0 <= min <= max <= 1.
25
+ * INVALID_OPTION unless `0 <= min <= max <= 1`.
26
26
  */
27
27
  export function resolveLimits(rate, limits) {
28
28
  const range = limits?.sessionSampleRate;
@@ -1,10 +1,23 @@
1
1
  import type { RumSettings } from "../contracts/runtime.ts";
2
2
  import { type RemoteConfigDocument, type RemoteConfigLimits } from "./clamp.ts";
3
3
  export declare const CONFIG_STORAGE_KEY = "libo11y.rum.config";
4
+ /** The pinned documents, pinned longest ago first. */
5
+ export declare const CONFIG_PINNED_STORAGE_KEY = "libo11y.rum.config.pinned";
4
6
  /** A config request that has not answered by then counts as failed. */
5
7
  export declare const REQUEST_TIMEOUT_MILLIS = 10000;
6
8
  /** The default refresh interval while the page is visible. */
7
9
  export declare const DEFAULT_REFRESH_MILLIS = 300000;
10
+ /** The most documents pin keeps. Past it the one pinned longest ago is dropped first. */
11
+ export declare const PINNED_MAX = 8;
12
+ /** The storage remote configuration caches in. */
13
+ export type RemoteConfigStorage = Pick<Storage, "getItem" | "setItem" | "removeItem"> & {
14
+ /**
15
+ * Sets key to fn of the value storage holds now, serialized with every other context's updates,
16
+ * where storage is shared by contexts that each hold a copy in memory. Optional: without it, pin
17
+ * reads and sets the value.
18
+ */
19
+ updateItem?(key: string, fn: (current: string | null) => string): void;
20
+ };
8
21
  /** The timers the client runs on. */
9
22
  export interface RemoteConfigTimers {
10
23
  setTimeout(cb: () => void, ms: number): unknown;
@@ -14,15 +27,25 @@ export interface RemoteConfigClient {
14
27
  /** The newest document known: from the cache of an earlier page, then from each fetch. */
15
28
  current(): RemoteConfigDocument | undefined;
16
29
  /**
17
- * The newest document, or the one before it, whose version is version: the document a session
18
- * started under. Undefined for undefined (a session that started without one); the newest for a
19
- * version the client no longer has.
30
+ * The newest document, the one before it or a pinned document whose version is version: the
31
+ * document a session started under. Undefined for undefined (a session that started without one)
32
+ * and for a version the client no longer has, never a document of another version.
20
33
  */
21
34
  find(version: string | undefined): RemoteConfigDocument | undefined;
35
+ /**
36
+ * Keeps doc in the cache while newer documents arrive, so a reload or another tab resuming the
37
+ * session that runs under it still finds it. At most PINNED_MAX documents are kept. clear removes
38
+ * them. Optional, for a client written before it.
39
+ */
40
+ pin?(doc: RemoteConfigDocument): void;
22
41
  /** Fetches now. Resolves true when the newest document changed. Never rejects. */
23
42
  refresh(): Promise<boolean>;
24
- /** Refreshes now and every refreshMillis while visible, calling onChange when the newest document changed. */
25
- start(onChange: (doc: RemoteConfigDocument | undefined) => void): () => void;
43
+ /**
44
+ * Refreshes now and every refreshMillis while visible, calling onChange when the newest document
45
+ * changed and onRefresh after any other refresh, as a 304, when another tab may have cached a
46
+ * document since.
47
+ */
48
+ start(onChange: (doc: RemoteConfigDocument | undefined) => void, onRefresh?: () => void): () => void;
26
49
  /** Removes the cache, and keeps a response in flight from being cached. */
27
50
  clear(): void;
28
51
  }
@@ -31,7 +54,7 @@ export interface RemoteConfigClientOptions {
31
54
  readonly url: string;
32
55
  readonly refreshMillis: number;
33
56
  readonly fetch: typeof fetch;
34
- readonly storage?: Pick<Storage, "getItem" | "setItem" | "removeItem">;
57
+ readonly storage?: RemoteConfigStorage | undefined;
35
58
  readonly timers: RemoteConfigTimers;
36
59
  readonly visible: () => boolean;
37
60
  }
@@ -53,7 +76,7 @@ export interface RemoteConfigOpenOptions {
53
76
  /** The full config URL, service and client_token included. */
54
77
  readonly url: string;
55
78
  readonly fetch: typeof fetch;
56
- readonly storage?: Pick<Storage, "getItem" | "setItem" | "removeItem">;
79
+ readonly storage?: RemoteConfigStorage | undefined;
57
80
  readonly timers: RemoteConfigTimers;
58
81
  readonly visible: () => boolean;
59
82
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The remote configuration client (decision P15). It fetches the gateway's
2
+ * The remote configuration client. It fetches the gateway's
3
3
  * GET /_o11y/v1/config?service=<service.name> with credentials omitted, cache no-cache and no referrer, sending
4
4
  * If-None-Match with the cached ETag. A 200 whose body parseRemoteConfig accepts is the newest
5
5
  * document; a 304 changes nothing; a 404 means the app has no configuration any more; anything
@@ -7,53 +7,74 @@
7
7
  * the client has.
8
8
  *
9
9
  * The newest document and the one before it are cached in localStorage under CONFIG_STORAGE_KEY,
10
- * so a later page can apply the document of the session it resumes (find). setupRum creates the
11
- * client only once consent is granted, so nothing is stored before. clear (on revoke) removes the
12
- * cache, and a response still in flight is then not cached.
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.
13
16
  */
14
17
  import { O11yError } from "@libo11y/core";
15
18
  import { clampConfig, parseRemoteConfig, resolveLimits, } from "./clamp.js";
16
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";
17
22
  /** A config request that has not answered by then counts as failed. */
18
23
  export const REQUEST_TIMEOUT_MILLIS = 10_000;
19
24
  /** The default refresh interval while the page is visible. */
20
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;
21
28
  const wire = (d) => {
22
29
  const { version, ...config } = d;
23
30
  return { version, config };
24
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
+ };
25
45
  export function createRemoteConfig(o) {
26
46
  let state;
27
47
  /** Bumped by clear and stop, so a response that outlives them is not used. */
28
48
  let generation = 0;
29
49
  /** The request in flight, and the generation it belongs to. */
30
50
  let inflight;
31
- const load = () => {
32
- if (state !== undefined)
33
- return state;
34
- let cache = {};
35
- try {
36
- const raw = o.storage?.getItem(CONFIG_STORAGE_KEY);
37
- if (raw != null)
38
- cache = JSON.parse(raw);
39
- }
40
- catch {
41
- cache = {};
42
- }
43
- const doc = parseRemoteConfig(cache?.body);
44
- state = {
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 {
45
62
  etag: doc !== undefined && typeof cache.etag === "string" ? cache.etag : undefined,
46
63
  doc,
47
- prior: parseRemoteConfig(cache?.prior),
64
+ prior: parseRemoteConfig(cache.prior),
65
+ pinned: pinsOf(() => o.storage?.getItem(CONFIG_PINNED_STORAGE_KEY)),
48
66
  };
49
- return state;
50
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
+ */
51
74
  const save = (s) => {
52
- const cache = {
53
- ...(s.etag === undefined ? {} : { etag: s.etag }),
54
- ...(s.doc === undefined ? {} : { body: wire(s.doc) }),
55
- ...(s.prior === undefined ? {} : { prior: wire(s.prior) }),
56
- };
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) };
57
78
  try {
58
79
  o.storage?.setItem(CONFIG_STORAGE_KEY, JSON.stringify(cache));
59
80
  }
@@ -69,7 +90,6 @@ export function createRemoteConfig(o) {
69
90
  // The timeout covers the headers and the body, so a stalled body cannot hold the client.
70
91
  const answer = async () => {
71
92
  const res = await o.fetch(o.url, {
72
- method: "GET",
73
93
  credentials: "omit",
74
94
  cache: "no-cache",
75
95
  // No Referer: from a content script it would be the host page's URL.
@@ -78,7 +98,7 @@ export function createRemoteConfig(o) {
78
98
  ...(abort === undefined ? {} : { signal: abort.signal }),
79
99
  });
80
100
  if (res.status !== 200)
81
- return { status: res.status, etag: null };
101
+ return { status: res.status };
82
102
  return { status: 200, etag: res.headers.get("ETag"), body: await res.json() };
83
103
  };
84
104
  let got;
@@ -101,11 +121,12 @@ export function createRemoteConfig(o) {
101
121
  }
102
122
  if (gen !== generation)
103
123
  return false;
124
+ // What the client holds now: documents may have been pinned while the request ran.
125
+ const cur = load();
104
126
  if (got.status === 404) {
105
- if (s.doc === undefined)
127
+ if (cur.doc === undefined)
106
128
  return false;
107
- state = { etag: undefined, doc: undefined, prior: s.doc };
108
- save(state);
129
+ save({ prior: cur.doc, pinned: cur.pinned });
109
130
  return true;
110
131
  }
111
132
  if (got.status !== 200)
@@ -114,9 +135,8 @@ export function createRemoteConfig(o) {
114
135
  if (doc === undefined)
115
136
  return false;
116
137
  const etag = got.etag ?? `"${doc.version}"`;
117
- const changed = doc.version !== s.doc?.version;
118
- state = changed ? { etag, doc, prior: s.doc ?? s.prior } : { ...s, etag };
119
- save(state);
138
+ const changed = doc.version !== cur.doc?.version;
139
+ save(changed ? { etag, doc, prior: cur.doc ?? cur.prior, pinned: cur.pinned } : { ...cur, etag });
120
140
  return changed;
121
141
  };
122
142
  const refresh = () => {
@@ -136,24 +156,35 @@ export function createRemoteConfig(o) {
136
156
  return {
137
157
  current: () => load().doc,
138
158
  find(version) {
139
- if (version === undefined)
140
- return undefined;
141
- const known = (s) => s.doc?.version === version ? s.doc : s.prior?.version === version ? s.prior : undefined;
142
- const here = known(load());
143
- if (here !== undefined)
144
- return here;
145
- // Another tab may have cached the document a session it started runs under.
146
- state = undefined;
147
- return known(load()) ?? load().doc;
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
+ }
148
179
  },
149
180
  refresh,
150
- start(onChange) {
181
+ start(onChange, onRefresh) {
151
182
  const gen = generation;
152
183
  let timer;
153
184
  const run = () => {
154
185
  void refresh().then((changed) => {
155
- if (changed && gen === generation)
156
- onChange(load().doc);
186
+ if (gen === generation)
187
+ changed ? onChange(load().doc) : onRefresh?.();
157
188
  });
158
189
  };
159
190
  const tick = () => {
@@ -175,9 +206,10 @@ export function createRemoteConfig(o) {
175
206
  },
176
207
  clear() {
177
208
  generation++;
178
- state = { etag: undefined, doc: undefined, prior: undefined };
209
+ state = NONE;
179
210
  try {
180
211
  o.storage?.removeItem(CONFIG_STORAGE_KEY);
212
+ o.storage?.removeItem(CONFIG_PINNED_STORAGE_KEY);
181
213
  }
182
214
  catch {
183
215
  // Nothing more can be done.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Parents requests to the open action (decision P10). When the inner context manager has no active
2
+ * Parents requests to the open action. When the inner context manager has no active
3
3
  * span, the open action's context is active, so fetch and XHR spans a click handler starts, even
4
4
  * after an await the StackContextManager cannot follow, become the action's children. An action
5
5
  * that has ended is never active.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Parents requests to the open action (decision P10). When the inner context manager has no active
2
+ * Parents requests to the open action. When the inner context manager has no active
3
3
  * span, the open action's context is active, so fetch and XHR spans a click handler starts, even
4
4
  * after an await the StackContextManager cannot follow, become the action's children. An action
5
5
  * that has ended is never active.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Contract, R3f extended by R5a. A platform binding: what setupRumCore hands the platform it runs
2
+ * A platform binding: what setupRumCore hands the platform it runs
3
3
  * on, and what the platform reports back. The web binding (bind.ts) runs @libo11y/web's setup, the
4
4
  * extension binding @libo11y/webext's content script setup. A binding runs nothing at module
5
5
  * evaluation and needs no browser global of its own, so a platform without a DOM can supply one.
@@ -7,6 +7,7 @@
7
7
  import type { ExporterSet, Telemetry } from "@libo11y/core";
8
8
  import type { ConsentController, Delivery, HttpTransportOptions, SendMode, SignalEndpoints, UrlMatcher } from "@libo11y/web/portable";
9
9
  import type { ContextManager } from "@opentelemetry/api";
10
+ import type { LogRecordExporter } from "@opentelemetry/sdk-logs";
10
11
  import type { SpanExporter, SpanProcessor } from "@opentelemetry/sdk-trace";
11
12
  import type { RequestStartHook } from "./runtime.ts";
12
13
  /** The parts of a platform's setup options RUM reads. WebSetupOptions has every one. */
@@ -14,6 +15,7 @@ export interface RumPlatformOptions {
14
15
  readonly hermetic?: boolean;
15
16
  readonly spanExporter?: SpanExporter;
16
17
  readonly spanProcessor?: SpanProcessor;
18
+ readonly logExporter?: LogRecordExporter;
17
19
  readonly contextManager?: () => ContextManager;
18
20
  readonly transport?: {
19
21
  readonly timeoutMillis?: number;
@@ -26,7 +28,7 @@ export interface RumPlatformOptions {
26
28
  export interface RumPlatformInfo {
27
29
  readonly endpoints: SignalEndpoints;
28
30
  readonly delivery: Delivery;
29
- /** The send mode, for the exporters' unload splitting. Default () => "normal". */
31
+ /** The send mode, for the exporters' unload splitting. Default `() => "normal"`. */
30
32
  readonly mode?: () => SendMode;
31
33
  }
32
34
  /** What the RUM core hands a platform binding, to wrap the parts of the platform's setup RUM needs. */
@@ -1,4 +1,4 @@
1
- /** Contract, frozen by R3a, extended by R3b. The retention buffer for sessions not yet kept. */
1
+ /** The retention buffer for sessions not yet kept. */
2
2
  import type { Delivery, OtlpBatch, QueueSize } from "@libo11y/web/internal";
3
3
  import type { SessionDecision } from "./session.ts";
4
4
  export interface RetentionBuffer {
@@ -6,9 +6,13 @@ export interface RetentionBuffer {
6
6
  put(batch: OtlpBatch): Promise<void>;
7
7
  /**
8
8
  * Sends every stored batch that keep accepts (default every batch) through delivery, and removes
9
- * every batch it claimed, sent or not. Resolves with the batches handed over. Never rejects.
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.
10
14
  */
11
- flush(delivery: Delivery, keep?: (batch: OtlpBatch) => boolean): Promise<number>;
15
+ flush(delivery: Delivery, keep?: (batch: OtlpBatch) => boolean, allowed?: () => boolean): Promise<number>;
12
16
  /** Removes every stored batch. Never rejects. */
13
17
  clear(): Promise<void>;
14
18
  /**