@sypnia/browser 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1199 @@
1
+ import { safe, matchesRoute, MAX_CHUNKS_PER_SESSION, whenIdle, writeDecision, CHUNK_CHARS, MAX_EVENT_CHARS, MAX_BUFFER_CHARS, CHUNK_INTERVAL_MS, readDecision, RESYNC_DELAYS_MS, SNAPSHOT_DELAY_MS, SNAPSHOTS_PER_SESSION, QUIET_MS, MAX_QUIET_WAIT_MS, SNAPSHOT_CHARS, deviceClassOf, post, encode, RETRY_DELAYS_MS, KEEPALIVE_MAX_CHARS, beacon, PARK_MAX_MS, PARK_BASE_MS, RECORD_CHECKOUT_MS, BUFFER_MS } from './chunk-SLX7QGK4.js';
2
+ import { record } from 'rrweb';
3
+
4
+ // src/recorder/masking.ts
5
+ var MASK_SELECTOR = "[data-sypnia-mask]";
6
+ var BLOCK_SELECTOR = "iframe, frame, object, embed, video, [data-sypnia-block]";
7
+ var EDITABLE_SELECTOR = '[contenteditable]:not([contenteditable="false"])';
8
+ var TOKEN_PARAMS = /* @__PURE__ */ new Set(["access_token", "refresh_token", "token", "code"]);
9
+ var URL_ATTRS = ["href", "action", "formaction"];
10
+ var TEXT_ATTRS = [
11
+ "title",
12
+ "alt",
13
+ "placeholder",
14
+ "aria-label",
15
+ "aria-description",
16
+ "aria-valuetext",
17
+ "aria-placeholder",
18
+ "data-tooltip",
19
+ "data-tip",
20
+ "data-title",
21
+ "data-label"
22
+ ];
23
+ var STRUCTURAL_DATA_ATTRS = /* @__PURE__ */ new Set([
24
+ "data-sypnia-mask",
25
+ "data-sypnia-block",
26
+ "data-state",
27
+ "data-slot",
28
+ "data-side",
29
+ "data-align",
30
+ "data-orientation",
31
+ "data-disabled",
32
+ "data-highlighted",
33
+ "data-selected",
34
+ "data-active",
35
+ "data-variant",
36
+ "data-size",
37
+ "data-testid"
38
+ ]);
39
+ var EMPTY_OR_BOOLEAN = /^\s*(true|false)?\s*$/i;
40
+ var CONTACT_LINK = /^(\s*(?:mailto|tel|sms):)([\s\S]*)$/i;
41
+ var FORM_TAGS = /* @__PURE__ */ new Set(["input", "textarea", "select"]);
42
+ var LETTER_OR_DIGIT = (() => {
43
+ try {
44
+ return new RegExp("[\\p{L}\\p{N}]", "gu");
45
+ } catch {
46
+ return /[A-Za-z0-9\u00C0-\u024F\u0370-\u03FF\u0400-\u04FF]/g;
47
+ }
48
+ })();
49
+ var DOCUMENT_NODE = 0;
50
+ var ELEMENT_NODE = 2;
51
+ var TEXT_NODE = 3;
52
+ var FULL_SNAPSHOT = 2;
53
+ var INCREMENTAL_SNAPSHOT = 3;
54
+ var META = 4;
55
+ var MUTATION_SOURCE = 0;
56
+ var INPUT_SOURCE = 5;
57
+ var POSITION_SOURCES = /* @__PURE__ */ new Set([1, 6, 12]);
58
+ var SELECTION_SOURCE = 14;
59
+ function isValidSelector(selector) {
60
+ try {
61
+ document.createDocumentFragment().querySelector(selector);
62
+ return true;
63
+ } catch {
64
+ return false;
65
+ }
66
+ }
67
+ function maskRules(options) {
68
+ const extraMask = options.maskSelector?.trim() || null;
69
+ const extraBlock = options.blockSelector?.trim() || null;
70
+ const unreadableMask = extraMask !== null && !isValidSelector(extraMask);
71
+ const all = options.maskAllText || unreadableMask;
72
+ return {
73
+ policy: all ? 2 : 1,
74
+ all,
75
+ maskSelector: extraMask && !unreadableMask ? `${MASK_SELECTOR}, ${extraMask}` : MASK_SELECTOR,
76
+ blockSelector: extraBlock && isValidSelector(extraBlock) ? `${BLOCK_SELECTOR}, ${extraBlock}` : BLOCK_SELECTOR
77
+ };
78
+ }
79
+ function maskString(text) {
80
+ return text.replace(LETTER_OR_DIGIT, "*");
81
+ }
82
+ function maskValue(text) {
83
+ return "*".repeat(text.length);
84
+ }
85
+ function closestOf(node, selector) {
86
+ if (!node) return null;
87
+ try {
88
+ const el = node.nodeType === 1 ? node : node.parentElement;
89
+ return el ? el.closest(selector) : null;
90
+ } catch {
91
+ return null;
92
+ }
93
+ }
94
+ var maskInput = (text) => maskValue(text);
95
+ var maskText = (text, element) => closestOf(element, EDITABLE_SELECTOR) ? maskValue(text) : maskString(text);
96
+ function serializerOptions(rules) {
97
+ return {
98
+ maskAllInputs: true,
99
+ maskInputFn: maskInput,
100
+ maskTextSelector: rules.all ? "*" : `${rules.maskSelector}, ${EDITABLE_SELECTOR}`,
101
+ maskTextFn: maskText,
102
+ blockSelector: rules.blockSelector,
103
+ inlineImages: false,
104
+ inlineStylesheet: true,
105
+ recordCanvas: false
106
+ };
107
+ }
108
+ function decodeKey(raw) {
109
+ try {
110
+ return decodeURIComponent(raw.replace(/\+/g, " ")).trim().toLowerCase();
111
+ } catch {
112
+ return raw.trim().toLowerCase();
113
+ }
114
+ }
115
+ function dropTokenParams(query) {
116
+ const pairs = query.split("&");
117
+ const kept = pairs.filter((pair) => {
118
+ const eq = pair.indexOf("=");
119
+ return !TOKEN_PARAMS.has(decodeKey(eq >= 0 ? pair.slice(0, eq) : pair));
120
+ });
121
+ return kept.length === pairs.length ? null : kept.filter(Boolean).join("&");
122
+ }
123
+ function scrubUrl(value) {
124
+ if (!/[?#]/.test(value) || /^\s*(mailto|tel|sms):/i.test(value)) return value;
125
+ const hashAt = value.indexOf("#");
126
+ const main = hashAt >= 0 ? value.slice(0, hashAt) : value;
127
+ const hash = hashAt >= 0 ? value.slice(hashAt + 1) : null;
128
+ const queryAt = main.indexOf("?");
129
+ let changed = false;
130
+ let out = queryAt >= 0 ? main.slice(0, queryAt) : main;
131
+ if (queryAt >= 0) {
132
+ const query = main.slice(queryAt + 1);
133
+ const kept = dropTokenParams(query);
134
+ if (kept !== null) changed = true;
135
+ const next = kept ?? query;
136
+ if (next) out += `?${next}`;
137
+ }
138
+ if (hash !== null) {
139
+ const inner = hash.indexOf("?");
140
+ let next = hash;
141
+ if (inner >= 0) {
142
+ const kept = dropTokenParams(hash.slice(inner + 1));
143
+ if (kept !== null) {
144
+ changed = true;
145
+ next = kept ? `${hash.slice(0, inner)}?${kept}` : hash.slice(0, inner);
146
+ }
147
+ } else if (hash.includes("=")) {
148
+ const kept = dropTokenParams(hash);
149
+ if (kept !== null) {
150
+ changed = true;
151
+ next = kept;
152
+ }
153
+ }
154
+ if (next) out += `#${next}`;
155
+ }
156
+ return changed ? out : value;
157
+ }
158
+ function scrubAttributes(attributes, tag, masked) {
159
+ for (const name of URL_ATTRS) {
160
+ const value = attributes[name];
161
+ if (typeof value === "string" && value) attributes[name] = scrubUrl(value);
162
+ }
163
+ if (FORM_TAGS.has(tag) && "value" in attributes) {
164
+ if (tag === "input" && String(attributes.type ?? "").trim().toLowerCase() === "hidden") delete attributes.value;
165
+ else if (typeof attributes.value === "string") attributes.value = maskValue(attributes.value);
166
+ }
167
+ if (tag === "option") delete attributes.selected;
168
+ if (!masked) return;
169
+ for (const name of Object.keys(attributes)) {
170
+ const value = attributes[name];
171
+ if (typeof value !== "string" || !value) continue;
172
+ const isText = TEXT_ATTRS.includes(name);
173
+ const isContentData = name.startsWith("data-") && !STRUCTURAL_DATA_ATTRS.has(name) && !name.startsWith("data-rr");
174
+ if (isText || isContentData && !EMPTY_OR_BOOLEAN.test(value)) attributes[name] = maskString(value);
175
+ }
176
+ const href = attributes.href;
177
+ const contact = typeof href === "string" ? CONTACT_LINK.exec(href) : null;
178
+ if (contact) attributes.href = `${contact[1] ?? ""}${maskString(contact[2] ?? "")}`;
179
+ delete attributes.checked;
180
+ delete attributes.selected;
181
+ }
182
+ function leftOut(node, rules, self) {
183
+ if (!node) return false;
184
+ try {
185
+ if ((node.nodeType === 9 ? node : node.ownerDocument) !== document) return true;
186
+ let current = self ? node : node.parentNode ?? node.host ?? null;
187
+ while (current) {
188
+ if (current.nodeType === 11) {
189
+ current = current.host ?? null;
190
+ continue;
191
+ }
192
+ if (current.nodeType !== 1) {
193
+ current = current.parentNode;
194
+ continue;
195
+ }
196
+ if (current.closest(rules.blockSelector)) return true;
197
+ const root = current.getRootNode();
198
+ current = root.nodeType === 11 ? root : null;
199
+ }
200
+ return false;
201
+ } catch {
202
+ return true;
203
+ }
204
+ }
205
+ function isPlaceholder(attributes, live, rules) {
206
+ if (hasAttribute(attributes, "rr_width") || hasAttribute(attributes, "rr_height")) return true;
207
+ try {
208
+ return live !== null && live.nodeType === 1 && live.matches(rules.blockSelector);
209
+ } catch {
210
+ return false;
211
+ }
212
+ }
213
+ function toPlaceholder(node, attributes) {
214
+ const kept = {};
215
+ for (const name of ["rr_width", "rr_height"]) if (hasAttribute(attributes, name)) kept[name] = attributes?.[name];
216
+ node.attributes = kept;
217
+ node.childNodes = [];
218
+ delete node.isShadowHost;
219
+ }
220
+ function resolve(lookup, id) {
221
+ if (!lookup || typeof id !== "number") return null;
222
+ try {
223
+ return lookup(id) ?? null;
224
+ } catch {
225
+ return null;
226
+ }
227
+ }
228
+ function hasAttribute(attributes, name) {
229
+ return !!attributes && Object.prototype.hasOwnProperty.call(attributes, name);
230
+ }
231
+ function isEditableAttribute(attributes) {
232
+ if (!hasAttribute(attributes, "contenteditable")) return false;
233
+ return String(attributes?.contenteditable).trim().toLowerCase() !== "false";
234
+ }
235
+ function liveContext(node, rules) {
236
+ return {
237
+ masked: rules.all || closestOf(node, rules.maskSelector) !== null,
238
+ editable: closestOf(node, EDITABLE_SELECTOR) !== null
239
+ };
240
+ }
241
+ function scrubNode(root, rules, lookup, inherited) {
242
+ if (!root || typeof root !== "object") return;
243
+ const start = inherited ?? { masked: rules.all, editable: false };
244
+ const stack = [{ node: root, context: start, parentTag: "" }];
245
+ while (stack.length > 0) {
246
+ const item = stack.pop();
247
+ if (!item) break;
248
+ const { node, parentTag } = item;
249
+ let context = item.context;
250
+ let tag = "";
251
+ if (node.type === ELEMENT_NODE) {
252
+ tag = typeof node.tagName === "string" ? node.tagName.toLowerCase() : "";
253
+ const attributes = node.attributes && typeof node.attributes === "object" ? node.attributes : void 0;
254
+ const live = resolve(lookup, node.id);
255
+ if (isPlaceholder(attributes, live, rules)) {
256
+ toPlaceholder(node, attributes);
257
+ continue;
258
+ }
259
+ const masked = context.masked || hasAttribute(attributes, "data-sypnia-mask") || live !== null && closestOf(live, rules.maskSelector) !== null;
260
+ context = { masked, editable: context.editable || isEditableAttribute(attributes) };
261
+ if (attributes) scrubAttributes(attributes, tag, masked);
262
+ } else if (node.type === TEXT_NODE && typeof node.textContent === "string" && node.textContent) {
263
+ const code = node.isStyle === true || parentTag === "style" || parentTag === "script";
264
+ if (parentTag === "textarea" || context.editable) node.textContent = maskValue(node.textContent);
265
+ else if (context.masked && !code) node.textContent = maskString(node.textContent);
266
+ }
267
+ let children = node.childNodes;
268
+ if (!Array.isArray(children)) continue;
269
+ if (children.some((child) => child?.type === DOCUMENT_NODE)) children = node.childNodes = children.filter((child) => child?.type !== DOCUMENT_NODE);
270
+ for (let i = children.length - 1; i >= 0; i--) {
271
+ const child = children[i];
272
+ if (child && typeof child === "object") stack.push({ node: child, context, parentTag: tag });
273
+ }
274
+ }
275
+ }
276
+ var list = (value) => Array.isArray(value) ? value : [];
277
+ function dropLeftOut(data, rules, lookup) {
278
+ const seen = /* @__PURE__ */ new Map();
279
+ const out = (id, self) => {
280
+ const key = `${String(id)}:${self ? 1 : 0}`;
281
+ let value = seen.get(key);
282
+ if (value === void 0) seen.set(key, value = leftOut(resolve(lookup, id), rules, self));
283
+ return value;
284
+ };
285
+ if (data.source === MUTATION_SOURCE) {
286
+ const adds = list(data.adds).filter(
287
+ (add) => !!add && add.node?.type !== DOCUMENT_NODE && !out(add.parentId, true)
288
+ );
289
+ const removes = list(data.removes).filter((remove) => !!remove && !out(remove.parentId, true));
290
+ const attributes = list(data.attributes).filter((change) => !!change && !out(change.id, true));
291
+ const texts = list(data.texts).filter((text) => !!text && !out(text.id, true));
292
+ if (Array.isArray(data.adds)) data.adds = adds;
293
+ if (Array.isArray(data.removes)) data.removes = removes;
294
+ if (Array.isArray(data.attributes)) data.attributes = attributes;
295
+ if (Array.isArray(data.texts)) data.texts = texts;
296
+ return adds.length + removes.length + attributes.length + texts.length === 0;
297
+ }
298
+ if (typeof data.source === "number" && POSITION_SOURCES.has(data.source) && Array.isArray(data.positions)) {
299
+ data.positions = data.positions.filter((position) => !!position && !out(position.id, false));
300
+ return data.positions.length === 0;
301
+ }
302
+ if (data.source === SELECTION_SOURCE) return list(data.ranges).some((range) => !range || out(range.start, false) || out(range.end, false));
303
+ return out(data.id, false);
304
+ }
305
+ function tagOf(node) {
306
+ try {
307
+ return node && node.nodeType === 1 ? node.tagName.toLowerCase() : "";
308
+ } catch {
309
+ return "";
310
+ }
311
+ }
312
+ function scrubEvent(event, rules, lookup) {
313
+ if (!event || typeof event !== "object") return true;
314
+ const { type, data } = event;
315
+ if (!data || typeof data !== "object") return true;
316
+ if (type === META) {
317
+ if (typeof data.href === "string") data.href = scrubUrl(data.href);
318
+ return true;
319
+ }
320
+ if (type === FULL_SNAPSHOT) {
321
+ scrubNode(data.node, rules, lookup);
322
+ return true;
323
+ }
324
+ if (type !== INCREMENTAL_SNAPSHOT) return true;
325
+ if (dropLeftOut(data, rules, lookup)) return false;
326
+ if (data.source === INPUT_SOURCE) {
327
+ if (typeof data.text === "string" && data.text) data.text = maskValue(data.text);
328
+ if (data.isChecked === true && liveContext(resolve(lookup, data.id), rules).masked) data.isChecked = false;
329
+ return true;
330
+ }
331
+ if (data.source !== MUTATION_SOURCE) return true;
332
+ for (const add of Array.isArray(data.adds) ? data.adds : []) {
333
+ if (!add || typeof add !== "object") continue;
334
+ const parent = resolve(lookup, add.parentId);
335
+ const context = liveContext(parent, rules);
336
+ if (tagOf(parent) === "textarea") context.editable = true;
337
+ scrubNode(add.node, rules, lookup, context);
338
+ }
339
+ for (const change of Array.isArray(data.attributes) ? data.attributes : []) {
340
+ if (!change || !change.attributes || typeof change.attributes !== "object") continue;
341
+ const node = resolve(lookup, change.id);
342
+ scrubAttributes(change.attributes, tagOf(node) || "input", liveContext(node, rules).masked);
343
+ }
344
+ for (const text of Array.isArray(data.texts) ? data.texts : []) {
345
+ if (!text || typeof text.value !== "string" || !text.value) continue;
346
+ const node = resolve(lookup, text.id);
347
+ const context = liveContext(node, rules);
348
+ const parentTag = tagOf(node?.parentElement ?? null);
349
+ if (context.editable || parentTag === "textarea") text.value = maskValue(text.value);
350
+ else if (context.masked && parentTag !== "style" && parentTag !== "script") text.value = maskString(text.value);
351
+ }
352
+ return true;
353
+ }
354
+
355
+ // src/recorder/uploads.ts
356
+ var UploadQueue = class {
357
+ constructor(url, key, now, events) {
358
+ this.url = url;
359
+ this.key = key;
360
+ this.now = now;
361
+ this.events = events;
362
+ /** Parked pieces, by seq. */
363
+ this.parked = [];
364
+ /** The parked piece sent alone to learn whether the engine is back. */
365
+ this.probe = null;
366
+ /** Failed probes in a row, and when parked pieces may go again. */
367
+ this.failures = 0;
368
+ this.retryAt = 0;
369
+ /** Pieces being gzipped: a beacon carries them raw if the page closes first. */
370
+ this.encoding = /* @__PURE__ */ new Set();
371
+ }
372
+ /** Parked pieces wait for the engine: new ones must park behind them to keep the order. */
373
+ holding() {
374
+ return this.parked.length > 0 || this.probe !== null;
375
+ }
376
+ /** Uploads are not going through right now. */
377
+ troubled() {
378
+ return this.holding() || this.failures > 0;
379
+ }
380
+ send(upload, mode) {
381
+ if (mode === "background" && this.holding()) {
382
+ this.park(upload, false);
383
+ return;
384
+ }
385
+ this.dispatch(upload, mode, 0);
386
+ }
387
+ /** The parked pieces: the oldest goes alone once the wait is over. Closing, each gets one last try. */
388
+ resendParked(mode) {
389
+ if (this.parked.length === 0) return;
390
+ if (mode === "closing") {
391
+ for (const upload2 of this.parked.splice(0)) this.dispatch(upload2, mode, RETRY_DELAYS_MS.length);
392
+ return;
393
+ }
394
+ if (this.probe || this.now() < this.retryAt) return;
395
+ const upload = this.parked.shift();
396
+ if (!upload) return;
397
+ this.probe = upload;
398
+ this.dispatch(upload, "background", RETRY_DELAYS_MS.length);
399
+ }
400
+ /** The page closes: pieces still being gzipped go out raw. */
401
+ beaconEncoding() {
402
+ for (const upload of this.encoding) {
403
+ if (!upload.done && upload.body.length <= KEEPALIVE_MAX_CHARS && beacon(this.url, this.key, upload.body)) {
404
+ this.accept(upload, null);
405
+ }
406
+ }
407
+ }
408
+ /** Drops every parked piece (a new session, or the end of the recording). */
409
+ clear() {
410
+ this.probe = null;
411
+ for (const upload of this.parked.splice(0)) this.lose(upload, "failed");
412
+ }
413
+ dispatch(upload, mode, attempt) {
414
+ if (mode === "closing") {
415
+ if (upload.body.length <= KEEPALIVE_MAX_CHARS && beacon(this.url, this.key, upload.body)) {
416
+ this.accept(upload, null);
417
+ return;
418
+ }
419
+ void this.attempt(upload, upload.body, attempt);
420
+ return;
421
+ }
422
+ if (mode === "hidden" && upload.body.length <= KEEPALIVE_MAX_CHARS) {
423
+ void this.attempt(upload, upload.body, attempt);
424
+ return;
425
+ }
426
+ void this.encodeAndSend(upload, attempt);
427
+ }
428
+ async encodeAndSend(upload, attempt) {
429
+ if (upload.encoded === void 0) {
430
+ this.encoding.add(upload);
431
+ upload.encoded = await encode(upload.body);
432
+ this.encoding.delete(upload);
433
+ }
434
+ if (upload.done) return;
435
+ await this.attempt(upload, upload.encoded, attempt);
436
+ }
437
+ async attempt(upload, payload, attempt) {
438
+ const outcome = await post(this.url, this.key, payload, this.now);
439
+ if (upload.done) return;
440
+ switch (outcome.kind) {
441
+ case "stored":
442
+ this.accept(upload, outcome.slowDown);
443
+ return;
444
+ case "rejected":
445
+ this.lose(upload, "rejected");
446
+ return;
447
+ case "refused":
448
+ case "not_recordable":
449
+ case "session_full":
450
+ this.halt(upload, outcome.kind, null);
451
+ return;
452
+ case "limit":
453
+ this.halt(upload, "limit", outcome.slowDown);
454
+ return;
455
+ case "retry":
456
+ this.retryLater(upload, payload, attempt, outcome.retryAfterMs, outcome.throttled);
457
+ }
458
+ }
459
+ /** Throttled, told when to come back, or behind pieces already waiting: park instead of hammering. */
460
+ retryLater(upload, payload, attempt, wait, throttled) {
461
+ const delay = RETRY_DELAYS_MS[attempt];
462
+ const behindOthers = this.parked.length > 0 || this.probe !== null && this.probe !== upload;
463
+ if (delay === void 0 || throttled || wait !== null || behindOthers) {
464
+ this.park(upload, true, wait);
465
+ return;
466
+ }
467
+ setTimeout(() => {
468
+ if (!upload.done) void this.attempt(upload, payload, attempt + 1);
469
+ }, delay);
470
+ }
471
+ accept(upload, slowDown) {
472
+ if (upload.done) return;
473
+ upload.done = true;
474
+ this.encoding.delete(upload);
475
+ this.failures = 0;
476
+ this.retryAt = 0;
477
+ const wasProbe = upload === this.probe;
478
+ if (wasProbe) this.probe = null;
479
+ safe(() => this.events.accepted(upload, slowDown));
480
+ if (!wasProbe) return;
481
+ for (const next of this.parked.splice(0)) this.dispatch(next, "background", 0);
482
+ }
483
+ lose(upload, reason) {
484
+ if (upload.done) return;
485
+ upload.done = true;
486
+ this.encoding.delete(upload);
487
+ if (upload === this.probe) this.probe = null;
488
+ safe(() => this.events.lost(upload, reason));
489
+ }
490
+ halt(upload, reason, slowDown) {
491
+ upload.done = true;
492
+ if (upload === this.probe) this.probe = null;
493
+ safe(() => this.events.halted(upload, reason, slowDown));
494
+ }
495
+ /**
496
+ * Keeps a piece for later, in seq order, under the memory cap. `failed`: it
497
+ * just failed against the engine, so the wait before the next probe grows
498
+ * (pieces failing together count once), never shorter than a `Retry-After`.
499
+ */
500
+ park(upload, failed, retryAfter = null) {
501
+ if (upload.done) return;
502
+ if (upload === this.probe) this.probe = null;
503
+ const index = this.parked.findIndex((item) => item.seq > upload.seq);
504
+ if (index < 0) this.parked.push(upload);
505
+ else this.parked.splice(index, 0, upload);
506
+ if (failed) {
507
+ const now = this.now();
508
+ if (now >= this.retryAt) {
509
+ this.failures++;
510
+ const wait = Math.min(PARK_MAX_MS, PARK_BASE_MS * 2 ** (this.failures - 1));
511
+ this.retryAt = now + wait * (0.5 + Math.random() / 2);
512
+ }
513
+ if (retryAfter !== null) this.retryAt = Math.max(this.retryAt, now + Math.min(PARK_MAX_MS, retryAfter));
514
+ }
515
+ let total = this.parked.reduce((sum, item) => sum + item.body.length, 0);
516
+ while (total > MAX_BUFFER_CHARS && this.parked.length > 0) {
517
+ const oldest = this.parked.shift();
518
+ if (!oldest) break;
519
+ total -= oldest.body.length;
520
+ this.lose(oldest, "overflow");
521
+ }
522
+ }
523
+ };
524
+
525
+ // src/recorder/replay.ts
526
+ var FULL_SNAPSHOT2 = 2;
527
+ var BEACON_BUDGET_CHARS = KEEPALIVE_MAX_CHARS - 2e3;
528
+ function recordOptionsFor(emit, rules, recording) {
529
+ return {
530
+ emit,
531
+ ...serializerOptions(rules),
532
+ slimDOMOptions: "all",
533
+ collectFonts: false,
534
+ sampling: { mousemove: 50, mouseInteraction: true, scroll: 150, input: "last" },
535
+ checkoutEveryNms: recording ? RECORD_CHECKOUT_MS : BUFFER_MS,
536
+ // Frames are left out: no frame of another origin is asked for its events. A
537
+ // same-origin frame is still walked by rrweb, and scrubEvent drops it.
538
+ recordCrossOriginIframes: false,
539
+ // rrweb's own errors stay in rrweb.
540
+ errorHandler: () => true
541
+ };
542
+ }
543
+ var ReplayRecorder = class {
544
+ constructor(options) {
545
+ this.options = options;
546
+ this.decision = null;
547
+ this.rules = null;
548
+ this.rrweb = null;
549
+ this.stopRrweb = null;
550
+ this.active = false;
551
+ this.loading = false;
552
+ /** This session's recording is over: 720 pieces, an event too big, a refused key, a limit. */
553
+ this.finished = false;
554
+ this.timer = null;
555
+ /** record mode: the piece being filled. */
556
+ this.pending = null;
557
+ /** Pieces ready to go. */
558
+ this.queue = [];
559
+ /**
560
+ * Resuming after a hole. `lostSeq`: the newest piece lost for good;
561
+ * `sentFullSeq` and `storedFullSeq`: the newest piece holding a full
562
+ * snapshot that went out, and that the engine accepted (-1: none). A fresh
563
+ * full snapshot is `owed` while none after `lostSeq` is stored; `tries`
564
+ * snapshots were taken for it, the next not before `resyncAt`.
565
+ */
566
+ this.lostSeq = -1;
567
+ this.sentFullSeq = -1;
568
+ this.storedFullSeq = -1;
569
+ this.owed = false;
570
+ this.tries = 0;
571
+ this.resyncAt = 0;
572
+ this.resyncTimer = null;
573
+ /** A snapshot was asked of rrweb and has not landed yet. */
574
+ this.resyncing = false;
575
+ /** buffer mode: the previous window and the current one. */
576
+ this.previous = [];
577
+ this.previousChars = 0;
578
+ this.current = [];
579
+ this.currentChars = 0;
580
+ this.inCheckout = false;
581
+ this.warnedKey = false;
582
+ /** Set while a full snapshot is taken for a page snapshot: the serialized page lands here. */
583
+ this.capture = null;
584
+ this.lookup = (id) => safe(() => this.rrweb?.record.mirror?.getNode(id) ?? null) ?? null;
585
+ const { host } = options;
586
+ this.uploads = new UploadQueue(`${host.endpoint}/v1/ingest/replay`, host.project, () => host.now(), {
587
+ accepted: (upload, slowDown) => this.accepted(upload, slowDown),
588
+ lost: (upload, reason) => this.gap(upload.seq, reason, upload.sid),
589
+ halted: (upload, reason, slowDown) => this.halted(upload, reason, slowDown)
590
+ });
591
+ }
592
+ mode() {
593
+ return this.decision?.mode ?? "off";
594
+ }
595
+ isRecording() {
596
+ return this.stopRrweb !== null;
597
+ }
598
+ // ---------------------------------------------------------------- lifecycle
599
+ /** Starts, or resumes, recording under `decision` with `rules`. */
600
+ start(decision, rules) {
601
+ try {
602
+ if (this.decision !== decision) {
603
+ this.finished = false;
604
+ this.queue = [];
605
+ this.pending = null;
606
+ this.uploads.clear();
607
+ this.resetResync();
608
+ }
609
+ this.decision = decision;
610
+ this.rules = rules;
611
+ if (decision.mode === "off" || this.active || this.finished) return;
612
+ if (decision.seq >= MAX_CHUNKS_PER_SESSION) return;
613
+ this.active = true;
614
+ (this.options.idle ?? whenIdle)(() => void this.load());
615
+ } catch {
616
+ }
617
+ }
618
+ /** Recording stops: the pending piece goes out, buffers are dropped. */
619
+ stop() {
620
+ try {
621
+ this.active = false;
622
+ const stop = this.stopRrweb;
623
+ this.stopRrweb = null;
624
+ if (stop) safe(stop);
625
+ this.stopTimer();
626
+ if (this.mode() === "record") this.uploadPending("background");
627
+ this.clearBuffers();
628
+ } catch {
629
+ }
630
+ }
631
+ /** An error, a rage click or a dead click: buffer becomes record, and the buffer the first pieces. */
632
+ onTrouble() {
633
+ try {
634
+ const decision = this.decision;
635
+ if (!decision || decision.mode !== "buffer" || this.finished) return;
636
+ decision.mode = "record";
637
+ writeDecision(decision);
638
+ const items = this.previous.concat(this.current);
639
+ this.clearBuffers();
640
+ for (const chunk of this.split(items, CHUNK_CHARS)) this.queue.push(chunk);
641
+ this.drain("background");
642
+ if (this.stopRrweb) {
643
+ const stop = this.stopRrweb;
644
+ this.stopRrweb = null;
645
+ safe(stop);
646
+ this.begin();
647
+ }
648
+ } catch {
649
+ }
650
+ }
651
+ /** The project reached its replays limit: the next piece is a `limit` gap and the session records no more. */
652
+ limit() {
653
+ const decision = this.decision;
654
+ if (!decision || this.finished) return;
655
+ if (decision.seq < MAX_CHUNKS_PER_SESSION) this.gap(decision.seq, "limit", decision.sid);
656
+ decision.mode = "off";
657
+ writeDecision(decision);
658
+ this.pending = null;
659
+ this.queue = [];
660
+ this.finish();
661
+ }
662
+ /**
663
+ * The tab is hidden (`hidden`): the page lives on, so the pending piece goes
664
+ * with keepalive. The page closes (`closing`): no async work survives, so the
665
+ * pending piece goes in beacon-sized pieces, and pieces being gzipped go raw.
666
+ */
667
+ flush(mode) {
668
+ try {
669
+ if (this.mode() !== "record") return;
670
+ if (mode === "closing") this.uploads.beaconEncoding();
671
+ this.uploadPending(mode);
672
+ } catch {
673
+ }
674
+ }
675
+ /**
676
+ * The page serialized with `rules` and scrubbed, for a page snapshot. While
677
+ * rrweb records, it takes one more full snapshot (also a starting point for
678
+ * the player); otherwise rrweb records just long enough to take one.
679
+ */
680
+ async fullSnapshot(rules) {
681
+ try {
682
+ if (this.stopRrweb && this.rrweb) {
683
+ const capture = { node: null };
684
+ this.capture = capture;
685
+ try {
686
+ this.rrweb.record.takeFullSnapshot?.(false);
687
+ } finally {
688
+ this.capture = null;
689
+ }
690
+ return capture.node;
691
+ }
692
+ this.rrweb ??= await this.options.loadRrweb();
693
+ if (this.stopRrweb) return this.fullSnapshot(rules);
694
+ return this.oneFullSnapshot(this.rrweb, rules);
695
+ } catch {
696
+ return null;
697
+ }
698
+ }
699
+ /** rrweb records for one full snapshot, synchronously, and stops. */
700
+ oneFullSnapshot(rrweb, rules) {
701
+ let node = null;
702
+ const lookup = (id) => safe(() => rrweb.record.mirror?.getNode(id) ?? null) ?? null;
703
+ const stop = rrweb.record({
704
+ ...recordOptionsFor(() => void 0, rules, false),
705
+ checkoutEveryNms: void 0,
706
+ emit: (event) => {
707
+ if (event.type !== FULL_SNAPSHOT2 || node !== null) return;
708
+ scrubEvent(event, rules, lookup);
709
+ node = event.data.node ?? null;
710
+ }
711
+ });
712
+ if (stop) safe(stop);
713
+ return node;
714
+ }
715
+ // ---------------------------------------------------------------- recording
716
+ async load() {
717
+ if (!this.active || this.stopRrweb || this.loading) return;
718
+ this.loading = true;
719
+ try {
720
+ this.rrweb ??= await this.options.loadRrweb();
721
+ } catch {
722
+ this.active = false;
723
+ return;
724
+ } finally {
725
+ this.loading = false;
726
+ }
727
+ if (this.active && !this.stopRrweb) this.begin();
728
+ }
729
+ begin() {
730
+ const rrweb = this.rrweb;
731
+ const rules = this.rules;
732
+ if (!rrweb || !rules) return;
733
+ try {
734
+ const recording = this.mode() === "record";
735
+ this.stopRrweb = rrweb.record(recordOptionsFor((event, isCheckout) => this.onEvent(event, isCheckout), rules, recording)) ?? null;
736
+ } catch {
737
+ this.stopRrweb = null;
738
+ return;
739
+ }
740
+ if (this.mode() === "record") this.startTimer();
741
+ }
742
+ onEvent(event, isCheckout) {
743
+ try {
744
+ if (!this.active || !this.decision || !this.rules || this.finished) return;
745
+ if (!scrubEvent(event, this.rules, this.lookup)) return;
746
+ const json = JSON.stringify(event);
747
+ if (!json) return;
748
+ if (json.length > MAX_EVENT_CHARS) {
749
+ this.finish();
750
+ return;
751
+ }
752
+ const item = {
753
+ json,
754
+ ts: typeof event.timestamp === "number" ? event.timestamp : this.options.host.now(),
755
+ full: event.type === FULL_SNAPSHOT2
756
+ };
757
+ if (item.full && this.capture) this.capture.node = event.data.node ?? null;
758
+ if (this.decision.mode === "record") this.record(item);
759
+ else this.buffer(item, isCheckout === true);
760
+ } catch {
761
+ }
762
+ }
763
+ record(item) {
764
+ this.pending ??= this.open();
765
+ this.pending.items.push(item);
766
+ this.pending.chars += item.json.length;
767
+ if (this.pending.chars >= CHUNK_CHARS) this.uploadPending("background");
768
+ }
769
+ /**
770
+ * A checkout arrives as Meta + FullSnapshot flagged `isCheckout`: at its
771
+ * Meta the current window becomes the previous one. Both stay under the
772
+ * memory cap; a current window past it alone is dropped and rrweb asked
773
+ * for a fresh full snapshot.
774
+ */
775
+ buffer(item, isCheckout) {
776
+ if (isCheckout && !this.inCheckout) {
777
+ this.previous = this.current;
778
+ this.previousChars = this.currentChars;
779
+ this.current = [];
780
+ this.currentChars = 0;
781
+ }
782
+ this.inCheckout = isCheckout;
783
+ this.current.push(item);
784
+ this.currentChars += item.json.length;
785
+ if (this.previousChars + this.currentChars > MAX_BUFFER_CHARS) {
786
+ this.previous = [];
787
+ this.previousChars = 0;
788
+ }
789
+ if (this.currentChars > MAX_BUFFER_CHARS) {
790
+ this.current = [];
791
+ this.currentChars = 0;
792
+ this.inCheckout = false;
793
+ this.takeFullSnapshot();
794
+ }
795
+ }
796
+ clearBuffers() {
797
+ this.previous = [];
798
+ this.previousChars = 0;
799
+ this.current = [];
800
+ this.currentChars = 0;
801
+ this.inCheckout = false;
802
+ }
803
+ open() {
804
+ const page = safe(() => this.options.host.page()) ?? null;
805
+ return {
806
+ items: [],
807
+ chars: 0,
808
+ route: page?.route ?? "",
809
+ url: page?.url ?? "",
810
+ vw: safe(() => window.innerWidth) || 0,
811
+ vh: safe(() => window.innerHeight) || 0
812
+ };
813
+ }
814
+ /** Packs items into pieces of at most `budget` characters (one big event gets its own piece). */
815
+ split(items, budget, template) {
816
+ const chunks = [];
817
+ let current = null;
818
+ for (const item of items) {
819
+ if (current === null || current.items.length > 0 && current.chars + item.json.length > budget) {
820
+ current = template ? { ...template, items: [], chars: 0 } : this.open();
821
+ chunks.push(current);
822
+ }
823
+ current.items.push(item);
824
+ current.chars += item.json.length;
825
+ }
826
+ return chunks;
827
+ }
828
+ startTimer() {
829
+ if (this.timer) return;
830
+ this.timer = setInterval(() => safe(() => this.uploadPending("background")), CHUNK_INTERVAL_MS);
831
+ }
832
+ stopTimer() {
833
+ if (this.timer) clearInterval(this.timer);
834
+ this.timer = null;
835
+ }
836
+ finish() {
837
+ if (this.finished) return;
838
+ this.finished = true;
839
+ this.queue = [];
840
+ this.pending = null;
841
+ this.uploads.clear();
842
+ this.resetResync();
843
+ this.stop();
844
+ }
845
+ takeFullSnapshot() {
846
+ setTimeout(() => safe(() => this.rrweb?.record.takeFullSnapshot?.(false)), 0);
847
+ }
848
+ // ------------------------------------------------------------------ upload
849
+ uploadPending(mode) {
850
+ const chunk = this.pending;
851
+ this.pending = null;
852
+ if (chunk && chunk.items.length > 0) {
853
+ const pieces = mode === "closing" && chunk.chars > BEACON_BUDGET_CHARS ? this.split(chunk.items, BEACON_BUDGET_CHARS, chunk) : [chunk];
854
+ this.queue.push(...pieces);
855
+ }
856
+ this.drain(mode);
857
+ }
858
+ /**
859
+ * Sends the queued pieces in order. The sequence is shared across tabs
860
+ * through storage; while parked pieces wait for the engine, new pieces get
861
+ * their seq and park behind them.
862
+ */
863
+ drain(mode) {
864
+ const decision = this.decision;
865
+ if (!decision || this.finished) {
866
+ this.queue = [];
867
+ return;
868
+ }
869
+ this.uploads.resendParked(mode);
870
+ const stored = readDecision(decision.sid);
871
+ if (stored && stored.seq > decision.seq) decision.seq = stored.seq;
872
+ while (this.queue.length > 0) {
873
+ if (decision.seq >= MAX_CHUNKS_PER_SESSION) break;
874
+ const chunk = this.queue.shift();
875
+ if (!chunk) break;
876
+ const seq = decision.seq++;
877
+ writeDecision(decision);
878
+ const upload = this.upload(decision.sid, seq, chunk);
879
+ if (upload.full) this.sentFullSeq = Math.max(this.sentFullSeq, seq);
880
+ this.uploads.send(upload, mode);
881
+ }
882
+ if (decision.seq >= MAX_CHUNKS_PER_SESSION) this.finish();
883
+ }
884
+ /** The ReplayChunk body of spec/events.schema.json, with the events serialized once. */
885
+ upload(sid, seq, chunk) {
886
+ const first = chunk.items[0];
887
+ const last = chunk.items[chunk.items.length - 1];
888
+ const full = chunk.items.some((item) => item.full);
889
+ const head = JSON.stringify({
890
+ sid,
891
+ seq,
892
+ ts_start: first?.ts ?? 0,
893
+ ts_end: last?.ts ?? 0,
894
+ route: chunk.route,
895
+ url: chunk.url,
896
+ vw: chunk.vw,
897
+ vh: chunk.vh,
898
+ full,
899
+ mask: this.rules?.policy ?? 1
900
+ });
901
+ const body = `${head.slice(0, -1)},"events":[${chunk.items.map((item) => item.json).join(",")}]}`;
902
+ return { sid, seq, body, route: chunk.route, full, done: false };
903
+ }
904
+ accepted(upload, slowDown) {
905
+ const { host } = this.options;
906
+ safe(() => host.onChunk({ sid: upload.sid, seq: upload.seq, bytes: upload.body.length, mask: this.rules?.policy ?? 1, full: upload.full }));
907
+ if (slowDown) safe(() => host.onSlowDown(slowDown));
908
+ if (slowDown?.replay === false) {
909
+ this.options.onLimit(slowDown);
910
+ return;
911
+ }
912
+ if (upload.sid !== this.decision?.sid) return;
913
+ if (upload.full) {
914
+ this.storedFullSeq = Math.max(this.storedFullSeq, upload.seq);
915
+ if (upload.seq > this.lostSeq) this.resetResync();
916
+ }
917
+ this.maybeSnapshot();
918
+ }
919
+ halted(upload, reason, slowDown) {
920
+ const { host } = this.options;
921
+ switch (reason) {
922
+ case "limit":
923
+ if (slowDown) safe(() => host.onSlowDown(slowDown));
924
+ this.options.onLimit(slowDown);
925
+ return;
926
+ case "not_recordable":
927
+ this.gap(upload.seq, "rejected", upload.sid);
928
+ this.options.onRouteRefused(upload.route);
929
+ return;
930
+ case "refused":
931
+ this.gap(upload.seq, "rejected", upload.sid);
932
+ if (!this.warnedKey) {
933
+ this.warnedKey = true;
934
+ safe(() => console.warn("[sypnia] replay off: the engine refused the ingest key"));
935
+ }
936
+ this.finish();
937
+ return;
938
+ case "session_full":
939
+ this.finish();
940
+ }
941
+ }
942
+ /** Events recorded under `sid` from `seq` on are missing: report it and owe a fresh starting point. */
943
+ gap(seq, reason, sid) {
944
+ safe(() => this.options.host.onGap({ sid, seq, reason, mask: this.rules?.policy ?? 1 }));
945
+ if (reason === "limit" || this.finished || this.decision?.sid !== sid || this.mode() !== "record") return;
946
+ if (this.storedFullSeq > seq) return;
947
+ this.lostSeq = Math.max(this.lostSeq, seq);
948
+ this.owed = true;
949
+ if (this.fullOnItsWay()) return;
950
+ const delay = RESYNC_DELAYS_MS[this.tries];
951
+ if (delay === void 0 || this.resyncTimer) return;
952
+ this.resyncAt = this.options.host.now() + delay;
953
+ this.resyncTimer = setTimeout(() => {
954
+ this.resyncTimer = null;
955
+ safe(() => this.maybeSnapshot());
956
+ }, delay);
957
+ }
958
+ /** A full snapshot taken after the newest hole is still to be sent, or sent and not answered yet. */
959
+ fullOnItsWay() {
960
+ if (this.resyncing || this.sentFullSeq > this.lostSeq) return true;
961
+ const holds = (chunk) => !!chunk && chunk.items.some((item) => item.full);
962
+ return holds(this.pending) || this.queue.some(holds);
963
+ }
964
+ resetResync() {
965
+ if (this.resyncTimer) clearTimeout(this.resyncTimer);
966
+ this.resyncTimer = null;
967
+ this.owed = false;
968
+ this.resyncing = false;
969
+ this.tries = 0;
970
+ this.resyncAt = 0;
971
+ this.lostSeq = -1;
972
+ this.sentFullSeq = -1;
973
+ this.storedFullSeq = -1;
974
+ }
975
+ /**
976
+ * The full snapshot a hole is owed. Only while uploads go through: waiting
977
+ * for the engine, a snapshot (hundreds of kB) would only fill the queue, so
978
+ * the next accepted piece calls this again.
979
+ */
980
+ maybeSnapshot() {
981
+ if (!this.owed || this.finished || !this.stopRrweb || this.mode() !== "record" || this.uploads.troubled()) return;
982
+ if (this.tries >= RESYNC_DELAYS_MS.length || this.fullOnItsWay()) return;
983
+ if (this.resyncTimer || this.options.host.now() < this.resyncAt) return;
984
+ this.tries++;
985
+ this.resyncing = true;
986
+ setTimeout(
987
+ () => safe(() => {
988
+ this.resyncing = false;
989
+ if (!this.stopRrweb || this.finished || this.mode() !== "record") return;
990
+ this.uploadPending("background");
991
+ this.rrweb?.record.takeFullSnapshot?.(false);
992
+ }),
993
+ 0
994
+ );
995
+ }
996
+ };
997
+
998
+ // src/recorder/snapshot.ts
999
+ var PageSnapshotter = class {
1000
+ constructor(options) {
1001
+ this.options = options;
1002
+ this.decision = null;
1003
+ this.rules = null;
1004
+ this.active = false;
1005
+ this.timer = null;
1006
+ this.taking = false;
1007
+ this.url = `${options.host.endpoint}/v1/ingest/snapshot`;
1008
+ }
1009
+ start(decision, rules) {
1010
+ this.decision = decision;
1011
+ this.rules = rules;
1012
+ this.active = true;
1013
+ }
1014
+ stop() {
1015
+ this.active = false;
1016
+ this.clearTimer();
1017
+ }
1018
+ /** A page was shown: the previous page's pending snapshot is cancelled. */
1019
+ schedule(page) {
1020
+ try {
1021
+ this.clearTimer();
1022
+ if (!this.active || !this.eligible(page.route)) return;
1023
+ this.timer = setTimeout(() => this.whenQuiet(page, 0), SNAPSHOT_DELAY_MS);
1024
+ } catch {
1025
+ }
1026
+ }
1027
+ eligible(route) {
1028
+ const decision = this.decision;
1029
+ if (!decision || !decision.snapshots || !this.options.host.snapshots) return false;
1030
+ return decision.snaps.length < SNAPSHOTS_PER_SESSION && !decision.snaps.includes(route);
1031
+ }
1032
+ clearTimer() {
1033
+ if (this.timer) clearTimeout(this.timer);
1034
+ this.timer = null;
1035
+ }
1036
+ whenQuiet(page, waited) {
1037
+ this.timer = null;
1038
+ if (!this.active) return;
1039
+ const { host } = this.options;
1040
+ const stillFor = host.now() - (safe(() => host.lastMutationAt()) ?? -1);
1041
+ const pending = safe(() => host.pendingRequests()) ?? 0;
1042
+ if ((stillFor < QUIET_MS || pending > 0) && waited < MAX_QUIET_WAIT_MS) {
1043
+ this.timer = setTimeout(() => this.whenQuiet(page, waited + QUIET_MS), QUIET_MS);
1044
+ return;
1045
+ }
1046
+ void this.take(page);
1047
+ }
1048
+ onPage(page) {
1049
+ return safe(() => this.options.host.page())?.route === page.route;
1050
+ }
1051
+ report(sid, bytes, skipped) {
1052
+ const mask = this.rules?.policy ?? 1;
1053
+ safe(() => this.options.host.onSnapshot(skipped ? { sid, bytes, mask, skipped } : { sid, bytes, mask }));
1054
+ }
1055
+ async take(page) {
1056
+ if (this.taking) return;
1057
+ this.taking = true;
1058
+ try {
1059
+ const decision = this.decision;
1060
+ const rules = this.rules;
1061
+ if (!decision || !rules || !this.active) return;
1062
+ for (const route of readDecision(decision.sid)?.snaps ?? []) if (!decision.snaps.includes(route)) decision.snaps.push(route);
1063
+ if (!this.eligible(page.route) || !this.onPage(page)) return;
1064
+ decision.snaps.push(page.route);
1065
+ writeDecision(decision);
1066
+ const tree = await this.options.serialize(rules);
1067
+ if (!tree || !this.active || !this.onPage(page)) return;
1068
+ const json = JSON.stringify(tree);
1069
+ if (json.length > SNAPSHOT_CHARS) {
1070
+ this.report(decision.sid, json.length, "too_big");
1071
+ return;
1072
+ }
1073
+ await this.send(page, decision.sid, rules, json);
1074
+ } catch {
1075
+ } finally {
1076
+ this.taking = false;
1077
+ }
1078
+ }
1079
+ async send(page, sid, rules, json) {
1080
+ const { host } = this.options;
1081
+ const vw = safe(() => window.innerWidth) || 0;
1082
+ const head = JSON.stringify({
1083
+ sid,
1084
+ route: page.route,
1085
+ url: page.url,
1086
+ dev: deviceClassOf(vw),
1087
+ vw,
1088
+ vh: safe(() => window.innerHeight) || 0,
1089
+ ph: safe(() => document.documentElement.scrollHeight) || 0,
1090
+ ts: host.now(),
1091
+ mask: rules.policy,
1092
+ // Not in the PageSnapshot schema, but the engine files a snapshot under this environment.
1093
+ ...host.environment ? { env: host.environment } : {}
1094
+ });
1095
+ const body = `${head.slice(0, -1)},"snapshot":${json}}`;
1096
+ const outcome = await post(this.url, host.project, await encode(body), () => host.now());
1097
+ if (outcome.kind !== "stored" && outcome.kind !== "limit") {
1098
+ this.report(sid, json.length, "upload_failed");
1099
+ return;
1100
+ }
1101
+ const slowDown = outcome.slowDown;
1102
+ this.report(sid, json.length, outcome.kind === "limit" ? "limit" : void 0);
1103
+ if (slowDown) safe(() => host.onSlowDown(slowDown));
1104
+ if (outcome.kind === "limit" || slowDown?.replay === false) this.options.onLimit();
1105
+ }
1106
+ };
1107
+
1108
+ // src/recorder/index.ts
1109
+ var loadRealRrweb = () => Promise.resolve({ record });
1110
+ var SessionRecorder = class {
1111
+ constructor(host, seams) {
1112
+ this.host = host;
1113
+ this.decision = null;
1114
+ this.rules = null;
1115
+ /** The current page may not be recorded. */
1116
+ this.blocked = false;
1117
+ /** Routes the engine answered `not_recordable` for. */
1118
+ this.refused = /* @__PURE__ */ new Set();
1119
+ this.replay = new ReplayRecorder({
1120
+ host,
1121
+ loadRrweb: seams.loadRrweb ?? loadRealRrweb,
1122
+ idle: seams.idle,
1123
+ onRouteRefused: (route) => this.refuseRoute(route),
1124
+ onLimit: () => this.onReplayLimit()
1125
+ });
1126
+ this.snapshots = new PageSnapshotter({
1127
+ host,
1128
+ serialize: (rules) => this.replay.fullSnapshot(rules),
1129
+ onLimit: () => this.onReplayLimit()
1130
+ });
1131
+ }
1132
+ start(decision) {
1133
+ try {
1134
+ if (decision.sid === this.decision?.sid) return;
1135
+ this.stop();
1136
+ this.decision = decision;
1137
+ this.rules = maskRules({
1138
+ maskAllText: this.host.maskAllText || decision.maskAllText,
1139
+ maskSelector: this.host.maskSelector,
1140
+ blockSelector: this.host.blockSelector
1141
+ });
1142
+ const page = this.host.page();
1143
+ this.blocked = page !== null && this.isBlocked(page);
1144
+ if (!this.blocked) this.resume(page);
1145
+ } catch {
1146
+ }
1147
+ }
1148
+ stop() {
1149
+ safe(() => this.replay.stop());
1150
+ safe(() => this.snapshots.stop());
1151
+ }
1152
+ onTrouble() {
1153
+ if (!this.blocked) this.replay.onTrouble();
1154
+ }
1155
+ onPage(page) {
1156
+ try {
1157
+ const blocked = this.isBlocked(page);
1158
+ if (blocked !== this.blocked) {
1159
+ this.blocked = blocked;
1160
+ if (blocked) this.stop();
1161
+ else this.resume(null);
1162
+ }
1163
+ if (!blocked) this.snapshots.schedule(page);
1164
+ } catch {
1165
+ }
1166
+ }
1167
+ onReplayLimit() {
1168
+ safe(() => this.replay.limit());
1169
+ safe(() => this.snapshots.stop());
1170
+ }
1171
+ flush(mode) {
1172
+ this.replay.flush(mode === "beacon" ? "closing" : "hidden");
1173
+ }
1174
+ resume(page) {
1175
+ const { decision, rules } = this;
1176
+ if (!decision || !rules) return;
1177
+ if (this.host.replay) this.replay.start(decision, rules);
1178
+ this.snapshots.start(decision, rules);
1179
+ if (page) this.snapshots.schedule(page);
1180
+ }
1181
+ /** `replay.blockedRoutes` in `init`, the project's `replay.blocked_routes`, and routes the engine refused. */
1182
+ isBlocked(page) {
1183
+ const patterns = [...this.host.blockedRoutes, ...this.decision?.blockedRoutes ?? []];
1184
+ const allow = this.host.allowRoutes;
1185
+ if (allow.length > 0 && !matchesRoute(page.url, allow) && !matchesRoute(page.route, allow)) return true;
1186
+ return this.refused.has(page.route) || matchesRoute(page.route, patterns) || matchesRoute(page.url, patterns);
1187
+ }
1188
+ refuseRoute(route) {
1189
+ this.refused.add(route);
1190
+ const page = safe(() => this.host.page());
1191
+ if (page) this.onPage(page);
1192
+ }
1193
+ };
1194
+ function createRecorderWith(host, seams) {
1195
+ return new SessionRecorder(host, seams);
1196
+ }
1197
+ var createRecorder = (host) => createRecorderWith(host, {});
1198
+
1199
+ export { createRecorder, createRecorderWith };