@dash0/sdk-web 0.23.0 → 0.25.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 (91) hide show
  1. package/README.md +5 -0
  2. package/dist/dash0-session-recording.iife.js +2 -0
  3. package/dist/dash0-session-recording.iife.js.map +1 -0
  4. package/dist/dash0-session-recording.js +2 -0
  5. package/dist/dash0-session-recording.js.map +1 -0
  6. package/dist/dash0-session-recording.umd.cjs +2 -0
  7. package/dist/dash0-session-recording.umd.cjs.map +1 -0
  8. package/dist/dash0.iife.js +1 -1
  9. package/dist/dash0.iife.js.map +1 -1
  10. package/dist/dash0.js +1 -1
  11. package/dist/dash0.js.map +1 -1
  12. package/dist/dash0.umd.cjs +1 -1
  13. package/dist/dash0.umd.cjs.map +1 -1
  14. package/dist/modules/api/init.js +18 -1
  15. package/dist/modules/api/init_test.js +27 -0
  16. package/dist/modules/api/session-recording.js +30 -0
  17. package/dist/modules/api/session-recording_test.js +36 -0
  18. package/dist/modules/api/start-view.js +47 -0
  19. package/dist/modules/api/start-view_test.js +91 -0
  20. package/dist/modules/entrypoint/npm-package.js +2 -0
  21. package/dist/modules/entrypoint/npm-package_test.js +7 -0
  22. package/dist/modules/entrypoint/script.js +5 -0
  23. package/dist/modules/entrypoint/session-recording-script.js +19 -0
  24. package/dist/modules/entrypoint/session-recording.js +11 -0
  25. package/dist/modules/instrumentations/navigation/event.js +42 -10
  26. package/dist/modules/instrumentations/navigation/event_test.js +128 -0
  27. package/dist/modules/instrumentations/session-recording/chunker.js +70 -0
  28. package/dist/modules/instrumentations/session-recording/chunker_test.js +125 -0
  29. package/dist/modules/instrumentations/session-recording/index.js +165 -0
  30. package/dist/modules/instrumentations/session-recording/index_test.js +230 -0
  31. package/dist/modules/instrumentations/session-recording/log.js +23 -0
  32. package/dist/modules/instrumentations/session-recording/log_test.js +46 -0
  33. package/dist/modules/semantic-conventions.js +7 -0
  34. package/dist/modules/transport/fetch.js +2 -2
  35. package/dist/modules/transport/fetch_test.js +25 -0
  36. package/dist/modules/transport/index.js +44 -11
  37. package/dist/modules/transport/index_test.js +73 -0
  38. package/dist/modules/types/session-recording.js +1 -0
  39. package/dist/modules/vars.js +11 -0
  40. package/dist/tsconfig.tsbuildinfo +1 -1
  41. package/dist/types/api/session-recording.d.ts +17 -0
  42. package/dist/types/api/session-recording_test.d.ts +1 -0
  43. package/dist/types/api/start-view.d.ts +33 -0
  44. package/dist/types/api/start-view_test.d.ts +1 -0
  45. package/dist/types/entrypoint/npm-package.d.ts +4 -0
  46. package/dist/types/entrypoint/npm-package_test.d.ts +1 -0
  47. package/dist/types/entrypoint/session-recording-script.d.ts +1 -0
  48. package/dist/types/entrypoint/session-recording.d.ts +5 -0
  49. package/dist/types/instrumentations/navigation/event.d.ts +18 -0
  50. package/dist/types/instrumentations/navigation/event_test.d.ts +1 -0
  51. package/dist/types/instrumentations/session-recording/chunker.d.ts +38 -0
  52. package/dist/types/instrumentations/session-recording/chunker_test.d.ts +1 -0
  53. package/dist/types/instrumentations/session-recording/index.d.ts +23 -0
  54. package/dist/types/instrumentations/session-recording/index_test.d.ts +1 -0
  55. package/dist/types/instrumentations/session-recording/log.d.ts +14 -0
  56. package/dist/types/instrumentations/session-recording/log_test.d.ts +1 -0
  57. package/dist/types/semantic-conventions.d.ts +6 -0
  58. package/dist/types/transport/fetch.d.ts +8 -1
  59. package/dist/types/transport/index.d.ts +10 -0
  60. package/dist/types/transport/index_test.d.ts +1 -0
  61. package/dist/types/types/options.d.ts +2 -2
  62. package/dist/types/types/session-recording.d.ts +128 -0
  63. package/dist/types/vars.d.ts +6 -0
  64. package/package.json +11 -3
  65. package/src/api/init.ts +19 -1
  66. package/src/api/init_test.ts +33 -1
  67. package/src/api/session-recording.ts +40 -0
  68. package/src/api/session-recording_test.ts +44 -0
  69. package/src/api/start-view.ts +68 -0
  70. package/src/api/start-view_test.ts +125 -0
  71. package/src/entrypoint/npm-package.ts +4 -0
  72. package/src/entrypoint/npm-package_test.ts +8 -0
  73. package/src/entrypoint/script.ts +5 -0
  74. package/src/entrypoint/session-recording-script.ts +23 -0
  75. package/src/entrypoint/session-recording.ts +13 -0
  76. package/src/instrumentations/navigation/event.ts +63 -15
  77. package/src/instrumentations/navigation/event_test.ts +171 -0
  78. package/src/instrumentations/session-recording/chunker.ts +118 -0
  79. package/src/instrumentations/session-recording/chunker_test.ts +147 -0
  80. package/src/instrumentations/session-recording/index.ts +175 -0
  81. package/src/instrumentations/session-recording/index_test.ts +273 -0
  82. package/src/instrumentations/session-recording/log.ts +48 -0
  83. package/src/instrumentations/session-recording/log_test.ts +60 -0
  84. package/src/semantic-conventions.ts +8 -0
  85. package/src/transport/fetch.ts +10 -2
  86. package/src/transport/fetch_test.ts +30 -0
  87. package/src/transport/index.ts +64 -25
  88. package/src/transport/index_test.ts +90 -0
  89. package/src/types/options.ts +3 -1
  90. package/src/types/session-recording.ts +144 -0
  91. package/src/vars.ts +18 -0
@@ -0,0 +1,147 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { Chunk, newChunker } from "./chunker";
3
+
4
+ // The SDK's timer wrapper captures window.setTimeout at import time, before vitest installs fake timers.
5
+ // Resolve the globals lazily so vi.useFakeTimers() takes effect.
6
+ vi.mock("../../utils/timers", () => ({
7
+ setTimeout: (...args: Parameters<typeof globalThis.setTimeout>) => globalThis.setTimeout(...args),
8
+ clearTimeout: (...args: Parameters<typeof globalThis.clearTimeout>) => globalThis.clearTimeout(...args),
9
+ }));
10
+
11
+ const META = 4;
12
+ const FULL_SNAPSHOT = 2;
13
+ const INCREMENTAL = 3;
14
+
15
+ function event(type: number, timestamp: number, data: unknown = {}) {
16
+ return { type, timestamp, data };
17
+ }
18
+
19
+ describe("session recording chunker", () => {
20
+ let chunks: Chunk[];
21
+
22
+ beforeEach(() => {
23
+ vi.useFakeTimers();
24
+ chunks = [];
25
+ });
26
+
27
+ afterEach(() => {
28
+ vi.useRealTimers();
29
+ });
30
+
31
+ function create(maxBytes = 10_000, maxMillis = 5000) {
32
+ return newChunker({ maxBytes, maxMillis, onChunk: (c) => chunks.push(c) });
33
+ }
34
+
35
+ it("does nothing on flush when empty", () => {
36
+ const chunker = create();
37
+ chunker.flush();
38
+ expect(chunks).toEqual([]);
39
+ });
40
+
41
+ it("discards buffered events and the pending time-based flush", () => {
42
+ const chunker = create();
43
+ chunker.add(event(META, 1000));
44
+ chunker.add(event(FULL_SNAPSHOT, 1001));
45
+
46
+ chunker.discard();
47
+ vi.advanceTimersByTime(10_000);
48
+ expect(chunks).toEqual([]);
49
+
50
+ // The chunker stays usable, and the dropped events do not leak into the next chunk.
51
+ chunker.add(event(INCREMENTAL, 2000));
52
+ chunker.flush();
53
+ expect(chunks).toHaveLength(1);
54
+ expect(chunks[0]!.seq).toBe(0);
55
+ expect(chunks[0]!.eventCount).toBe(1);
56
+ expect(chunks[0]!.hasSnapshot).toBe(false);
57
+ });
58
+
59
+ it("flushes on explicit flush with a serialized JSON array body", () => {
60
+ const chunker = create();
61
+ chunker.add(event(META, 1000, { href: "http://x" }));
62
+ chunker.add(event(FULL_SNAPSHOT, 1001));
63
+ chunker.add(event(INCREMENTAL, 1002));
64
+ chunker.flush();
65
+
66
+ expect(chunks).toHaveLength(1);
67
+ const chunk = chunks[0]!;
68
+ expect(chunk.seq).toBe(0);
69
+ expect(chunk.eventCount).toBe(3);
70
+ expect(chunk.hasSnapshot).toBe(true);
71
+ expect(chunk.startTime).toBe(1000);
72
+ expect(chunk.endTime).toBe(1002);
73
+ expect(JSON.parse(chunk.body)).toEqual([
74
+ { type: META, timestamp: 1000, data: { href: "http://x" } },
75
+ { type: FULL_SNAPSHOT, timestamp: 1001, data: {} },
76
+ { type: INCREMENTAL, timestamp: 1002, data: {} },
77
+ ]);
78
+ });
79
+
80
+ it("flushes when maxMillis elapse after the first event", () => {
81
+ const chunker = create(10_000, 5000);
82
+ chunker.add(event(INCREMENTAL, 1));
83
+ vi.advanceTimersByTime(4999);
84
+ expect(chunks).toHaveLength(0);
85
+ chunker.add(event(INCREMENTAL, 2));
86
+ vi.advanceTimersByTime(1);
87
+ expect(chunks).toHaveLength(1);
88
+ expect(chunks[0]!.eventCount).toBe(2);
89
+ });
90
+
91
+ it("flushes when the serialized size reaches maxBytes", () => {
92
+ const chunker = create(100, 60_000);
93
+ const payload = "x".repeat(40);
94
+ chunker.add(event(INCREMENTAL, 1, payload)); // ~70 bytes
95
+ expect(chunks).toHaveLength(0);
96
+ chunker.add(event(INCREMENTAL, 2, payload)); // crosses 100
97
+ expect(chunks).toHaveLength(1);
98
+ expect(chunks[0]!.eventCount).toBe(2);
99
+ });
100
+
101
+ it("emits an oversized single event as its own chunk", () => {
102
+ const chunker = create(50, 60_000);
103
+ chunker.add(event(FULL_SNAPSHOT, 1, "y".repeat(500)));
104
+ expect(chunks).toHaveLength(1);
105
+ expect(chunks[0]!.eventCount).toBe(1);
106
+ expect(chunks[0]!.hasSnapshot).toBe(true);
107
+ });
108
+
109
+ it("closes the current chunk when a Meta event starts a new snapshot", () => {
110
+ const chunker = create();
111
+ chunker.add(event(META, 1));
112
+ chunker.add(event(FULL_SNAPSHOT, 2));
113
+ chunker.add(event(INCREMENTAL, 3));
114
+ expect(chunks).toHaveLength(0);
115
+
116
+ chunker.add(event(META, 4));
117
+ expect(chunks).toHaveLength(1);
118
+ expect(chunks[0]!.eventCount).toBe(3);
119
+
120
+ chunker.add(event(FULL_SNAPSHOT, 5));
121
+ chunker.flush();
122
+ expect(chunks).toHaveLength(2);
123
+ expect(chunks[1]!.eventCount).toBe(2);
124
+ expect(chunks[1]!.hasSnapshot).toBe(true);
125
+ });
126
+
127
+ it("increments seq across chunks and resets hasSnapshot", () => {
128
+ const chunker = create();
129
+ chunker.add(event(FULL_SNAPSHOT, 1));
130
+ chunker.flush();
131
+ chunker.add(event(INCREMENTAL, 2));
132
+ chunker.flush();
133
+ chunker.add(event(INCREMENTAL, 3));
134
+ chunker.flush();
135
+
136
+ expect(chunks.map((c) => c.seq)).toEqual([0, 1, 2]);
137
+ expect(chunks.map((c) => c.hasSnapshot)).toEqual([true, false, false]);
138
+ });
139
+
140
+ it("cancels the pending timer on flush so it does not fire twice", () => {
141
+ const chunker = create(10_000, 1000);
142
+ chunker.add(event(INCREMENTAL, 1));
143
+ chunker.flush();
144
+ vi.advanceTimersByTime(5000);
145
+ expect(chunks).toHaveLength(1);
146
+ });
147
+ });
@@ -0,0 +1,175 @@
1
+ import { vars } from "../../vars";
2
+ import { sessionId } from "../../api/session";
3
+ import { debug, generateUniqueId, isSessionSampledIn, TRACE_ID_BYTES, warn, win } from "../../utils";
4
+ import { generateTraceId } from "../../utils/trace-id";
5
+ import { generateSpanId } from "../../utils/span-id";
6
+ import { isUrlIgnored } from "../../utils/ignore-rules";
7
+ import { onLastChance } from "../../utils/on-last-chance";
8
+ import { sendSessionRecordingChunk } from "../../transport";
9
+ import { SessionRecorder, SessionRecordingEvent } from "../../types/session-recording";
10
+ import { Chunker, newChunker } from "./chunker";
11
+ import { buildSessionRecordingLog, RecordingStream } from "./log";
12
+
13
+ /**
14
+ * Global set by `dash0-session-recording.iife.js`. Read by `armSessionRecording()` and by
15
+ * `startSessionRecording()` when called without a recorder.
16
+ */
17
+ export const GLOBAL_RECORDER_KEY = "dash0Recorder";
18
+
19
+ let recorder: SessionRecorder | undefined;
20
+ let armed = false;
21
+ let stopRecorder: (() => void) | undefined;
22
+ let chunker: Chunker | undefined;
23
+ let lastChanceRegistered = false;
24
+ // True while the last-chance handler flushes. The chunk emitted then must be sent uncompressed: gzip is
25
+ // asynchronous, and a document that is being unloaded may never get to the `fetch()` behind the await.
26
+ let flushingOnLastChance = false;
27
+
28
+ /**
29
+ * Makes a recorder available. Called from the public `startSessionRecording` API, which the
30
+ * `dash0-session-recording.iife.js` script and npm consumers use. Recording starts as soon as both a recorder
31
+ * is registered and `init()` has armed session recording, in either order.
32
+ */
33
+ export function registerSessionRecorder(r: SessionRecorder): void {
34
+ recorder = r;
35
+ if (armed) {
36
+ start();
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Called from `init()` once configuration is in place and the session is sampled.
42
+ *
43
+ * Recorder precedence: `sessionRecording.recorder` from the init options, then a recorder registered through
44
+ * `startSessionRecording(recorder)`, then `window.dash0Recorder`. The last one is set by
45
+ * `dash0-session-recording.iife.js`, and is the only handover that works when that script executes before the
46
+ * initializer snippet has defined the `dash0` command queue.
47
+ */
48
+ export function armSessionRecording(): void {
49
+ armed = true;
50
+ if (vars.sessionRecording.recorder) {
51
+ recorder = vars.sessionRecording.recorder;
52
+ } else if (!recorder) {
53
+ const globalRecorder = (win as any)?.[GLOBAL_RECORDER_KEY];
54
+ if (typeof globalRecorder === "function") {
55
+ recorder = globalRecorder as SessionRecorder;
56
+ }
57
+ }
58
+ if (recorder) {
59
+ start();
60
+ }
61
+ }
62
+
63
+ export function stopSessionRecording(): void {
64
+ if (stopRecorder) {
65
+ try {
66
+ stopRecorder();
67
+ } catch (e) {
68
+ debug("Failed to stop session recorder", e);
69
+ }
70
+ stopRecorder = undefined;
71
+ }
72
+ chunker?.flush();
73
+ chunker = undefined;
74
+ }
75
+
76
+ export function isSessionRecording(): boolean {
77
+ return stopRecorder != null;
78
+ }
79
+
80
+ function start(): void {
81
+ if (stopRecorder) {
82
+ debug("Session recording already running. Ignoring start.");
83
+ return;
84
+ }
85
+ if (!recorder || !win) return;
86
+
87
+ const settings = vars.sessionRecording;
88
+
89
+ if (!vars.isSessionSampled) {
90
+ debug("Session is not sampled. Session recording will not start.");
91
+ return;
92
+ }
93
+ if (!isSessionSampledIn(sessionId ?? "", settings.samplingRate ?? 100)) {
94
+ debug("Session is not sampled for recording. Session recording will not start.");
95
+ return;
96
+ }
97
+ if (isUrlIgnored(win.location.href)) {
98
+ debug("Page URL is ignored. Session recording will not start.");
99
+ return;
100
+ }
101
+
102
+ const traceId = generateTraceId(sessionId);
103
+ const stream: RecordingStream = {
104
+ recordingId: generateUniqueId(TRACE_ID_BYTES),
105
+ traceId,
106
+ spanId: generateSpanId(traceId),
107
+ };
108
+
109
+ const c = newChunker({
110
+ maxBytes: settings.chunkMaxBytes ?? 48000,
111
+ maxMillis: settings.chunkMaxMillis ?? 5000,
112
+ onChunk: (chunk) => {
113
+ try {
114
+ sendSessionRecordingChunk(buildSessionRecordingLog(stream, chunk), { compress: !flushingOnLastChance });
115
+ } catch (e) {
116
+ warn("Failed to transmit session recording chunk", e);
117
+ }
118
+ },
119
+ });
120
+ chunker = c;
121
+
122
+ try {
123
+ stopRecorder = recorder({
124
+ // rrweb can still emit after its stop function ran (trailing throttle timers), and a recorder that failed
125
+ // to start may have emitted already. Only accept events while this chunker is the active one.
126
+ emit: (event: SessionRecordingEvent) => {
127
+ if (chunker === c) c.add(event);
128
+ },
129
+ checkoutEveryNms: settings.checkoutEveryNms,
130
+ maskAllInputs: settings.maskAllInputs,
131
+ maskTextClass: settings.maskTextClass,
132
+ maskTextSelector: settings.maskTextSelector,
133
+ maskInputFn: settings.maskInputFn,
134
+ maskTextFn: settings.maskTextFn,
135
+ blockClass: settings.blockClass,
136
+ blockSelector: settings.blockSelector,
137
+ recordCanvas: settings.recordCanvas,
138
+ collectFonts: settings.collectFonts,
139
+ });
140
+ } catch (e) {
141
+ warn("Failed to start session recorder", e);
142
+ abandonChunker(c);
143
+ return;
144
+ }
145
+
146
+ if (!stopRecorder) {
147
+ // rrweb returns undefined when it refuses to record, e.g. in an unsupported environment.
148
+ warn("Session recorder did not start.");
149
+ abandonChunker(c);
150
+ return;
151
+ }
152
+
153
+ if (!lastChanceRegistered) {
154
+ lastChanceRegistered = true;
155
+ onLastChance(() => {
156
+ flushingOnLastChance = true;
157
+ try {
158
+ chunker?.flush();
159
+ } finally {
160
+ flushingOnLastChance = false;
161
+ }
162
+ });
163
+ }
164
+
165
+ debug("Session recording started", stream);
166
+ }
167
+
168
+ /**
169
+ * The recorder did not start, but it may already have emitted events into `c` and armed its flush timer. Drop
170
+ * them so no chunk of a stream that never started is transmitted later.
171
+ */
172
+ function abandonChunker(c: Chunker): void {
173
+ c.discard();
174
+ chunker = undefined;
175
+ }
@@ -0,0 +1,273 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import type { SessionRecorder, SessionRecorderOptions } from "../../types/session-recording";
3
+ import { win } from "../../utils";
4
+
5
+ vi.mock("../../transport", () => ({
6
+ sendSessionRecordingChunk: vi.fn(),
7
+ sendLog: vi.fn(),
8
+ sendSpan: vi.fn(),
9
+ }));
10
+
11
+ vi.mock("../../api/session", () => ({
12
+ sessionId: "aabbccdd11223344",
13
+ }));
14
+
15
+ type Module = typeof import("./index");
16
+
17
+ describe("session recording lifecycle", () => {
18
+ let mod: Module;
19
+ let vars: typeof import("../../vars").vars;
20
+ let sendSessionRecordingChunk: ReturnType<typeof vi.fn>;
21
+ let stopFn: ReturnType<typeof vi.fn>;
22
+ let recorder: ReturnType<typeof vi.fn> & SessionRecorder;
23
+ let capturedOptions: SessionRecorderOptions | undefined;
24
+
25
+ beforeEach(async () => {
26
+ vi.resetModules();
27
+ vi.useFakeTimers();
28
+ mod = await import("./index");
29
+ vars = (await import("../../vars")).vars;
30
+ sendSessionRecordingChunk = (await import("../../transport")).sendSessionRecordingChunk as any;
31
+ sendSessionRecordingChunk.mockClear();
32
+
33
+ vars.isSessionSampled = true;
34
+ vars.ignoreUrls = [];
35
+ vars.endpoints = [{ url: "https://ingress.example.com", authToken: "x" }];
36
+ vars.sessionRecording = { ...vars.sessionRecording, samplingRate: 100, recorder: undefined };
37
+
38
+ stopFn = vi.fn();
39
+ capturedOptions = undefined;
40
+ recorder = vi.fn((opts: SessionRecorderOptions) => {
41
+ capturedOptions = opts;
42
+ return stopFn;
43
+ }) as any;
44
+ });
45
+
46
+ afterEach(() => {
47
+ mod.stopSessionRecording();
48
+ vi.useRealTimers();
49
+ });
50
+
51
+ it("does not start before init arms recording", () => {
52
+ mod.registerSessionRecorder(recorder);
53
+ expect(recorder).not.toHaveBeenCalled();
54
+ expect(mod.isSessionRecording()).toBe(false);
55
+ });
56
+
57
+ it("starts when armed after the recorder was registered", () => {
58
+ mod.registerSessionRecorder(recorder);
59
+ mod.armSessionRecording();
60
+ expect(recorder).toHaveBeenCalledTimes(1);
61
+ expect(mod.isSessionRecording()).toBe(true);
62
+ });
63
+
64
+ it("starts when the recorder is registered after arming", () => {
65
+ mod.armSessionRecording();
66
+ expect(recorder).not.toHaveBeenCalled();
67
+ mod.registerSessionRecorder(recorder);
68
+ expect(recorder).toHaveBeenCalledTimes(1);
69
+ });
70
+
71
+ it("picks up window.dash0Recorder when arming, so the recorder script may run before the initializer", () => {
72
+ (win as any).dash0Recorder = recorder;
73
+ try {
74
+ mod.armSessionRecording();
75
+ expect(recorder).toHaveBeenCalledTimes(1);
76
+ expect(mod.isSessionRecording()).toBe(true);
77
+ } finally {
78
+ delete (win as any).dash0Recorder;
79
+ }
80
+ });
81
+
82
+ it("prefers an explicitly registered recorder over window.dash0Recorder", () => {
83
+ const globalRecorder = vi.fn(() => vi.fn());
84
+ (win as any).dash0Recorder = globalRecorder;
85
+ try {
86
+ mod.registerSessionRecorder(recorder);
87
+ mod.armSessionRecording();
88
+ expect(recorder).toHaveBeenCalledTimes(1);
89
+ expect(globalRecorder).not.toHaveBeenCalled();
90
+ } finally {
91
+ delete (win as any).dash0Recorder;
92
+ }
93
+ });
94
+
95
+ it("ignores a window.dash0Recorder that is not a function", () => {
96
+ (win as any).dash0Recorder = "nope";
97
+ try {
98
+ mod.armSessionRecording();
99
+ expect(mod.isSessionRecording()).toBe(false);
100
+ } finally {
101
+ delete (win as any).dash0Recorder;
102
+ }
103
+ });
104
+
105
+ it("uses the recorder from vars.sessionRecording.recorder", () => {
106
+ vars.sessionRecording.recorder = recorder;
107
+ mod.armSessionRecording();
108
+ expect(recorder).toHaveBeenCalledTimes(1);
109
+ });
110
+
111
+ it("does not start twice", () => {
112
+ mod.armSessionRecording();
113
+ mod.registerSessionRecorder(recorder);
114
+ mod.registerSessionRecorder(recorder);
115
+ mod.armSessionRecording();
116
+ expect(recorder).toHaveBeenCalledTimes(1);
117
+ });
118
+
119
+ it("forwards privacy settings to the recorder with masking on by default", () => {
120
+ mod.armSessionRecording();
121
+ mod.registerSessionRecorder(recorder);
122
+
123
+ expect(capturedOptions).toMatchObject({
124
+ maskAllInputs: true,
125
+ maskTextClass: "dash0-mask",
126
+ blockClass: "dash0-block",
127
+ recordCanvas: false,
128
+ collectFonts: false,
129
+ checkoutEveryNms: 300000,
130
+ });
131
+ expect(typeof capturedOptions!.emit).toBe("function");
132
+ });
133
+
134
+ it("does not start when the session is not sampled", () => {
135
+ vars.isSessionSampled = false;
136
+ mod.armSessionRecording();
137
+ mod.registerSessionRecorder(recorder);
138
+ expect(recorder).not.toHaveBeenCalled();
139
+ });
140
+
141
+ it("does not start when the recording sampling rate excludes the session", () => {
142
+ vars.sessionRecording.samplingRate = 0;
143
+ mod.armSessionRecording();
144
+ mod.registerSessionRecorder(recorder);
145
+ expect(recorder).not.toHaveBeenCalled();
146
+ });
147
+
148
+ it("does not start when the page url is ignored", () => {
149
+ vars.ignoreUrls = [/localhost/];
150
+ mod.armSessionRecording();
151
+ mod.registerSessionRecorder(recorder);
152
+ expect(recorder).not.toHaveBeenCalled();
153
+ });
154
+
155
+ it("survives a recorder that throws", () => {
156
+ const throwing = vi.fn(() => {
157
+ throw new Error("boom");
158
+ }) as any;
159
+ mod.armSessionRecording();
160
+ mod.registerSessionRecorder(throwing);
161
+ expect(mod.isSessionRecording()).toBe(false);
162
+ });
163
+
164
+ it("discards events emitted by a recorder that then refuses to start", () => {
165
+ // rrweb emits Meta + FullSnapshot synchronously and returns undefined when it cannot record.
166
+ const refusing = vi.fn((opts: SessionRecorderOptions) => {
167
+ opts.emit({ type: 4, timestamp: 1000, data: {} });
168
+ opts.emit({ type: 2, timestamp: 1001, data: {} });
169
+ return undefined;
170
+ }) as any;
171
+ mod.armSessionRecording();
172
+ mod.registerSessionRecorder(refusing);
173
+
174
+ expect(mod.isSessionRecording()).toBe(false);
175
+ vi.advanceTimersByTime(10_000);
176
+ expect(sendSessionRecordingChunk).not.toHaveBeenCalled();
177
+
178
+ // stop must be a harmless no-op afterwards
179
+ expect(() => mod.stopSessionRecording()).not.toThrow();
180
+ expect(sendSessionRecordingChunk).not.toHaveBeenCalled();
181
+ });
182
+
183
+ it("swallows a stop function that throws and still resets its state", () => {
184
+ stopFn.mockImplementation(() => {
185
+ throw new Error("stop failed");
186
+ });
187
+ mod.armSessionRecording();
188
+ mod.registerSessionRecorder(recorder);
189
+ capturedOptions!.emit({ type: 3, timestamp: 1, data: {} });
190
+
191
+ expect(() => mod.stopSessionRecording()).not.toThrow();
192
+ expect(mod.isSessionRecording()).toBe(false);
193
+ // buffered events are still flushed
194
+ expect(sendSessionRecordingChunk).toHaveBeenCalledTimes(1);
195
+ });
196
+
197
+ it("ignores events the recorder emits after stop", () => {
198
+ mod.armSessionRecording();
199
+ mod.registerSessionRecorder(recorder);
200
+ mod.stopSessionRecording();
201
+ sendSessionRecordingChunk.mockClear();
202
+
203
+ // rrweb's trailing throttle timers can still call emit after its stop function ran.
204
+ capturedOptions!.emit({ type: 3, timestamp: 1, data: {} });
205
+ vi.advanceTimersByTime(10_000);
206
+ expect(sendSessionRecordingChunk).not.toHaveBeenCalled();
207
+ });
208
+
209
+ it("compresses periodic chunks but sends the last-chance flush uncompressed", () => {
210
+ mod.armSessionRecording();
211
+ mod.registerSessionRecorder(recorder);
212
+
213
+ capturedOptions!.emit({ type: 3, timestamp: 1, data: {} });
214
+ vi.advanceTimersByTime(5000);
215
+ expect(sendSessionRecordingChunk).toHaveBeenCalledTimes(1);
216
+ expect(sendSessionRecordingChunk.mock.calls[0]![1]).toEqual({ compress: true });
217
+
218
+ capturedOptions!.emit({ type: 3, timestamp: 2, data: {} });
219
+ globalThis.dispatchEvent(new Event("pagehide"));
220
+ expect(sendSessionRecordingChunk).toHaveBeenCalledTimes(2);
221
+ expect(sendSessionRecordingChunk.mock.calls[1]![1]).toEqual({ compress: false });
222
+
223
+ // back to normal once the page keeps running
224
+ capturedOptions!.emit({ type: 3, timestamp: 3, data: {} });
225
+ vi.advanceTimersByTime(5000);
226
+ expect(sendSessionRecordingChunk).toHaveBeenCalledTimes(3);
227
+ expect(sendSessionRecordingChunk.mock.calls[2]![1]).toEqual({ compress: true });
228
+ });
229
+
230
+ it("transmits chunks that share one trace id embedding the session id", () => {
231
+ mod.armSessionRecording();
232
+ mod.registerSessionRecorder(recorder);
233
+
234
+ capturedOptions!.emit({ type: 4, timestamp: 1000, data: {} });
235
+ capturedOptions!.emit({ type: 2, timestamp: 1001, data: {} });
236
+ vi.advanceTimersByTime(5000);
237
+ capturedOptions!.emit({ type: 3, timestamp: 7000, data: {} });
238
+ vi.advanceTimersByTime(5000);
239
+
240
+ expect(sendSessionRecordingChunk).toHaveBeenCalledTimes(2);
241
+ const [first, second] = sendSessionRecordingChunk.mock.calls.map((c) => c[0]);
242
+
243
+ expect(first.traceId).toMatch(/^d04200aabbccdd11223344[0-9a-f]{10}$/);
244
+ expect(second.traceId).toBe(first.traceId);
245
+ expect(second.spanId).toBe(first.spanId);
246
+ expect(first.attributes).toEqual(
247
+ expect.arrayContaining([
248
+ { key: "event.name", value: { stringValue: "browser.session_recording" } },
249
+ { key: "dash0.session_recording.seq", value: { intValue: "0" } },
250
+ { key: "dash0.session_recording.has_snapshot", value: { boolValue: true } },
251
+ ])
252
+ );
253
+ expect(second.attributes).toEqual(
254
+ expect.arrayContaining([
255
+ { key: "dash0.session_recording.seq", value: { intValue: "1" } },
256
+ { key: "dash0.session_recording.has_snapshot", value: { boolValue: false } },
257
+ ])
258
+ );
259
+ });
260
+
261
+ it("stops the recorder and flushes buffered events on stop", () => {
262
+ mod.armSessionRecording();
263
+ mod.registerSessionRecorder(recorder);
264
+ capturedOptions!.emit({ type: 3, timestamp: 1, data: {} });
265
+ expect(sendSessionRecordingChunk).not.toHaveBeenCalled();
266
+
267
+ mod.stopSessionRecording();
268
+
269
+ expect(stopFn).toHaveBeenCalledTimes(1);
270
+ expect(sendSessionRecordingChunk).toHaveBeenCalledTimes(1);
271
+ expect(mod.isSessionRecording()).toBe(false);
272
+ });
273
+ });
@@ -0,0 +1,48 @@
1
+ import { addAttribute } from "../../utils/otel";
2
+ import {
3
+ EVENT_NAME,
4
+ EVENT_NAMES,
5
+ LOG_SEVERITIES,
6
+ SESSION_RECORDING_END_TIME_UNIX_NANO,
7
+ SESSION_RECORDING_EVENT_COUNT,
8
+ SESSION_RECORDING_HAS_SNAPSHOT,
9
+ SESSION_RECORDING_ID,
10
+ SESSION_RECORDING_SEQ,
11
+ } from "../../semantic-conventions";
12
+ import { addCommonAttributes } from "../../attributes";
13
+ import { toNanosTs } from "../../utils";
14
+ import { KeyValue, LogRecord } from "../../types/otlp";
15
+ import { Chunk } from "./chunker";
16
+
17
+ export type RecordingStream = {
18
+ /**
19
+ * Identifies one recorder run. All chunks of the run share it.
20
+ */
21
+ recordingId: string;
22
+ /**
23
+ * Trace context shared by all chunks of the run. The trace ID embeds the session ID.
24
+ */
25
+ traceId: string;
26
+ spanId: string;
27
+ };
28
+
29
+ export function buildSessionRecordingLog(stream: RecordingStream, chunk: Chunk): LogRecord {
30
+ const attributes: KeyValue[] = [];
31
+ addAttribute(attributes, EVENT_NAME, EVENT_NAMES.SESSION_RECORDING);
32
+ addCommonAttributes(attributes);
33
+ addAttribute(attributes, SESSION_RECORDING_ID, stream.recordingId);
34
+ addAttribute(attributes, SESSION_RECORDING_SEQ, { intValue: String(chunk.seq) });
35
+ addAttribute(attributes, SESSION_RECORDING_EVENT_COUNT, { intValue: String(chunk.eventCount) });
36
+ addAttribute(attributes, SESSION_RECORDING_HAS_SNAPSHOT, chunk.hasSnapshot);
37
+ addAttribute(attributes, SESSION_RECORDING_END_TIME_UNIX_NANO, { intValue: toNanosTs(chunk.endTime) });
38
+
39
+ return {
40
+ timeUnixNano: toNanosTs(chunk.startTime),
41
+ severityNumber: LOG_SEVERITIES.INFO,
42
+ severityText: "INFO",
43
+ body: { stringValue: chunk.body },
44
+ attributes,
45
+ traceId: stream.traceId,
46
+ spanId: stream.spanId,
47
+ };
48
+ }