@full-self-browsing/phantom-stream 0.1.0 → 0.3.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 (64) hide show
  1. package/README.md +48 -2
  2. package/dist/types/adapters/extension.d.ts.map +1 -1
  3. package/dist/types/adapters/playwright.d.ts.map +1 -1
  4. package/dist/types/capture/index.d.ts +150 -0
  5. package/dist/types/capture/index.d.ts.map +1 -1
  6. package/dist/types/index.d.ts +2 -0
  7. package/dist/types/player/index.d.ts +136 -0
  8. package/dist/types/player/index.d.ts.map +1 -0
  9. package/dist/types/protocol/constants.d.ts +22 -0
  10. package/dist/types/protocol/constants.d.ts.map +1 -1
  11. package/dist/types/protocol/index.d.ts +1 -0
  12. package/dist/types/protocol/media-reconcile.d.ts +53 -0
  13. package/dist/types/protocol/media-reconcile.d.ts.map +1 -0
  14. package/dist/types/protocol/messages.d.ts +326 -4
  15. package/dist/types/protocol/messages.d.ts.map +1 -1
  16. package/dist/types/recorder/index.d.ts +207 -0
  17. package/dist/types/recorder/index.d.ts.map +1 -0
  18. package/dist/types/renderer/asset-policy.d.ts +72 -0
  19. package/dist/types/renderer/asset-policy.d.ts.map +1 -0
  20. package/dist/types/renderer/diff.d.ts.map +1 -1
  21. package/dist/types/renderer/index.d.ts +61 -8
  22. package/dist/types/renderer/index.d.ts.map +1 -1
  23. package/dist/types/renderer/media-player.d.ts +114 -0
  24. package/dist/types/renderer/media-player.d.ts.map +1 -0
  25. package/dist/types/renderer/overlays.d.ts +12 -0
  26. package/dist/types/renderer/overlays.d.ts.map +1 -1
  27. package/dist/types/renderer/parser-safe.d.ts +26 -0
  28. package/dist/types/renderer/parser-safe.d.ts.map +1 -0
  29. package/dist/types/renderer/sanitize.d.ts +22 -0
  30. package/dist/types/renderer/sanitize.d.ts.map +1 -1
  31. package/dist/types/renderer/snapshot.d.ts +38 -0
  32. package/dist/types/renderer/snapshot.d.ts.map +1 -1
  33. package/dist/types/transport/websocket.d.ts.map +1 -1
  34. package/docs/ARCHITECTURE.md +83 -4
  35. package/docs/QUICKSTARTS.md +64 -0
  36. package/docs/SECURITY.md +279 -2
  37. package/docs/paper/OUTLINE.md +24 -91
  38. package/examples/bookmarklet-demo/viewer.html +12 -3
  39. package/examples/extension-mv3/viewer.html +10 -3
  40. package/package.json +25 -1
  41. package/src/adapters/extension.js +202 -7
  42. package/src/adapters/playwright-inject.js +645 -28
  43. package/src/adapters/playwright.js +176 -2
  44. package/src/capture/README.md +96 -1
  45. package/src/capture/index.js +1672 -40
  46. package/src/index.js +2 -0
  47. package/src/player/README.md +175 -0
  48. package/src/player/index.js +627 -0
  49. package/src/protocol/constants.js +24 -0
  50. package/src/protocol/index.js +1 -0
  51. package/src/protocol/media-reconcile.js +188 -0
  52. package/src/protocol/messages.js +195 -4
  53. package/src/recorder/README.md +225 -0
  54. package/src/recorder/index.js +487 -0
  55. package/src/renderer/README.md +111 -8
  56. package/src/renderer/asset-policy.js +172 -0
  57. package/src/renderer/diff.js +158 -15
  58. package/src/renderer/index.js +978 -21
  59. package/src/renderer/media-player.js +367 -0
  60. package/src/renderer/overlays.js +324 -0
  61. package/src/renderer/parser-safe.js +111 -0
  62. package/src/renderer/sanitize.js +25 -3
  63. package/src/renderer/snapshot.js +534 -3
  64. package/src/transport/websocket.js +36 -0
@@ -42,20 +42,118 @@
42
42
  import {
43
43
  RELAY_PER_MESSAGE_LIMIT_BYTES,
44
44
  SNAPSHOT_BUDGET_BYTES,
45
+ SNAPSHOT_BUDGET_FRACTION,
45
46
  TRUNCATION_VIEWPORT_MULTIPLIER,
46
47
  SCROLL_THROTTLE_MS,
48
+ MEDIA_SYNC_THROTTLE_MS,
47
49
  OVERLAY_THROTTLE_MS,
48
50
  MUTATION_STALE_THRESHOLD_MS,
49
51
  WATCHDOG_TICK_MS,
50
52
  INLINE_STYLE_MAX_BYTES,
53
+ ASSET_DATA_URI_MAX_BYTES,
51
54
  } from '../protocol/constants.js';
52
- import { STREAM, CONTROL, DIFF_OP, createStreamSessionId } from '../protocol/messages.js';
55
+ import {
56
+ STREAM,
57
+ CONTROL,
58
+ DIFF_OP,
59
+ BODY_NID,
60
+ PARSER_SAFE_TAG,
61
+ PARSER_SAFE_TAG_ATTR,
62
+ createStreamSessionId,
63
+ } from '../protocol/messages.js';
53
64
 
54
65
  // RELAY_PER_MESSAGE_LIMIT_BYTES is the relay's hard per-message cap;
55
66
  // SNAPSHOT_BUDGET_BYTES is the 80% truncation budget derived from it
56
67
  // (replaces the reference's inline Math.floor(limit * 0.8) computation).
57
68
  // Both are imported, never redefined, so capture and relay stay in sync.
69
+ // They are the DEFAULTS: createCapture's messageLimitBytes and
70
+ // snapshotBudgetBytes options override them per instance for local recorders
71
+ // that never pass through a relay (quick task 261202-jwf), and every budget
72
+ // pass compares against those instance values.
58
73
  void RELAY_PER_MESSAGE_LIMIT_BYTES;
74
+ void SNAPSHOT_BUDGET_BYTES;
75
+
76
+ // Cadence of the CSSOM full style re-collect safety net, in ms (quick task
77
+ // 261202-jwf, D 1.2). The per-flush reconcile skips a scope whose cheap
78
+ // signature is unchanged; at most once per this interval it re-collects every
79
+ // known scope anyway, which catches a rule edit that keeps cssRules.length.
80
+ // Fingerprints still dedupe the result, so an unchanged sheet sends nothing.
81
+ var STYLE_FULL_RECONCILE_MS = 2000; // 2 s
82
+
83
+ // Parser-safe serialization tag sets (quick task 261202-jwf, D 3.2). They
84
+ // mirror the HTML tree-construction rules that rewrite script-built nesting
85
+ // when serialized markup is parsed again; neutralizeParserHostileNesting reads
86
+ // them. Only HTML-namespace elements are renamed or count as matches.
87
+ var PARSER_SAFE_HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
88
+ var PARSER_SAFE_SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
89
+ var PARSER_SAFE_MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
90
+ // (a) an element of one of these tags inside a same-tag ancestor
91
+ var PARSER_SAFE_SAME_TAG = { button: true, a: true, form: true, nobr: true };
92
+ // (b) a start tag that closes an open <p>
93
+ var PARSER_SAFE_BLOCK_CLOSERS = {
94
+ address: true, article: true, aside: true, blockquote: true, center: true,
95
+ details: true, dialog: true, dir: true, div: true, dl: true, fieldset: true,
96
+ figcaption: true, figure: true, footer: true, header: true, hgroup: true,
97
+ main: true, menu: true, nav: true, ol: true, p: true, search: true,
98
+ section: true, summary: true, ul: true, h1: true, h2: true, h3: true,
99
+ h4: true, h5: true, h6: true, pre: true, listing: true, form: true,
100
+ plaintext: true, xmp: true, table: true, hr: true, li: true, dd: true, dt: true
101
+ };
102
+ // (c) headings
103
+ var PARSER_SAFE_HEADINGS = { h1: true, h2: true, h3: true, h4: true, h5: true, h6: true };
104
+ // (d) the HTML "special" category, which stops the li/dd/dt scope walk
105
+ var PARSER_SAFE_SPECIAL = {
106
+ address: true, applet: true, area: true, article: true, aside: true,
107
+ base: true, basefont: true, bgsound: true, blockquote: true, body: true,
108
+ br: true, button: true, caption: true, center: true, col: true,
109
+ colgroup: true, dd: true, details: true, dir: true, div: true, dl: true,
110
+ dt: true, embed: true, fieldset: true, figcaption: true, figure: true,
111
+ footer: true, form: true, frame: true, frameset: true, h1: true, h2: true,
112
+ h3: true, h4: true, h5: true, h6: true, head: true, header: true,
113
+ hgroup: true, hr: true, html: true, iframe: true, img: true, input: true,
114
+ keygen: true, li: true, link: true, listing: true, main: true,
115
+ marquee: true, menu: true, meta: true, nav: true, noembed: true,
116
+ noframes: true, noscript: true, object: true, ol: true, p: true,
117
+ param: true, plaintext: true, pre: true, script: true, search: true,
118
+ section: true, select: true, source: true, style: true, summary: true,
119
+ table: true, tbody: true, td: true, template: true, textarea: true,
120
+ tfoot: true, th: true, thead: true, title: true, tr: true, track: true,
121
+ ul: true, wbr: true, xmp: true
122
+ };
123
+ var PARSER_SAFE_LIST_WALK_EXEMPT = { address: true, div: true, p: true };
124
+ var PARSER_SAFE_LI = { li: true };
125
+ var PARSER_SAFE_DD_DT = { dd: true, dt: true };
126
+ var PARSER_SAFE_SVG_INTEGRATION_POINTS = { foreignObject: true, desc: true, title: true };
127
+ var PARSER_SAFE_MATHML_INTEGRATION_POINTS = { mi: true, mo: true, mn: true, ms: true, mtext: true, 'annotation-xml': true };
128
+ // (e) the only element content a <select> keeps through a parse
129
+ var PARSER_SAFE_SELECT_CONTENT = { option: true, optgroup: true, hr: true, script: true, template: true };
130
+ // (f) elements whose content parses as text
131
+ var PARSER_SAFE_TEXT_ONLY = { textarea: true, xmp: true, plaintext: true };
132
+ // (g) void elements, which cannot hold child nodes in markup
133
+ var PARSER_SAFE_VOID = { img: true, input: true, br: true, hr: true, wbr: true, area: true, col: true, source: true, track: true };
134
+ // (h) table structure
135
+ var PARSER_SAFE_TABLE_PARTS = { caption: true, colgroup: true, col: true, thead: true, tbody: true, tfoot: true, tr: true, td: true, th: true };
136
+ var PARSER_SAFE_TABLE_CHILDREN = { caption: true, colgroup: true, thead: true, tbody: true, tfoot: true, script: true, template: true, style: true };
137
+ var PARSER_SAFE_VALID_PARENTS = {
138
+ caption: { table: true },
139
+ colgroup: { table: true },
140
+ thead: { table: true },
141
+ tbody: { table: true },
142
+ tfoot: { table: true },
143
+ tr: { thead: true, tbody: true, tfoot: true },
144
+ td: { tr: true },
145
+ th: { tr: true },
146
+ col: { colgroup: true }
147
+ };
148
+ var PARSER_SAFE_PART_CHILDREN = {
149
+ thead: { tr: true, script: true, template: true },
150
+ tbody: { tr: true, script: true, template: true },
151
+ tfoot: { tr: true, script: true, template: true },
152
+ tr: { td: true, th: true, script: true, template: true },
153
+ colgroup: { col: true, template: true }
154
+ };
155
+ // (i) document shell elements
156
+ var PARSER_SAFE_SHELL = { html: true, head: true, body: true, frameset: true };
59
157
 
60
158
  // Attributes that need URL absolutification
61
159
  var URL_ATTRS = ['src', 'href', 'action', 'poster', 'data'];
@@ -186,6 +284,88 @@ function hasDangerousScheme(value) {
186
284
  || compact.indexOf('data:text/html') === 0;
187
285
  }
188
286
 
287
+ /**
288
+ * Count UTF-8 bytes of a string (module-scope twin of the createCapture-inner
289
+ * utf8ByteLength; both exist because classifyAssetRef is a pure module-level
290
+ * export and the inner degrade hooks reuse it). Surrogate pairs count as 4
291
+ * bytes; lone surrogates as 3.
292
+ * @param {string} text
293
+ * @returns {number}
294
+ */
295
+ function assetUtf8ByteLength(text) {
296
+ var str = String(text == null ? '' : text);
297
+ var bytes = 0;
298
+ for (var i = 0; i < str.length; i++) {
299
+ var code = str.charCodeAt(i);
300
+ if (code < 0x80) {
301
+ bytes += 1;
302
+ } else if (code < 0x800) {
303
+ bytes += 2;
304
+ } else if (code >= 0xD800 && code <= 0xDBFF && i + 1 < str.length) {
305
+ var next = str.charCodeAt(i + 1);
306
+ if (next >= 0xDC00 && next <= 0xDFFF) {
307
+ bytes += 4;
308
+ i++;
309
+ } else {
310
+ bytes += 3;
311
+ }
312
+ } else {
313
+ bytes += 3;
314
+ }
315
+ }
316
+ return bytes;
317
+ }
318
+
319
+ /**
320
+ * Classify an asset URL by FETCHABILITY (Phase 12 ASST-04). This is a control
321
+ * distinct from hasDangerousScheme (injection): a URL can be injection-safe yet
322
+ * non-shareable as a mirrored reference. Two non-shareable classes degrade to a
323
+ * dimensioned placeholder at capture so a dead/blob reference never reaches the
324
+ * wire and one giant inline image cannot blow the per-message cap:
325
+ * - `blob:`/origin-local object URLs (always non-shareable -- they are
326
+ * origin-local and dead at the cross-origin viewer);
327
+ * - `data:` URIs whose UTF-8 byte length exceeds `capBytes`.
328
+ * Everything else (http/https, small inline `data:`, relative URLs that
329
+ * absolutify) is shareable and passes through untouched -- benign small `data:`
330
+ * icons stay byte-identical (Pitfall 5: no over-degrade).
331
+ * @param {string} url the (resolved or raw) asset reference
332
+ * @param {number} capBytes byte cap for inline `data:` (ASSET_DATA_URI_MAX_BYTES)
333
+ * @returns {{ok: true}|{ok: false, reason: 'blob'|'oversized-data'}}
334
+ */
335
+ export function classifyAssetRef(url, capBytes) {
336
+ if (!url || typeof url !== 'string') return { ok: true };
337
+ // Match the whitespace-obfuscation discipline of hasDangerousScheme: a
338
+ // "blo\tb:" or " data:" form normalizes at parse time, so strip <= 0x20
339
+ // before scheme-matching.
340
+ var compact = stripLowChars(url).toLowerCase();
341
+ if (compact.indexOf('blob:') === 0) {
342
+ return { ok: false, reason: 'blob' };
343
+ }
344
+ if (compact.indexOf('data:') === 0) {
345
+ var cap = capBytes || 0;
346
+ if (assetUtf8ByteLength(url) > cap) {
347
+ return { ok: false, reason: 'oversized-data' };
348
+ }
349
+ }
350
+ return { ok: true };
351
+ }
352
+
353
+ /**
354
+ * Pure predicate (Phase 12 ASST-03): true only when a resolved `currentSrc`
355
+ * is present AND differs from the resolved plain `src`, i.e. a responsive
356
+ * `srcset`/`<picture>` actually negotiated a non-default variant worth pinning.
357
+ * Empty `currentSrc` (jsdom returns "") never enriches; an equal value never
358
+ * enriches (plain `<img src>` stays byte-identical on the wire).
359
+ * @param {string} resolvedCurrentSrc absolutified currentSrc
360
+ * @param {string} resolvedSrc absolutified src
361
+ * @returns {boolean}
362
+ */
363
+ export function currentSrcDiffers(resolvedCurrentSrc, resolvedSrc) {
364
+ if (!resolvedCurrentSrc || typeof resolvedCurrentSrc !== 'string') return false;
365
+ if (resolvedCurrentSrc === '') return false;
366
+ return resolvedCurrentSrc !== (resolvedSrc || '');
367
+ }
368
+
189
369
  /**
190
370
  * Minimal srcset candidate parser for the URL+descriptor forms this project
191
371
  * emits. Unlike split(','), it keeps commas inside data:image URLs attached
@@ -424,6 +604,48 @@ function defaultMaskText(text) {
424
604
  * @property {(text: string, element: Element) => string} [maskInputFn]
425
605
  * Optional (SEC-03). Custom input-value mask (rrweb signature). Same
426
606
  * fail-closed containment as maskTextFn.
607
+ * @property {string} [maskMediaSelector]
608
+ * Optional (MSEC-03). CSS selector: matching <video>/<audio>/asset elements
609
+ * omit their URL from the wire and degrade to the dimension-only block
610
+ * placeholder (the blockSelector placeholder path), AND emit NO STREAM.MEDIA
611
+ * state (the media-tracker skip predicates also gate on this selector). The
612
+ * privacy control for "mirror nothing about this media -- not its URL, not
613
+ * its playback timeline." Invalid selectors THROW Error('invalid-mask-
614
+ * selector') at factory time, exactly like blockSelector/maskTextSelector.
615
+ * @property {boolean} [maskAssetUrls]
616
+ * Optional (MSEC-03), default false. When true, strip a documented token/PII
617
+ * query-param denylist (AWS SigV4/SigV2, GCP signed-URL, Azure SAS, and a
618
+ * generic token/secret/auth set -- case-insensitive, exact-name OR denied
619
+ * prefix) from asset/media URLs before the wire. Functional params (w, h, q,
620
+ * format, v, id, t, ...) survive. A URL with no denylisted param is emitted
621
+ * BYTE-IDENTICAL (the original string, never URL.toString() normalization),
622
+ * so off-by-default keeps the wire byte-identical (the differential oracle is
623
+ * unaffected). See TOKEN_PARAM_DENYLIST + docs/SECURITY.md for the exact list.
624
+ * @property {(url: string, ctx: {attr: string, tag: string, nid: string, kind: ('image'|'media')}) => (string|null)} [maskAssetUrlFn]
625
+ * Optional (MSEC-03). Custom asset/media URL redactor; takes precedence over
626
+ * maskAssetUrls. A returned string replaces the URL on the wire; null BLOCKS
627
+ * the URL (the attribute is removed -> the viewer never fetches it); a THROW
628
+ * FAILS CLOSED -> block (logged, treated as null -- never raised, never the
629
+ * raw URL). Stricter than maskTextFn: a thrown text mask falls back to the
630
+ * asterisk default, but a thrown URL redactor blocks (a half-redacted URL
631
+ * that the viewer then fetches is worse than no URL).
632
+ * @property {number} [messageLimitBytes]
633
+ * Optional (quick task 261202-jwf), default RELAY_PER_MESSAGE_LIMIT_BYTES
634
+ * (1 MiB). The largest wire message this capture emits, in UTF-8 bytes of
635
+ * the JSON payload: it governs the snapshot hard reset, single mutation
636
+ * diffs, mutation chunking and subtree responses. Only a positive finite
637
+ * number is accepted; any other value falls back to the default. Relay
638
+ * users keep the default, because the relay drops messages over 1 MiB;
639
+ * local recorders that never pass through a relay (FSB records with 8 MiB)
640
+ * may raise it.
641
+ * @property {number} [snapshotBudgetBytes]
642
+ * Optional (quick task 261202-jwf), default
643
+ * floor(messageLimitBytes * SNAPSHOT_BUDGET_FRACTION). The budget the
644
+ * snapshot truncation passes and sidecar pruning aim for, in UTF-8 wire
645
+ * bytes. Only a positive finite number is accepted; any other value falls
646
+ * back to the default. Clamped to at most messageLimitBytes. Relay users
647
+ * keep the default; local recorders may raise it (FSB records with 4 MiB)
648
+ * so large pages keep every stylesheet.
427
649
  */
428
650
 
429
651
  /**
@@ -472,6 +694,19 @@ export function createCapture(config) {
472
694
  ? cfg.fetchStylesheet
473
695
  : null;
474
696
 
697
+ // Per-instance budgets (quick task 261202-jwf, D 2.1). Only positive finite
698
+ // numbers are accepted; anything else falls back to the relay-sized
699
+ // defaults, so with no options the wire is unchanged. The snapshot budget
700
+ // never exceeds the message limit, or the hard reset in
701
+ // fitSnapshotPayloadForBudget would empty an over-budget snapshot instead
702
+ // of pruning it.
703
+ function positiveFiniteOption(value) {
704
+ return typeof value === 'number' && isFinite(value) && value > 0 ? value : null;
705
+ }
706
+ var messageLimitBytes = positiveFiniteOption(cfg.messageLimitBytes) || RELAY_PER_MESSAGE_LIMIT_BYTES;
707
+ var snapshotBudgetBytes = positiveFiniteOption(cfg.snapshotBudgetBytes) || Math.floor(messageLimitBytes * SNAPSHOT_BUDGET_FRACTION);
708
+ snapshotBudgetBytes = Math.min(snapshotBudgetBytes, messageLimitBytes);
709
+
475
710
  // SEC-03 privacy-masking config (plan 03-03, rrweb-compatible vocabulary
476
711
  // per 03-RESEARCH Pattern 5). Every option defaults OFF: with no masking
477
712
  // config the wire is byte-identical to the unmasked output. The one
@@ -488,6 +723,16 @@ export function createCapture(config) {
488
723
  var maskInputFn = (typeof cfg.maskInputFn === 'function') ? cfg.maskInputFn : null;
489
724
  var blockSelector = compileMaskSelector(cfg.blockSelector);
490
725
  var maskTextSelector = compileMaskSelector(cfg.maskTextSelector);
726
+ // MSEC-03 asset/media URL masking (plan 15-01). Same off-by-default + one-
727
+ // allowed-throw-site discipline as the SEC-03 family above: maskMediaSelector
728
+ // is compiled (validated) here so an invalid selector fails closed and LOUD;
729
+ // maskAssetUrls/maskAssetUrlFn default OFF so the wire stays byte-identical
730
+ // (the differential oracle is unaffected). maskAssetUrlFn fails closed at
731
+ // RUNTIME to BLOCK (see maskAssetUrlForWire), the safeMaskText precedent
732
+ // adapted for URLs (a half-redacted URL the viewer fetches is worse than none).
733
+ var maskMediaSelector = compileMaskSelector(cfg.maskMediaSelector);
734
+ var maskAssetUrls = cfg.maskAssetUrls === true;
735
+ var maskAssetUrlFn = (typeof cfg.maskAssetUrlFn === 'function') ? cfg.maskAssetUrlFn : null;
491
736
 
492
737
  /**
493
738
  * Ancestor-inclusive form of the skipElement seam (reference parity:
@@ -605,12 +850,30 @@ export function createCapture(config) {
605
850
  var valueCaptureActive = false;
606
851
  var valueListenerRoots = new WeakSet();
607
852
  var valueListenerRecords = [];
853
+ // Media tracker bookkeeping (STREAM.MEDIA). Mirrors the value-tracker's
854
+ // root-set/records pair (above): media events do NOT bubble, so listeners
855
+ // are PER-ELEMENT and must be explicitly torn down. mediaTracked maps a live
856
+ // <video>/<audio> to its bound listener handlers + per-element lastMediaSend
857
+ // throttle stamp; mediaTrackedRecords is the iteration order for teardown.
858
+ var mediaTrackingActive = false;
859
+ var mediaTracked = new Map();
860
+ var mediaTrackedRecords = [];
608
861
  var nativeAttachShadow = null;
609
862
  var attachShadowProto = null;
610
863
  var pendingStyleSourceChanges = new Map();
611
864
  var styleSourceRegistry = new Map();
612
865
  var styleOwnerToSourceKey = typeof WeakMap === 'function' ? new WeakMap() : null;
613
866
  var styleScopeRoots = new Map();
867
+ // CSSOM dedupe state (quick task 261202-jwf, D 1.1 / D 1.2), per session:
868
+ // styleSourceFingerprints maps sourceId -> fingerprint of the source the
869
+ // viewer holds, seeded from every emitted snapshot; styleScopeSignatures maps
870
+ // styleScopeKey -> cheap scope signature; styleSheetIdentities gives each
871
+ // CSSStyleSheet a stable counter for those signatures.
872
+ var styleSourceFingerprints = new Map();
873
+ var styleScopeSignatures = new Map();
874
+ var styleSheetIdentities = typeof WeakMap === 'function' ? new WeakMap() : null;
875
+ var nextStyleSheetIdentity = 1;
876
+ var lastFullStyleReconcileAt = 0;
614
877
  var nativeCssStyleSheetMethods = null;
615
878
  var flushingMutations = false;
616
879
 
@@ -626,7 +889,8 @@ export function createCapture(config) {
626
889
  blockedSubtrees: 0, // object/embed subtrees dropped + srcdoc attrs dropped
627
890
  cssScrubs: 0, // CSS values rewritten by scrubCssText
628
891
  maskedTextNodes: 0, // (plan 03-03) maskTextSelector-matched text masked
629
- maskedInputs: 0 // (plan 03-03) masked input values
892
+ maskedInputs: 0, // (plan 03-03) masked input values
893
+ maskedAssetUrls: 0 // (plan 15-01) asset/media URLs stripped/redacted/blocked
630
894
  };
631
895
 
632
896
  function beginStreamSession() {
@@ -645,10 +909,15 @@ export function createCapture(config) {
645
909
  sanitizeCounters.cssScrubs = 0;
646
910
  sanitizeCounters.maskedTextNodes = 0;
647
911
  sanitizeCounters.maskedInputs = 0;
912
+ sanitizeCounters.maskedAssetUrls = 0;
648
913
  pendingStyleSourceChanges.clear();
649
914
  styleSourceRegistry.clear();
650
915
  styleScopeRoots.clear();
651
916
  styleOwnerToSourceKey = typeof WeakMap === 'function' ? new WeakMap() : null;
917
+ styleSourceFingerprints.clear();
918
+ styleScopeSignatures.clear();
919
+ styleSheetIdentities = typeof WeakMap === 'function' ? new WeakMap() : null;
920
+ lastFullStyleReconcileAt = 0;
652
921
  }
653
922
 
654
923
  function getCurrentStreamMetadata() {
@@ -684,6 +953,22 @@ export function createCapture(config) {
684
953
  return nid;
685
954
  }
686
955
 
956
+ // Resolve the nid a childList add op uses as its parent, or an attributes
957
+ // op uses as its target (quick task 261127-u5c). The MAIN document <body>
958
+ // never receives a counter nid (the snapshot sidecar starts below it), so
959
+ // it resolves to the reserved BODY_NID; every other node resolves exactly
960
+ // as getTrackedNodeId does. Main document only: same-origin frame bodies
961
+ // are different elements that already carry counter nids from
962
+ // serializeFrameDocument. The body is deliberately kept out of
963
+ // elementToNid/nidToElement, so getNodeId, rm ops, subtree requests, and
964
+ // shadow hosts never see it. Used only for the add-op parent and the
965
+ // attr-op target: text ops keep getTrackedNodeId because a text op applies
966
+ // as textContent = text and would flatten the whole mirror body.
967
+ function mutationTargetNid(target) {
968
+ if (target && target === document.body) return BODY_NID;
969
+ return getTrackedNodeId(target);
970
+ }
971
+
687
972
  function clearNodeMirror() {
688
973
  elementToNid = new WeakMap();
689
974
  nidToElement.clear();
@@ -839,6 +1124,7 @@ export function createCapture(config) {
839
1124
  cloneToNid: cloneToNid
840
1125
  });
841
1126
  if (subtreeResult && subtreeResult.drop) return null;
1127
+ neutralizeParserHostileNesting(container, cloneToNid, { rootContext: 'container' });
842
1128
 
843
1129
  var shadowPayload = {
844
1130
  hostNid: String(hostNid),
@@ -1077,6 +1363,36 @@ export function createCapture(config) {
1077
1363
  };
1078
1364
  }
1079
1365
 
1366
+ // 32-bit FNV-1a over UTF-16 code units (quick task 261202-jwf, D 1.1). Not a
1367
+ // security hash: it only tells whether the viewer already holds a source.
1368
+ function fnv1a32(text) {
1369
+ var str = String(text || '');
1370
+ var hash = 0x811c9dc5; // FNV-1a 32-bit offset basis
1371
+ for (var i = 0; i < str.length; i++) {
1372
+ hash ^= str.charCodeAt(i);
1373
+ hash = Math.imul(hash, 0x01000193); // FNV-1a 32-bit prime
1374
+ }
1375
+ return (hash >>> 0).toString(16);
1376
+ }
1377
+
1378
+ // Fingerprint of a style source as the viewer holds it: ownerKind, order,
1379
+ // href, media, disabled, plus the length and FNV-1a hash of its cssText.
1380
+ // Callers pass the source as collected (the same once-sanitized text a
1381
+ // snapshot carries), so an unchanged source never pays a second CSS scrub.
1382
+ function styleSourceFingerprint(source) {
1383
+ var s = source || {};
1384
+ var cssText = String(s.cssText || '');
1385
+ return [
1386
+ s.ownerKind || '',
1387
+ s.order,
1388
+ s.href || '',
1389
+ s.media || '',
1390
+ s.disabled ? 1 : 0,
1391
+ cssText.length,
1392
+ fnv1a32(cssText)
1393
+ ].join('|');
1394
+ }
1395
+
1080
1396
  function safeStylesheetHref(href, doc) {
1081
1397
  if (!href) return '';
1082
1398
  var resolved = absolutifyUrl(String(href), doc);
@@ -1164,6 +1480,50 @@ export function createCapture(config) {
1164
1480
  return entries;
1165
1481
  }
1166
1482
 
1483
+ function styleSheetIdentity(sheet) {
1484
+ if (!sheet || !styleSheetIdentities) return 0;
1485
+ var identity = styleSheetIdentities.get(sheet);
1486
+ if (!identity) {
1487
+ identity = nextStyleSheetIdentity++;
1488
+ styleSheetIdentities.set(sheet, identity);
1489
+ }
1490
+ return identity;
1491
+ }
1492
+
1493
+ // Cheap per-scope signature (quick task 261202-jwf, D 1.2): per stylesheet
1494
+ // entry, its sheet identity, cssRules.length (-1 when unreadable), disabled,
1495
+ // media and RAW href. It never serializes rules, so the per-flush reconcile
1496
+ // costs no CSS text. It reads the raw href attribute instead of calling
1497
+ // styleOwnerHref, which counts blocked URL schemes as a side effect.
1498
+ function styleScopeSignature(doc, root) {
1499
+ var entries = styleSheetEntriesForScope(doc, root);
1500
+ var parts = [];
1501
+ for (var i = 0; i < entries.length; i++) {
1502
+ var entry = entries[i] || {};
1503
+ var sheet = entry.sheet || null;
1504
+ var ownerNode = entry.ownerNode || null;
1505
+ var ruleCount = -1;
1506
+ try {
1507
+ ruleCount = sheet && sheet.cssRules ? sheet.cssRules.length : -1;
1508
+ } catch (err) {
1509
+ ruleCount = -1; // cross-origin sheets throw on cssRules
1510
+ }
1511
+ var rawHref = '';
1512
+ if (ownerNode && typeof ownerNode.getAttribute === 'function') {
1513
+ rawHref = ownerNode.getAttribute('href') || '';
1514
+ }
1515
+ if (!rawHref && sheet && sheet.href) rawHref = String(sheet.href);
1516
+ parts.push([
1517
+ styleSheetIdentity(sheet),
1518
+ ruleCount,
1519
+ styleOwnerDisabled(ownerNode, sheet) ? 1 : 0,
1520
+ styleOwnerMedia(ownerNode, sheet),
1521
+ rawHref
1522
+ ].join(','));
1523
+ }
1524
+ return parts.join(';');
1525
+ }
1526
+
1167
1527
  function sourceFromStyleSheetEntry(entry, scope, order, doc, root) {
1168
1528
  var e = entry || {};
1169
1529
  var ownerKind = ownerKindForStyleNode(e.ownerNode, e.adopted);
@@ -1288,12 +1648,21 @@ export function createCapture(config) {
1288
1648
  if (!sourceId) return;
1289
1649
  var safeSource = null;
1290
1650
  if (action !== 'remove') {
1651
+ // Quick task 261202-jwf (D 1.1): skip a source the viewer already
1652
+ // holds. The fingerprint is taken before the re-sanitize below.
1653
+ var fingerprint = styleSourceFingerprint(source);
1654
+ if (styleSourceFingerprints.get(sourceId) === fingerprint) return;
1291
1655
  safeSource = Object.assign({}, source, {
1292
1656
  sourceId: sourceId,
1293
1657
  scope: cloneStyleScope(scope || source.scope),
1294
1658
  cssText: sanitizeCssTextForSource(source.cssText || '')
1295
1659
  });
1296
1660
  safeSource.approxBytes = wireByteLength(safeSource.cssText || '');
1661
+ styleSourceFingerprints.set(sourceId, fingerprint);
1662
+ } else {
1663
+ // A remove is only meaningful for a source the viewer holds.
1664
+ if (!styleSourceFingerprints.has(sourceId)) return;
1665
+ styleSourceFingerprints.delete(sourceId);
1297
1666
  }
1298
1667
  pendingStyleSourceChanges.set(sourceId, {
1299
1668
  op: DIFF_OP.STYLE_SOURCE,
@@ -1351,6 +1720,43 @@ export function createCapture(config) {
1351
1720
  scope: entry ? entry.scope : cloneStyleScope(scope)
1352
1721
  }, entry ? entry.scope : scope, reason || 'cssom-style-source-stale');
1353
1722
  });
1723
+ styleScopeSignatures.set(scopeKey, styleScopeSignature(docForScope, rootForScope));
1724
+ }
1725
+
1726
+ // Quick task 261202-jwf (D 1.4): find the known style scope an owner lives
1727
+ // in. An element (or a sheet's ownerNode) resolves through getRootNode(); a
1728
+ // constructable sheet matches the first scope whose adoptedStyleSheets holds
1729
+ // it. Returns a styleScopeRoots value, or null when no known scope matches.
1730
+ function resolveStyleScopeForOwner(owner) {
1731
+ if (!owner) return null;
1732
+ var match = null;
1733
+ var node = owner.nodeType ? owner : owner.ownerNode;
1734
+ if (node) {
1735
+ var rootNode = null;
1736
+ try {
1737
+ rootNode = typeof node.getRootNode === 'function' ? node.getRootNode() : null;
1738
+ } catch (err) {
1739
+ rootNode = null;
1740
+ }
1741
+ if (!rootNode) return null;
1742
+ styleScopeRoots.forEach(function(info) {
1743
+ if (!match && info && info.root === rootNode) match = info;
1744
+ });
1745
+ if (!match) {
1746
+ styleScopeRoots.forEach(function(info) {
1747
+ if (!match && info && info.doc === rootNode) match = info;
1748
+ });
1749
+ }
1750
+ return match;
1751
+ }
1752
+ styleScopeRoots.forEach(function(info) {
1753
+ if (match || !info || !info.root) return;
1754
+ try {
1755
+ var adopted = info.root.adoptedStyleSheets;
1756
+ if (adopted && Array.prototype.indexOf.call(adopted, owner) !== -1) match = info;
1757
+ } catch (err) { /* adoptedStyleSheets unreadable in this scope */ }
1758
+ });
1759
+ return match;
1354
1760
  }
1355
1761
 
1356
1762
  function markStyleOwnerDirty(owner, reason) {
@@ -1358,6 +1764,14 @@ export function createCapture(config) {
1358
1764
  var key = owner && styleOwnerToSourceKey ? styleOwnerToSourceKey.get(owner) : '';
1359
1765
  var entry = key ? styleSourceRegistry.get(key) : null;
1360
1766
  if (!entry) {
1767
+ // An owner added after the snapshot is not registered yet: reconcile
1768
+ // the scope it lives in, and fall back to a fresh snapshot only when no
1769
+ // known scope matches (quick task 261202-jwf, D 1.4).
1770
+ var info = resolveStyleScopeForOwner(owner);
1771
+ if (info) {
1772
+ queueStyleScopeReplacement(info.scope, info.root, reason || 'cssom-style-source-stale');
1773
+ return;
1774
+ }
1361
1775
  sendCssomFreshSnapshot('cssom-style-source-stale');
1362
1776
  return;
1363
1777
  }
@@ -1408,10 +1822,19 @@ export function createCapture(config) {
1408
1822
  nativeCssStyleSheetMethods = null;
1409
1823
  }
1410
1824
 
1411
- function reconcileAdoptedStyleSheetsForScope(root, scope) {
1825
+ // Periodic reconcile, run on every flush. It catches rule changes the
1826
+ // patched prototype cannot see, such as a page insertRule from an extension's
1827
+ // isolated world. It skips a scope whose cheap signature is unchanged unless
1828
+ // forceFull is set (quick task 261202-jwf, D 1.2).
1829
+ function reconcileAdoptedStyleSheetsForScope(root, scope, forceFull) {
1412
1830
  if (styleMode !== 'cssom') return;
1413
1831
  try {
1414
1832
  if (root && root.adoptedStyleSheets) {
1833
+ if (!forceFull) {
1834
+ var info = styleScopeRoots.get(styleScopeKey(scope)) || {};
1835
+ var signature = styleScopeSignature(info.doc || root.ownerDocument || document, root);
1836
+ if (styleScopeSignatures.get(styleScopeKey(scope)) === signature) return;
1837
+ }
1415
1838
  queueStyleScopeReplacement(scope, root, 'adoptedStyleSheets');
1416
1839
  }
1417
1840
  } catch (err) {
@@ -1421,9 +1844,78 @@ export function createCapture(config) {
1421
1844
 
1422
1845
  function reconcileAllKnownStyleScopes() {
1423
1846
  if (styleMode !== 'cssom') return;
1847
+ // Safety net: at most once every STYLE_FULL_RECONCILE_MS, re-collect every
1848
+ // scope even when its signature is unchanged (a same-count rule edit).
1849
+ var now = Date.now();
1850
+ var forceFull = (now - lastFullStyleReconcileAt) >= STYLE_FULL_RECONCILE_MS;
1851
+ if (forceFull) lastFullStyleReconcileAt = now;
1424
1852
  styleScopeRoots.forEach(function(info) {
1425
1853
  if (!info || !info.root || !info.scope) return;
1426
- reconcileAdoptedStyleSheetsForScope(info.root, info.scope);
1854
+ reconcileAdoptedStyleSheetsForScope(info.root, info.scope, forceFull);
1855
+ });
1856
+ }
1857
+
1858
+ // Visit every style scope an emitted snapshot payload carries: the document
1859
+ // scope, each shadowRoots[] entry and each frames[] entry, recursing into
1860
+ // each frame's own shadowRoots and frames. Entries without arrays are skipped.
1861
+ function forEachEmittedStyleScope(payload, visit) {
1862
+ var p = payload || {};
1863
+ function visitSidecars(container) {
1864
+ var shadowRoots = Array.isArray(container.shadowRoots) ? container.shadowRoots : [];
1865
+ for (var s = 0; s < shadowRoots.length; s++) {
1866
+ var shadow = shadowRoots[s] || {};
1867
+ if (Array.isArray(shadow.styleSources)) {
1868
+ visit({ kind: 'shadow', hostNid: String(shadow.hostNid) }, shadow.styleSources, shadow.styleStrategy || null);
1869
+ }
1870
+ }
1871
+ var frames = Array.isArray(container.frames) ? container.frames : [];
1872
+ for (var f = 0; f < frames.length; f++) {
1873
+ var frame = frames[f] || {};
1874
+ if (Array.isArray(frame.styleSources)) {
1875
+ visit({ kind: 'frame', frameNid: String(frame.frameNid) }, frame.styleSources, frame.styleStrategy || null);
1876
+ }
1877
+ visitSidecars(frame);
1878
+ }
1879
+ }
1880
+ if (Array.isArray(p.styleSources)) {
1881
+ visit({ kind: 'document' }, p.styleSources, p.styleStrategy || null);
1882
+ }
1883
+ visitSidecars(p);
1884
+ }
1885
+
1886
+ // Seed the dedupe state from an EMITTED snapshot (quick task 261202-jwf,
1887
+ // D 1.1): the viewer now holds exactly the style sources the payload carries
1888
+ // after budget pruning, and the snapshot supersedes any queued change.
1889
+ function seedStyleSourceFingerprints(payload) {
1890
+ if (styleMode !== 'cssom') return;
1891
+ styleSourceFingerprints.clear();
1892
+ pendingStyleSourceChanges.clear();
1893
+ forEachEmittedStyleScope(payload, function(scope, styleSources) {
1894
+ for (var i = 0; i < styleSources.length; i++) {
1895
+ var source = styleSources[i];
1896
+ if (!source || !source.sourceId) continue;
1897
+ styleSourceFingerprints.set(String(source.sourceId), styleSourceFingerprint(source));
1898
+ }
1899
+ });
1900
+ styleScopeSignatures.clear();
1901
+ styleScopeRoots.forEach(function(info, scopeKey) {
1902
+ if (!info || !info.root) return;
1903
+ styleScopeSignatures.set(scopeKey, styleScopeSignature(info.doc || document, info.root));
1904
+ });
1905
+ lastFullStyleReconcileAt = Date.now();
1906
+ }
1907
+
1908
+ // Heal a pruned snapshot (quick task 261202-jwf, D 1.3): when an emitted
1909
+ // scope carries fewer styleSources than it collected, reconcile that scope
1910
+ // now, so the dropped sources go out as style-source diffs in the next
1911
+ // flush. Scopes the snapshot dropped whole have no viewer host to heal.
1912
+ function healPrunedStyleScopes(payload) {
1913
+ if (styleMode !== 'cssom') return;
1914
+ forEachEmittedStyleScope(payload, function(scope, styleSources, styleStrategy) {
1915
+ if (!styleStrategy) return;
1916
+ if (styleSources.length < styleStrategy.sourceCount) {
1917
+ queueStyleScopeReplacement(scope, null, 'snapshot-style-pruned');
1918
+ }
1427
1919
  });
1428
1920
  }
1429
1921
 
@@ -1432,7 +1924,10 @@ export function createCapture(config) {
1432
1924
  logger.warn('[DOM Stream] cssom resnapshot', {
1433
1925
  reason: reason || 'cssom-style-source-stale'
1434
1926
  });
1435
- safeSend(STREAM.SNAPSHOT, serializeDOM());
1927
+ var snapshot = serializeDOM();
1928
+ safeSend(STREAM.SNAPSHOT, snapshot);
1929
+ seedStyleSourceFingerprints(snapshot);
1930
+ healPrunedStyleScopes(snapshot);
1436
1931
  }
1437
1932
 
1438
1933
  function prepareFrameDocumentClone(frameDoc, bodyClone, cloneToNid) {
@@ -1442,6 +1937,7 @@ export function createCapture(config) {
1442
1937
  var cloneDescendants = bodyClone.querySelectorAll('*');
1443
1938
  var toRemove = [];
1444
1939
  var blockedPairs = [];
1940
+ var assetUnavailablePairs = [];
1445
1941
 
1446
1942
  for (var i = 0; i < liveDescendants.length; i++) {
1447
1943
  var live = liveDescendants[i];
@@ -1484,6 +1980,21 @@ export function createCapture(config) {
1484
1980
  }
1485
1981
  var srcsetVal = clone.getAttribute('srcset');
1486
1982
  if (srcsetVal) clone.setAttribute('srcset', absolutifySrcset(srcsetVal, frameDoc));
1983
+
1984
+ // ASST-04 degrade + ASST-03 currentSrc pin (same treatment as the main
1985
+ // snapshot pair walk), clone-only -- the live frame node is never touched.
1986
+ var frameDegradeReason = assetDegradeReason(clone);
1987
+ if (frameDegradeReason) {
1988
+ assetUnavailablePairs.push({ orig: live, clone: clone, reason: frameDegradeReason });
1989
+ } else if (tag === 'img') {
1990
+ var frameResolvedCurrent = absolutifyUrl(live.currentSrc || '', frameDoc);
1991
+ var frameResolvedSrc = clone.getAttribute('src') || '';
1992
+ if (currentSrcDiffers(frameResolvedCurrent, frameResolvedSrc)
1993
+ && !hasDangerousScheme(frameResolvedCurrent)) {
1994
+ clone.setAttribute('data-ps-currentsrc', frameResolvedCurrent);
1995
+ }
1996
+ }
1997
+
1487
1998
  if (styleMode !== 'cssom') captureComputedStyles(live, clone);
1488
1999
  sanitizeForWire('element', { orig: live, clone: clone });
1489
2000
  }
@@ -1499,6 +2010,15 @@ export function createCapture(config) {
1499
2010
  cloneToNid
1500
2011
  );
1501
2012
  }
2013
+ for (var aub = 0; aub < assetUnavailablePairs.length; aub++) {
2014
+ replaceWithAssetUnavailablePlaceholder(
2015
+ assetUnavailablePairs[aub].orig,
2016
+ assetUnavailablePairs[aub].clone,
2017
+ readBlockRect(assetUnavailablePairs[aub].orig),
2018
+ assetUnavailablePairs[aub].reason,
2019
+ cloneToNid
2020
+ );
2021
+ }
1502
2022
  }
1503
2023
 
1504
2024
  function serializeFrameDocument(iframe, frameNid, frameDoc) {
@@ -1517,6 +2037,7 @@ export function createCapture(config) {
1517
2037
  cloneToNid: cloneToNid
1518
2038
  });
1519
2039
  if (subtreeResult && subtreeResult.drop) return null;
2040
+ neutralizeParserHostileNesting(bodyClone, cloneToNid, { rootContext: 'container' });
1520
2041
 
1521
2042
  var nodeIds = buildNodeIdSidecar(bodyClone, cloneToNid, false);
1522
2043
  var frameShadowRoots = collectShadowRootPayloads(frameDoc.body, nodeIds);
@@ -1712,6 +2233,39 @@ export function createCapture(config) {
1712
2233
  return values;
1713
2234
  }
1714
2235
 
2236
+ // Positional identity for the selected options. selectedValues carry the
2237
+ // masked option text, so colliding masks (default mask turns 'aa' and 'bb'
2238
+ // both into '**') make value-based selection ambiguous on the renderer.
2239
+ // Option indexes contain no page content, survive masking unchanged, and
2240
+ // pin the exact option(s) the renderer must select.
2241
+ function selectedOptionIndexes(select) {
2242
+ var indexes = [];
2243
+ var options = select && select.options ? select.options : [];
2244
+ for (var i = 0; i < options.length; i++) {
2245
+ if (options[i].selected) indexes.push(i);
2246
+ }
2247
+ return indexes;
2248
+ }
2249
+
2250
+ // Positional selectedIndexes only line up with the mirror when EVERY option
2251
+ // survives the wire. If skipElement/blockSelector drops an <option> (or an
2252
+ // <optgroup>), the mirror's options list is shorter, so live-collection
2253
+ // indexes would address the wrong option. Detect that and fall back to value
2254
+ // matching instead.
2255
+ function selectHasFilteredOptions(select) {
2256
+ var nodes = select && select.querySelectorAll
2257
+ ? select.querySelectorAll('option, optgroup')
2258
+ : [];
2259
+ for (var i = 0; i < nodes.length; i++) {
2260
+ if (skipElementWithAncestors(nodes[i])
2261
+ || blockedWithAncestors(nodes[i])
2262
+ || wireDroppedWithAncestors(nodes[i])) {
2263
+ return true;
2264
+ }
2265
+ }
2266
+ return false;
2267
+ }
2268
+
1715
2269
  function sanitizeInputValue(value, owner) {
1716
2270
  return sanitizeForWire('input', {
1717
2271
  value: value == null ? '' : String(value),
@@ -1748,6 +2302,15 @@ export function createCapture(config) {
1748
2302
  for (var s = 0; s < selected.length; s++) {
1749
2303
  diff.selectedValues.push(sanitizeInputValue(selected[s], control));
1750
2304
  }
2305
+ // Authoritative selection identity (the renderer prefers this over the
2306
+ // maskable selectedValues): option indexes never carry page content and
2307
+ // stay unambiguous even when masked option values collide. Only emit when
2308
+ // every option survives the wire -- if an option is filtered out, the
2309
+ // live indexes would mis-address the shorter mirror options list, so fall
2310
+ // back to value matching there.
2311
+ if (!selectHasFilteredOptions(control)) {
2312
+ diff.selectedIndexes = selectedOptionIndexes(control);
2313
+ }
1751
2314
  return diff;
1752
2315
  }
1753
2316
 
@@ -2087,6 +2650,49 @@ export function createCapture(config) {
2087
2650
  }
2088
2651
  }
2089
2652
 
2653
+ /**
2654
+ * True when the element itself matches maskMediaSelector (MSEC-03). The
2655
+ * blockMatches twin keyed off maskMediaSelector: used by the snapshot/subtree
2656
+ * placeholder path so a masked media/asset element degrades to the
2657
+ * dimension-only block placeholder. Runtime selector errors are contained
2658
+ * (logged, treated as not-matched) so capture never wedges after factory-time
2659
+ * validation. Returns false immediately when maskMediaSelector is null, so the
2660
+ * no-config path is wire-identical (no closest() walk).
2661
+ * @param {Element} el
2662
+ * @returns {boolean}
2663
+ */
2664
+ function maskMediaMatches(el) {
2665
+ if (!maskMediaSelector) return false;
2666
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
2667
+ try {
2668
+ return !!(el.matches && el.matches(maskMediaSelector));
2669
+ } catch (err) {
2670
+ logger.error('[DOM Stream] maskMediaSelector match failed', err);
2671
+ return false;
2672
+ }
2673
+ }
2674
+
2675
+ /**
2676
+ * Ancestor-inclusive maskMediaSelector predicate (MSEC-03), the
2677
+ * blockedWithAncestors twin. ORed into the media-tracker skip guards
2678
+ * (collectTrackedMediaElements + attachMediaListeners) so a masked
2679
+ * <video>/<audio> -- or media inside a masked subtree -- emits NO STREAM.MEDIA
2680
+ * baseline entry and NO STREAM.MEDIA events. Returns false immediately when
2681
+ * maskMediaSelector is null (no-config path wire-identical, no walk).
2682
+ * @param {Element} el
2683
+ * @returns {boolean}
2684
+ */
2685
+ function maskMediaWithAncestors(el) {
2686
+ if (!maskMediaSelector) return false;
2687
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
2688
+ try {
2689
+ return !!(el.closest && el.closest(maskMediaSelector));
2690
+ } catch (err) {
2691
+ logger.error('[DOM Stream] maskMediaSelector match failed', err);
2692
+ return false;
2693
+ }
2694
+ }
2695
+
2090
2696
  /**
2091
2697
  * Elements intentionally absent from the wire must also be absent from the
2092
2698
  * live tracking graph. Otherwise descendants can receive nids before the
@@ -2325,6 +2931,98 @@ export function createCapture(config) {
2325
2931
  return placeholder;
2326
2932
  }
2327
2933
 
2934
+ /**
2935
+ * Build the placeholder for a non-shareable asset (ASST-04). Mirrors
2936
+ * createBlockPlaceholder (dimension-only <div>, identity in the nodeIds
2937
+ * sidecar) plus a machine-readable reason attribute so the renderer/viewer
2938
+ * can show a neutral, dimensioned gap instead of a broken/dead reference.
2939
+ * @param {Document} doc
2940
+ * @param {{width: number, height: number}} rect
2941
+ * @param {'blob'|'oversized-data'} reason
2942
+ * @returns {Element}
2943
+ */
2944
+ function createAssetUnavailablePlaceholder(doc, rect, reason) {
2945
+ var placeholder = doc.createElement('div');
2946
+ placeholder.setAttribute('rr_width', String(rect.width || 0) + 'px');
2947
+ placeholder.setAttribute('rr_height', String(rect.height || 0) + 'px');
2948
+ placeholder.setAttribute('data-ps-asset-unavailable', reason);
2949
+ return placeholder;
2950
+ }
2951
+
2952
+ /**
2953
+ * Replace a detached clone element with its asset-unavailable placeholder,
2954
+ * transferring the nid in cloneToNid exactly like replaceWithBlockPlaceholder.
2955
+ * The LIVE element is never touched (clone-only; Phase 7 no-mutation
2956
+ * invariant -- Pitfall 4).
2957
+ * @param {Element} liveEl
2958
+ * @param {Element} cloneEl
2959
+ * @param {{width: number, height: number}} rect
2960
+ * @param {'blob'|'oversized-data'} reason
2961
+ * @param {Map<Element, string>} [cloneToNid]
2962
+ * @returns {Element|null}
2963
+ */
2964
+ function replaceWithAssetUnavailablePlaceholder(liveEl, cloneEl, rect, reason, cloneToNid) {
2965
+ if (!cloneEl || !cloneEl.parentNode) return null;
2966
+ var nid = cloneToNid && cloneToNid.get(cloneEl);
2967
+ if (!nid) nid = getTrackedNodeId(liveEl) || '';
2968
+ var placeholder = createAssetUnavailablePlaceholder(cloneEl.ownerDocument, rect, reason);
2969
+ cloneEl.parentNode.replaceChild(placeholder, cloneEl);
2970
+ if (cloneToNid) {
2971
+ cloneToNid.delete(cloneEl);
2972
+ if (nid) cloneToNid.set(placeholder, nid);
2973
+ }
2974
+ sanitizeCounters.blockedSubtrees++;
2975
+ return placeholder;
2976
+ }
2977
+
2978
+ /**
2979
+ * Decide whether a clone's URL-bearing attributes make it a non-shareable
2980
+ * asset that must degrade to a placeholder (ASST-04). Inspects the wire
2981
+ * clone's already-absolutified `src`/`poster`/`srcset` and returns the
2982
+ * degrade reason, or '' when the asset is shareable. Pure read of the clone;
2983
+ * never mutates anything.
2984
+ * @param {Element} cloneEl the detached wire clone (post-absolutify)
2985
+ * @returns {'blob'|'oversized-data'|''}
2986
+ */
2987
+ function assetDegradeReason(cloneEl) {
2988
+ if (!cloneEl || !cloneEl.getAttribute) return '';
2989
+ // Scalar src/poster: classify the value directly.
2990
+ var scalarAttrs = ['src', 'poster'];
2991
+ for (var s = 0; s < scalarAttrs.length; s++) {
2992
+ var v = cloneEl.getAttribute(scalarAttrs[s]);
2993
+ if (v) {
2994
+ var c = classifyAssetRef(v, ASSET_DATA_URI_MAX_BYTES);
2995
+ if (!c.ok) return c.reason;
2996
+ }
2997
+ }
2998
+ // srcset: classify each candidate; a single non-shareable candidate
2999
+ // degrades the element (the whole responsive set is unusable as a
3000
+ // reference when one variant is blob:/oversized-data).
3001
+ var srcset = cloneEl.getAttribute('srcset');
3002
+ if (srcset) {
3003
+ var reason = assetDegradeReasonForSrcset(srcset);
3004
+ if (reason) return reason;
3005
+ }
3006
+ return '';
3007
+ }
3008
+
3009
+ /**
3010
+ * Classify a raw srcset string by fetchability: returns the degrade reason of
3011
+ * the first non-shareable candidate, or '' when every candidate is shareable.
3012
+ * Used by the mutation attr branch (which has the raw value, not a clone).
3013
+ * @param {string} srcset
3014
+ * @returns {'blob'|'oversized-data'|''}
3015
+ */
3016
+ function assetDegradeReasonForSrcset(srcset) {
3017
+ if (!srcset) return '';
3018
+ var candidates = parseSrcsetCandidates(srcset);
3019
+ for (var k = 0; k < candidates.length; k++) {
3020
+ var rc = classifyAssetRef(candidates[k].url, ASSET_DATA_URI_MAX_BYTES);
3021
+ if (!rc.ok) return rc.reason;
3022
+ }
3023
+ return '';
3024
+ }
3025
+
2328
3026
  function createTruncatedPlaceholder(doc) {
2329
3027
  var placeholder = doc.createElement('div');
2330
3028
  placeholder.setAttribute('data-phantomstream-truncated', 'true');
@@ -2352,6 +3050,190 @@ export function createCapture(config) {
2352
3050
  return placeholder;
2353
3051
  }
2354
3052
 
3053
+ // Parser-safe serialization (quick task 261202-jwf, D 3.2). A DOM built by
3054
+ // scripts can hold nesting that HTML text cannot express (a button inside a
3055
+ // button, a link inside a link, a div inside a paragraph, a row without a
3056
+ // tbody). The viewer's parse would rewrite it, moving content and breaking
3057
+ // the positional nodeIds pairing. This pass renames such elements in the
3058
+ // DETACHED clone to <ps-node data-ps-tag="original-tag"> placeholders, which
3059
+ // the renderer restores right after its parse. It collects every element to
3060
+ // rename from the ORIGINAL clone structure first, then renames: each
3061
+ // placeholder takes the element's attributes, children, position and
3062
+ // cloneToNid entry, so element order and count are unchanged and the
3063
+ // nodeIds sidecar stays aligned. Renaming too much is harmless.
3064
+ //
3065
+ // options.rootContext: 'container' (snapshot body, frame body, shadow
3066
+ // container) never renames the root, and the root bounds every walk;
3067
+ // 'fragment' (add op and subtree response) evaluates the root too, and a
3068
+ // fragment-root table part is never stray, because the viewer's <template>
3069
+ // parse accepts table parts at its root. Returns the root to serialize,
3070
+ // which is the placeholder when a fragment root was renamed. It runs after
3071
+ // each site's last sanitizeForWire, so masking always sees original tags.
3072
+ function neutralizeParserHostileNesting(root, cloneToNid, options) {
3073
+ if (!root || typeof root.querySelectorAll !== 'function') return root;
3074
+ var opts = options || {};
3075
+ var fragment = opts.rootContext === 'fragment';
3076
+ var evaluated = fragment ? [root] : [];
3077
+ var descendants = root.querySelectorAll('*');
3078
+ for (var d = 0; d < descendants.length; d++) evaluated.push(descendants[d]);
3079
+
3080
+ function scopedParent(el) {
3081
+ if (!el || el === root) return null;
3082
+ var parent = el.parentElement;
3083
+ if (!parent) return null;
3084
+ if (parent === root) return fragment ? root : null;
3085
+ return parent;
3086
+ }
3087
+ function isHtmlIn(el, names) {
3088
+ return !!(el && el.namespaceURI === PARSER_SAFE_HTML_NAMESPACE && names && names[el.localName] === true);
3089
+ }
3090
+ function isHtmlTag(el, tag) {
3091
+ return !!(el && el.namespaceURI === PARSER_SAFE_HTML_NAMESPACE && el.localName === tag);
3092
+ }
3093
+ function hasNonWhitespaceText(el) {
3094
+ for (var n = el.firstChild; n; n = n.nextSibling) {
3095
+ if (n.nodeType === Node.TEXT_NODE && /[^ \t\n\f\r]/.test(n.data)) return true;
3096
+ }
3097
+ return false;
3098
+ }
3099
+ function stopsListWalk(el) {
3100
+ if (el.namespaceURI === PARSER_SAFE_HTML_NAMESPACE) {
3101
+ return PARSER_SAFE_SPECIAL[el.localName] === true && PARSER_SAFE_LIST_WALK_EXEMPT[el.localName] !== true;
3102
+ }
3103
+ if (el.namespaceURI === PARSER_SAFE_SVG_NAMESPACE) return PARSER_SAFE_SVG_INTEGRATION_POINTS[el.localName] === true;
3104
+ if (el.namespaceURI === PARSER_SAFE_MATHML_NAMESPACE) return PARSER_SAFE_MATHML_INTEGRATION_POINTS[el.localName] === true;
3105
+ return false;
3106
+ }
3107
+
3108
+ var marked = new Set();
3109
+ var renames = [];
3110
+ function mark(el) {
3111
+ if (marked.has(el)) return;
3112
+ marked.add(el);
3113
+ renames.push(el);
3114
+ }
3115
+ function markTablePartsUnder(node) {
3116
+ for (var c = node.firstElementChild; c; c = c.nextElementSibling) {
3117
+ if (isHtmlTag(c, 'table')) continue; // a nested table is judged on its own
3118
+ if (isHtmlIn(c, PARSER_SAFE_TABLE_PARTS)) mark(c);
3119
+ markTablePartsUnder(c);
3120
+ }
3121
+ }
3122
+ function markTable(start) {
3123
+ mark(start);
3124
+ markTablePartsUnder(start);
3125
+ }
3126
+
3127
+ // 1. A page-owned <ps-node> must never be upgraded by the viewer.
3128
+ for (var s = 0; s < evaluated.length; s++) {
3129
+ if (evaluated[s].localName === PARSER_SAFE_TAG) evaluated[s].removeAttribute(PARSER_SAFE_TAG_ATTR);
3130
+ }
3131
+
3132
+ // 2. Collect from the original structure (rules a-i).
3133
+ for (var e = 0; e < evaluated.length; e++) {
3134
+ var el = evaluated[e];
3135
+ if (el.namespaceURI !== PARSER_SAFE_HTML_NAMESPACE) continue;
3136
+ var tag = el.localName;
3137
+ var p = null;
3138
+ if (PARSER_SAFE_SAME_TAG[tag] === true) {
3139
+ for (p = scopedParent(el); p; p = scopedParent(p)) {
3140
+ if (isHtmlTag(p, tag)) { mark(el); break; }
3141
+ }
3142
+ }
3143
+ if (PARSER_SAFE_BLOCK_CLOSERS[tag] === true) {
3144
+ for (p = scopedParent(el); p; p = scopedParent(p)) {
3145
+ if (isHtmlTag(p, 'p')) mark(p);
3146
+ }
3147
+ }
3148
+ if (PARSER_SAFE_HEADINGS[tag] === true && isHtmlIn(scopedParent(el), PARSER_SAFE_HEADINGS)) mark(el);
3149
+ if (tag === 'li' || tag === 'dd' || tag === 'dt') {
3150
+ var listMatch = tag === 'li' ? PARSER_SAFE_LI : PARSER_SAFE_DD_DT;
3151
+ for (p = scopedParent(el); p; p = scopedParent(p)) {
3152
+ if (isHtmlIn(p, listMatch)) { mark(el); break; }
3153
+ if (stopsListWalk(p)) break;
3154
+ }
3155
+ }
3156
+ if ((tag === 'option' || tag === 'optgroup') && isHtmlTag(scopedParent(el), 'option')) mark(el);
3157
+ if (tag === 'optgroup' && isHtmlTag(scopedParent(el), 'optgroup')) mark(el);
3158
+ if (tag === 'select') {
3159
+ var selectDescendants = el.querySelectorAll('*');
3160
+ for (var sd = 0; sd < selectDescendants.length; sd++) {
3161
+ if (!isHtmlIn(selectDescendants[sd], PARSER_SAFE_SELECT_CONTENT)) { mark(el); break; }
3162
+ }
3163
+ }
3164
+ if (PARSER_SAFE_TEXT_ONLY[tag] === true && el.firstElementChild) mark(el);
3165
+ if (PARSER_SAFE_VOID[tag] === true && el.firstChild) mark(el);
3166
+ if (PARSER_SAFE_SHELL[tag] === true && el !== root) mark(el);
3167
+
3168
+ // 3. Tables (rule h). A table the parser would restructure is renamed
3169
+ // with all its table parts, stopping at nested tables.
3170
+ if (tag === 'table') {
3171
+ var badTable = hasNonWhitespaceText(el);
3172
+ for (var tc = el.firstElementChild; tc && !badTable; tc = tc.nextElementSibling) {
3173
+ if (isHtmlIn(tc, PARSER_SAFE_TABLE_CHILDREN)) continue;
3174
+ if (isHtmlTag(tc, 'input') && String(tc.getAttribute('type') || '').toLowerCase() === 'hidden') continue;
3175
+ badTable = true;
3176
+ }
3177
+ if (badTable) markTable(el);
3178
+ }
3179
+ if (PARSER_SAFE_TABLE_PARTS[tag] === true) {
3180
+ var partParent = scopedParent(el);
3181
+ if (!(fragment && el === root) && !isHtmlIn(partParent, PARSER_SAFE_VALID_PARENTS[tag])) {
3182
+ markTable(el); // a stray table part
3183
+ }
3184
+ var allowedChildren = PARSER_SAFE_PART_CHILDREN[tag];
3185
+ if (allowedChildren) {
3186
+ var badPart = hasNonWhitespaceText(el);
3187
+ for (var pc = el.firstElementChild; pc && !badPart; pc = pc.nextElementSibling) {
3188
+ if (!isHtmlIn(pc, allowedChildren)) badPart = true;
3189
+ }
3190
+ if (badPart) {
3191
+ // The nearest enclosing table, or the topmost part of the chain.
3192
+ var top = el;
3193
+ for (p = partParent; p; p = scopedParent(p)) {
3194
+ if (isHtmlTag(p, 'table')) { top = p; break; }
3195
+ if (isHtmlIn(p, PARSER_SAFE_TABLE_PARTS)) top = p;
3196
+ else break;
3197
+ }
3198
+ markTable(top);
3199
+ }
3200
+ }
3201
+ }
3202
+ }
3203
+
3204
+ // 4. Rename. Order and count of elements are unchanged.
3205
+ var result = root;
3206
+ for (var r = 0; r < renames.length; r++) {
3207
+ var original = renames[r];
3208
+ var placeholder = (original.ownerDocument || document).createElement(PARSER_SAFE_TAG);
3209
+ // The tag goes first, and a page-owned data-ps-tag on the original is
3210
+ // not copied, so it can never override the real tag.
3211
+ placeholder.setAttribute(PARSER_SAFE_TAG_ATTR, String(original.localName).toLowerCase());
3212
+ var attrs = original.attributes;
3213
+ for (var at = 0; at < attrs.length; at++) {
3214
+ if (String(attrs[at].name).toLowerCase() === PARSER_SAFE_TAG_ATTR) continue;
3215
+ try {
3216
+ placeholder.setAttribute(attrs[at].name, attrs[at].value);
3217
+ } catch (err) {
3218
+ try {
3219
+ placeholder.setAttributeNode(attrs[at].cloneNode(true));
3220
+ } catch (err2) { /* an attribute no element can carry is dropped */ }
3221
+ }
3222
+ }
3223
+ while (original.firstChild) placeholder.appendChild(original.firstChild);
3224
+ if (original.parentNode) {
3225
+ original.parentNode.replaceChild(placeholder, original);
3226
+ } else {
3227
+ result = placeholder;
3228
+ }
3229
+ if (cloneToNid && cloneToNid.has(original)) {
3230
+ cloneToNid.set(placeholder, cloneToNid.get(original));
3231
+ cloneToNid.delete(original);
3232
+ }
3233
+ }
3234
+ return result;
3235
+ }
3236
+
2355
3237
  function utf8ByteLength(text) {
2356
3238
  var str = String(text || '');
2357
3239
  var bytes = 0;
@@ -2443,7 +3325,7 @@ export function createCapture(config) {
2443
3325
  }));
2444
3326
  }
2445
3327
 
2446
- while (currentWireLength() > SNAPSHOT_BUDGET_BYTES && (keptShadowRoots.length || keptFrames.length)) {
3328
+ while (currentWireLength() > snapshotBudgetBytes && (keptShadowRoots.length || keptFrames.length)) {
2447
3329
  var largestKind = '';
2448
3330
  var largestIndex = -1;
2449
3331
  var largestLength = -1;
@@ -2510,68 +3392,101 @@ export function createCapture(config) {
2510
3392
  bodyAttrs: Object.assign({}, payload && payload.bodyAttrs ? payload.bodyAttrs : {})
2511
3393
  });
2512
3394
 
2513
- while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.inlineStyles.length) {
3395
+ // CSSOM mode carries full stylesheet text in styleSources; copy the array
3396
+ // so the budget passes below can prune it without mutating the caller's
3397
+ // sources. Only present in cssom mode -- computed mode omits the field.
3398
+ if (Array.isArray(next.styleSources)) {
3399
+ next.styleSources = next.styleSources.slice();
3400
+ }
3401
+
3402
+ // media[] (MEDIA-02) addresses nodes by nid; truncation can drop those nodes
3403
+ // from the clone. Copy the array so the prune below never mutates the
3404
+ // caller's baseline. Only present when the page had <video>/<audio>.
3405
+ if (Array.isArray(next.media)) {
3406
+ next.media = next.media.slice();
3407
+ }
3408
+
3409
+ while (wireByteLength(next) > snapshotBudgetBytes && next.inlineStyles.length) {
2514
3410
  next.inlineStyles.pop();
2515
3411
  markSnapshotPayloadTruncated(next);
2516
3412
  }
2517
- while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.stylesheets.length) {
3413
+ while (wireByteLength(next) > snapshotBudgetBytes && next.stylesheets.length) {
2518
3414
  next.stylesheets.pop();
2519
3415
  markSnapshotPayloadTruncated(next);
2520
3416
  }
3417
+ // A single large CSSOM source can dominate the payload; shed sources before
3418
+ // dropping DOM structure so an oversized stylesheet cannot blow the cap.
3419
+ while (wireByteLength(next) > snapshotBudgetBytes && Array.isArray(next.styleSources) && next.styleSources.length) {
3420
+ next.styleSources.pop();
3421
+ markSnapshotPayloadTruncated(next);
3422
+ }
2521
3423
 
2522
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.htmlStyle) {
3424
+ if (wireByteLength(next) > snapshotBudgetBytes && next.htmlStyle) {
2523
3425
  next.htmlStyle = '';
2524
3426
  markSnapshotPayloadTruncated(next);
2525
3427
  }
2526
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.bodyStyle) {
3428
+ if (wireByteLength(next) > snapshotBudgetBytes && next.bodyStyle) {
2527
3429
  next.bodyStyle = '';
2528
3430
  markSnapshotPayloadTruncated(next);
2529
3431
  }
2530
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Object.keys(next.htmlAttrs).length) {
3432
+ if (wireByteLength(next) > snapshotBudgetBytes && Object.keys(next.htmlAttrs).length) {
2531
3433
  next.htmlAttrs = {};
2532
3434
  markSnapshotPayloadTruncated(next);
2533
3435
  }
2534
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Object.keys(next.bodyAttrs).length) {
3436
+ if (wireByteLength(next) > snapshotBudgetBytes && Object.keys(next.bodyAttrs).length) {
2535
3437
  next.bodyAttrs = {};
2536
3438
  markSnapshotPayloadTruncated(next);
2537
3439
  }
2538
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.title) {
3440
+ if (wireByteLength(next) > snapshotBudgetBytes && next.title) {
2539
3441
  next.title = '';
2540
3442
  markSnapshotPayloadTruncated(next);
2541
3443
  }
2542
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.url) {
3444
+ if (wireByteLength(next) > snapshotBudgetBytes && next.url) {
2543
3445
  next.url = '';
2544
3446
  markSnapshotPayloadTruncated(next);
2545
3447
  }
2546
3448
 
2547
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && clone && cloneToNid) {
3449
+ if (wireByteLength(next) > snapshotBudgetBytes && clone && cloneToNid) {
2548
3450
  var cloneEls = cloneElementsWithNodeIds(clone, cloneToNid);
2549
- for (var i = cloneEls.length - 1; i >= 0 && wireByteLength(next) > SNAPSHOT_BUDGET_BYTES; i--) {
3451
+ for (var i = cloneEls.length - 1; i >= 0 && wireByteLength(next) > snapshotBudgetBytes; i--) {
2550
3452
  var nid = cloneToNid.get(cloneEls[i]);
2551
3453
  if (markCloneNidTruncated(clone, cloneToNid, nid, truncatedNodeIds)) {
2552
3454
  next.html = clone.innerHTML || '';
2553
3455
  next.nodeIds = buildNodeIdSidecar(clone, cloneToNid, false);
2554
3456
  next.shadowRoots = collectShadowRootPayloads(document.body, next.nodeIds, truncatedNodeIds);
2555
3457
  next.frames = collectFramePayloads(document.body, cloneToNid, truncatedNodeIds);
3458
+ // WR-02: a dropped <video>/<audio> subtree leaves a media[] baseline
3459
+ // entry that addresses a nid no longer in nodeIds. Re-derive media[]
3460
+ // against the freshly rebuilt sidecar so the baseline can never
3461
+ // reference a truncated node (and dead entries stop counting toward
3462
+ // the cap).
3463
+ pruneMediaToNodeIds(next);
2556
3464
  next.missingDescendants = (next.missingDescendants || 0) + 1;
2557
3465
  markSnapshotPayloadTruncated(next);
2558
3466
  }
2559
3467
  }
2560
3468
  }
2561
3469
 
2562
- if (wireByteLength(next) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
3470
+ if (wireByteLength(next) > messageLimitBytes) {
2563
3471
  next.html = '';
2564
3472
  next.nodeIds = [];
2565
3473
  next.shadowRoots = [];
2566
3474
  next.frames = [];
2567
3475
  next.inlineStyles = [];
2568
3476
  next.stylesheets = [];
3477
+ if (Array.isArray(next.styleSources)) next.styleSources = [];
2569
3478
  next.htmlAttrs = {};
2570
3479
  next.bodyAttrs = {};
2571
3480
  next.htmlStyle = '';
2572
3481
  next.bodyStyle = '';
2573
3482
  next.title = '';
2574
3483
  next.url = '';
3484
+ // WR-02: the hard reset empties every nid-addressed field; media[] must go
3485
+ // with them or an emptied snapshot would still ship a baseline that
3486
+ // addresses nodes nodeIds (now []) no longer contains. pruneMediaToNodeIds
3487
+ // filters against the now-empty sidecar, so media[] becomes [] (or stays
3488
+ // absent when the page had no media).
3489
+ pruneMediaToNodeIds(next);
2575
3490
  next.missingDescendants = (next.missingDescendants || 0) + 1;
2576
3491
  markSnapshotPayloadTruncated(next);
2577
3492
  }
@@ -2579,6 +3494,179 @@ export function createCapture(config) {
2579
3494
  return next;
2580
3495
  }
2581
3496
 
3497
+ /**
3498
+ * Prune a budget-fitted snapshot payload's media[] baseline to entries whose
3499
+ * nid is still present in the payload's nodeIds sidecar (WR-02). Truncation
3500
+ * (clone-subtree drop or the over-cap hard reset) re-derives nodeIds but the
3501
+ * media[] array is independent, so without this an entry can address a node
3502
+ * the snapshot no longer carries. No-op when media[] is absent (the common
3503
+ * media-free page -- the field stays unset, preserving wire byte-identity).
3504
+ * Compares String(nid) because ensureNodeId stamps string nids and nodeIds
3505
+ * holds those same strings (renderer applyMediaBaseline also keys on String).
3506
+ * @param {Object} payload The mutable budget-fitted payload (next).
3507
+ */
3508
+ function pruneMediaToNodeIds(payload) {
3509
+ if (!payload || !Array.isArray(payload.media)) return;
3510
+ var ids = Array.isArray(payload.nodeIds) ? payload.nodeIds : [];
3511
+ var live = new Set();
3512
+ for (var i = 0; i < ids.length; i++) live.add(String(ids[i]));
3513
+ payload.media = payload.media.filter(function (m) {
3514
+ return m && live.has(String(m.nid));
3515
+ });
3516
+ }
3517
+
3518
+ // =========================================================================
3519
+ // 0.45 MSEC-03 asset/media URL masking (plan 15-01)
3520
+ // =========================================================================
3521
+
3522
+ // Token/PII query-param denylist (documented in docs/SECURITY.md §4). When
3523
+ // maskAssetUrls is on, these param NAMES are stripped from asset/media URLs
3524
+ // before the wire -- credential/signature/expiry params only; functional
3525
+ // params (w, h, q, format, v, id, t, ...) survive. Matching is CASE-
3526
+ // INSENSITIVE and exact-name OR denied-prefix (TOKEN_PARAM_PREFIXES). The set
3527
+ // is lowercased so isTokenParamName can do a single lowercased membership
3528
+ // test. Provider param names are CITED from each signing scheme (AWS SigV4/
3529
+ // SigV2, GCP signed-URL V4, Azure SAS); the generic set is a reasoned default.
3530
+ var TOKEN_PARAM_DENYLIST = {
3531
+ // AWS S3 / CloudFront presigned (SigV4) -- the x-amz- prefix subsumes these
3532
+ // but they are kept explicit for documentation/audit clarity.
3533
+ 'x-amz-signature': 1, 'x-amz-credential': 1, 'x-amz-security-token': 1,
3534
+ 'x-amz-algorithm': 1, 'x-amz-date': 1, 'x-amz-expires': 1, 'x-amz-signedheaders': 1,
3535
+ // AWS S3 / CloudFront presigned (SigV2 / canned policy)
3536
+ 'awsaccesskeyid': 1, 'key-pair-id': 1, 'policy': 1,
3537
+ // Google Cloud Storage signed URL (V4) -- x-goog- prefix subsumes these.
3538
+ 'x-goog-signature': 1, 'x-goog-credential': 1, 'x-goog-algorithm': 1,
3539
+ 'x-goog-date': 1, 'x-goog-expires': 1, 'x-goog-signedheaders': 1, 'googleaccessid': 1,
3540
+ // Azure Blob SAS
3541
+ 'sig': 1, 'se': 1, 'sp': 1, 'sv': 1, 'sr': 1, 'st': 1, 'skoid': 1, 'sktid': 1,
3542
+ 'skt': 1, 'ske': 1, 'sks': 1, 'skv': 1, 'spr': 1, 'sip': 1, 'ss': 1, 'srt': 1,
3543
+ // Generic token/secret/auth/expiry
3544
+ 'token': 1, 'access_token': 1, 'auth': 1, 'authorization': 1, 'apikey': 1,
3545
+ 'api_key': 1, 'key': 1, 'signature': 1, 'sign': 1, 'hash': 1, 'hmac': 1,
3546
+ 'jwt': 1, 'password': 1, 'passwd': 1, 'pwd': 1, 'secret': 1, 'session': 1,
3547
+ 'sessionid': 1, 'sid': 1, 'expires': 1, 'expiry': 1
3548
+ };
3549
+ // Denied-name prefixes: any param whose lowercased name starts with one of
3550
+ // these is a token param (the AWS/GCP signed-URL families add provider-
3551
+ // specific x-amz-*/x-goog-* params beyond the explicit names above).
3552
+ var TOKEN_PARAM_PREFIXES = ['x-amz-', 'x-goog-'];
3553
+
3554
+ /**
3555
+ * True when a query-param name is a token/PII param to strip: lowercased
3556
+ * exact-set membership OR starts-with a denied prefix. Case-insensitive.
3557
+ * @param {string} name
3558
+ * @returns {boolean}
3559
+ */
3560
+ function isTokenParamName(name) {
3561
+ if (!name || typeof name !== 'string') return false;
3562
+ var lower = name.toLowerCase();
3563
+ if (TOKEN_PARAM_DENYLIST[lower] === 1) return true;
3564
+ for (var i = 0; i < TOKEN_PARAM_PREFIXES.length; i++) {
3565
+ if (lower.indexOf(TOKEN_PARAM_PREFIXES[i]) === 0) return true;
3566
+ }
3567
+ return false;
3568
+ }
3569
+
3570
+ /**
3571
+ * True when a URL fragment (the part after '#') carries a denied token param
3572
+ * (review WR-04). OAuth implicit flow returns tokens in the fragment
3573
+ * (#access_token=...); the fragment is never sent in the asset GET, but the
3574
+ * URL STRING crosses the relay to a possibly-cross-origin viewer, so a token
3575
+ * there is still a disclosure. We parse the fragment as a URLSearchParams and
3576
+ * report whether any name is denylisted. Empty / token-free fragments report
3577
+ * false so the no-strip byte-identity path is preserved (a plain `#section-2`
3578
+ * anchor never triggers a rewrite).
3579
+ * @param {string} hash - u.hash, including the leading '#' (or '')
3580
+ * @returns {boolean}
3581
+ */
3582
+ function fragmentHasTokenParam(hash) {
3583
+ if (!hash || hash.length < 2) return false; // '' or bare '#' -> no token
3584
+ var body = hash.charAt(0) === '#' ? hash.slice(1) : hash;
3585
+ if (body.indexOf('=') === -1) return false; // plain anchor, not key=value
3586
+ var fragParams;
3587
+ try { fragParams = new URLSearchParams(body); }
3588
+ catch (e) { return false; } // unparseable -> not a token map
3589
+ var found = false;
3590
+ fragParams.forEach(function (_v, k) { if (isTokenParamName(k)) found = true; });
3591
+ return found;
3592
+ }
3593
+
3594
+ /**
3595
+ * Strip the TOKEN_PARAM_DENYLIST params from a URL (the maskAssetUrls path).
3596
+ * PURE: parses with new URL() in try/catch (a non-absolute/opaque URL --
3597
+ * data:/blob:/relative -- throws and is returned UNCHANGED). Returns the
3598
+ * original `url` string when nothing was stripped (Pitfall 1: new URL()
3599
+ * .toString() normalizes host case / default port / trailing slash / percent-
3600
+ * encoding, which would diverge the wire even with masking effectively off for
3601
+ * this URL). Only emits u.toString() when a query param was deleted OR a
3602
+ * token-bearing fragment was dropped.
3603
+ *
3604
+ * Fragment handling (review WR-04): a token in the fragment
3605
+ * (#access_token=...) is not part of u.search, so the query strip never sees
3606
+ * it, yet the full URL string -- fragment included -- crosses the relay to a
3607
+ * possibly-cross-origin viewer. When the fragment carries a denylisted param
3608
+ * name we drop the WHOLE fragment (it is never needed for an asset/media
3609
+ * fetch); a benign anchor fragment (no '=', or no denied name) is left intact
3610
+ * so byte-identity holds on the no-strip path.
3611
+ * @param {string} url
3612
+ * @returns {string}
3613
+ */
3614
+ function stripTokenParams(url) {
3615
+ var u;
3616
+ try { u = new URL(url); }
3617
+ catch (e) { return url; } // non-absolute / opaque -> leave as-is
3618
+ var dropFragment = fragmentHasTokenParam(u.hash);
3619
+ // No query AND no token fragment -> unchanged (byte-identity). A token-only
3620
+ // fragment URL has no u.search, so the old `if (!u.search) return url` fast
3621
+ // path would have leaked it; gate the early return on the fragment too.
3622
+ if (!u.search && !dropFragment) return url;
3623
+ var changed = dropFragment;
3624
+ // Snapshot the keys first: URLSearchParams is live, deleting while iterating
3625
+ // skips entries. URLSearchParams preserves order and repeated keys.
3626
+ var keys = [];
3627
+ u.searchParams.forEach(function (_v, k) { keys.push(k); });
3628
+ for (var i = 0; i < keys.length; i++) {
3629
+ if (isTokenParamName(keys[i])) { u.searchParams.delete(keys[i]); changed = true; }
3630
+ }
3631
+ if (dropFragment) u.hash = ''; // redact the token-bearing fragment
3632
+ return changed ? u.toString() : url; // original string identity when untouched
3633
+ }
3634
+
3635
+ /**
3636
+ * PURE asset/media URL masking helper (MSEC-03). Decides the wire value for a
3637
+ * single URL attribute value: a custom redactor (maskAssetUrlFn) first, then
3638
+ * the boolean token-param strip (maskAssetUrls), else the URL UNCHANGED
3639
+ * (off-by-default -> byte-identical wire). NEVER reads the DOM or mutates a
3640
+ * clone -- the caller owns the clone mutation / placeholder swap.
3641
+ *
3642
+ * Fail-closed direction (Pitfall 3): maskAssetUrlFn mirrors safeMaskText's
3643
+ * try/catch but the catch returns null (BLOCK), not the asterisk default --
3644
+ * a thrown URL redactor is an undecided-unsafe URL, which must NOT be fetched.
3645
+ * @param {string} url
3646
+ * @param {{attr: string, tag: string, nid: string, kind: ('image'|'media')}} [ctx]
3647
+ * @returns {string|null} replacement URL, the unchanged URL, or null (block)
3648
+ */
3649
+ function maskAssetUrlForWire(url, ctx) {
3650
+ if (!url || typeof url !== 'string') return url;
3651
+ // 1. Custom redactor first -- full host control, FAIL CLOSED on throw.
3652
+ if (maskAssetUrlFn) {
3653
+ try {
3654
+ var out = maskAssetUrlFn(url, ctx || {});
3655
+ if (out === null) return null; // explicit block -> placeholder/remove
3656
+ return String(out); // redacted replacement
3657
+ } catch (err) {
3658
+ logger.error('[DOM Stream] maskAssetUrlFn failed; URL blocked (fail-closed)', err);
3659
+ return null; // THROW -> block (never raise, never pass raw)
3660
+ }
3661
+ }
3662
+ // 2. Boolean token/PII strip.
3663
+ if (maskAssetUrls) {
3664
+ return stripTokenParams(url);
3665
+ }
3666
+ // 3. Default OFF -> unchanged (byte-identical wire).
3667
+ return url;
3668
+ }
3669
+
2582
3670
  // =========================================================================
2583
3671
  // 0.5 SEC-01 Sanitization chokepoint
2584
3672
  // =========================================================================
@@ -2595,7 +3683,8 @@ export function createCapture(config) {
2595
3683
  blockedSubtrees: sanitizeCounters.blockedSubtrees,
2596
3684
  cssScrubs: sanitizeCounters.cssScrubs,
2597
3685
  maskedTextNodes: sanitizeCounters.maskedTextNodes,
2598
- maskedInputs: sanitizeCounters.maskedInputs
3686
+ maskedInputs: sanitizeCounters.maskedInputs,
3687
+ maskedAssetUrls: sanitizeCounters.maskedAssetUrls
2599
3688
  };
2600
3689
  }
2601
3690
 
@@ -2638,6 +3727,10 @@ export function createCapture(config) {
2638
3727
  // 5. E2 text-childlist branch -- 'text' dispatch (same seam)
2639
3728
  // 6. input/change value branch -- 'input' dispatch (CAPT-05
2640
3729
  // masking seam for event-driven form state)
3730
+ // Markup paths (1, 2 and the shadow-root, frame and subtree-response
3731
+ // clones) also run neutralizeParserHostileNesting AFTER their last
3732
+ // sanitizeForWire call: a structural rename (quick task 261202-jwf), never a
3733
+ // scrub, so masking and the URL and handler strips always see original tags.
2641
3734
  // Head inline <style> text additionally routes through the 'css' dispatch
2642
3735
  // at the serializeDOM collection site (a value scrub, not a markup walk).
2643
3736
  // Side channels that BYPASS the markup scrub AND the masking helpers BY
@@ -2737,6 +3830,32 @@ export function createCapture(config) {
2737
3830
  sanitizeCounters.blockedUrlSchemes++;
2738
3831
  }
2739
3832
  }
3833
+ // MSEC-03 asset/media URL masking (plan 15-01): route each SURVIVING
3834
+ // URL-attr value through the dedicated 'asset-url'/'media-url' dispatch
3835
+ // AFTER the scheme scrub (a hostile scheme is already gone, so it never
3836
+ // reaches maskAssetUrlForWire). Gated on the masking config so the
3837
+ // off-by-default path is wire-identical (no per-attr work, no string
3838
+ // churn). A null result BLOCKS -> remove the attribute (the viewer never
3839
+ // fetches it); a changed value replaces it. The live element is never
3840
+ // touched (clone-only, Phase 7 invariant).
3841
+ if (maskAssetUrls || maskAssetUrlFn) {
3842
+ var elNid = getTrackedNodeId(payload.orig) || '';
3843
+ for (var um = 0; um < URL_ATTRS.length; um++) {
3844
+ var maskAttr = URL_ATTRS[um];
3845
+ var maskVal = clone.getAttribute(maskAttr);
3846
+ if (!maskVal) continue;
3847
+ var maskKind = assetUrlKindForTag(tag);
3848
+ var maskRes = sanitizeForWire(maskKind === 'media' ? 'media-url' : 'asset-url', {
3849
+ value: maskVal,
3850
+ ctx: { attr: maskAttr, tag: tag, nid: elNid, kind: maskKind }
3851
+ });
3852
+ if (maskRes.value === null) {
3853
+ clone.removeAttribute(maskAttr);
3854
+ } else if (maskRes.value !== maskVal) {
3855
+ clone.setAttribute(maskAttr, maskRes.value);
3856
+ }
3857
+ }
3858
+ }
2740
3859
  var formactionVal = clone.getAttribute('formaction');
2741
3860
  if (formactionVal && hasDangerousScheme(formactionVal)) {
2742
3861
  clone.removeAttribute('formaction');
@@ -2828,7 +3947,10 @@ export function createCapture(config) {
2828
3947
  if (!root.contains(desc)) continue;
2829
3948
  if (liveDesc && wireDroppedWithAncestors(liveDesc.parentElement)) continue;
2830
3949
  if (liveDesc && blockedWithAncestors(liveDesc.parentElement)) continue;
2831
- if (liveDesc && blockMatches(liveDesc)) {
3950
+ if (liveDesc && maskMediaWithAncestors(liveDesc.parentElement)) continue;
3951
+ // blockSelector OR maskMediaSelector (MSEC-03): degrade the matched
3952
+ // element to the same dimension-only block placeholder.
3953
+ if (liveDesc && (blockMatches(liveDesc) || maskMediaMatches(liveDesc))) {
2832
3954
  replaceWithBlockPlaceholder(liveDesc, desc, readBlockRect(liveDesc), payload.cloneToNid);
2833
3955
  continue;
2834
3956
  }
@@ -2879,6 +4001,25 @@ export function createCapture(config) {
2879
4001
  sanitizeCounters.blockedUrlSchemes++;
2880
4002
  return { value: null };
2881
4003
  }
4004
+ // MSEC-03 asset/media URL masking (plan 15-01): the mutation 'attr' path's
4005
+ // URL values flow through the SAME dedicated dispatch after the scheme
4006
+ // scrub above. A null result becomes the inert ATTR-op shape ({ value:
4007
+ // null } -> diff.js removeAttribute), matching the dangerous-scheme branch.
4008
+ // Gated on config so off-by-default attr ops are byte-identical.
4009
+ if ((maskAssetUrls || maskAssetUrlFn)
4010
+ && URL_ATTRS.indexOf(attrName) !== -1 && payload.value) {
4011
+ var attrTag = (payload.target && payload.target.tagName)
4012
+ ? String(payload.target.tagName).toLowerCase() : '';
4013
+ var attrMaskKind = assetUrlKindForTag(attrTag);
4014
+ var attrMaskRes = sanitizeForWire(attrMaskKind === 'media' ? 'media-url' : 'asset-url', {
4015
+ value: payload.value,
4016
+ ctx: {
4017
+ attr: attrName, tag: attrTag,
4018
+ nid: getTrackedNodeId(payload.target) || '', kind: attrMaskKind
4019
+ }
4020
+ });
4021
+ return { value: attrMaskRes.value };
4022
+ }
2882
4023
  if (attrName === 'value' && (shouldMaskInput(payload.target) || isOptionUnderMaskedSelect(payload.target))) {
2883
4024
  var maskedAttrValue = safeMaskInput(payload.value == null ? '' : payload.value, payload.target);
2884
4025
  if (maskedAttrValue !== payload.value) {
@@ -2933,9 +4074,40 @@ export function createCapture(config) {
2933
4074
  return { css: scrubbedCss };
2934
4075
  }
2935
4076
 
4077
+ // MSEC-03 asset/media URL masking (plan 15-01). The single dedicated seam
4078
+ // for redacting/stripping/blocking a URL attribute value -- a thin wrapper
4079
+ // around the PURE maskAssetUrlForWire helper so URL masking lives in ONE
4080
+ // testable place rather than overloading the 'attr' path. 'asset-url' and
4081
+ // 'media-url' share one branch (the behavior is identical); the asset-vs-
4082
+ // media distinction travels in payload.ctx.kind ('image'|'media'). The
4083
+ // 'element' and 'attr' paths route their surviving URL-attr values through
4084
+ // this branch AFTER the hasDangerousScheme scrub (a hostile scheme is gone
4085
+ // before masking runs). Returns the same { value } discriminated shape as
4086
+ // 'attr'; value === null signals block -> the caller removes the attribute /
4087
+ // emits a placeholder.
4088
+ if (kind === 'asset-url' || kind === 'media-url') {
4089
+ var maskedUrl = maskAssetUrlForWire(payload.value, payload.ctx);
4090
+ if (maskedUrl !== payload.value) {
4091
+ sanitizeCounters.maskedAssetUrls++;
4092
+ }
4093
+ return { value: maskedUrl };
4094
+ }
4095
+
2936
4096
  return {};
2937
4097
  }
2938
4098
 
4099
+ /**
4100
+ * Map a tag name to the maskAssetUrlFn ctx.kind ('media' for the media
4101
+ * elements that carry a fetchable URL, 'image' for everything else -- <img>,
4102
+ * SVG <image>, <link>, <a>, ...). Used to build the ctx for the 'asset-url'/
4103
+ * 'media-url' dispatch so a host redactor can branch on asset-vs-media.
4104
+ * @param {string} tag lowercased tag name
4105
+ * @returns {('image'|'media')}
4106
+ */
4107
+ function assetUrlKindForTag(tag) {
4108
+ return (tag === 'video' || tag === 'audio' || tag === 'source') ? 'media' : 'image';
4109
+ }
4110
+
2939
4111
  // =========================================================================
2940
4112
  // 1. DOM Serializer
2941
4113
  // =========================================================================
@@ -3108,6 +4280,11 @@ export function createCapture(config) {
3108
4280
  // Elements to remove from clone (scripts, noscript, host-flagged elements)
3109
4281
  var toRemove = [];
3110
4282
  var blockedPairs = [];
4283
+ // ASST-04: clones whose absolutified asset refs are non-shareable
4284
+ // (blob:/oversized-data:). Collected during the walk, their live rects
4285
+ // read together below (single-pass layout discipline), then swapped for a
4286
+ // dimensioned placeholder after the walk -- exactly like blockedPairs.
4287
+ var assetUnavailablePairs = [];
3111
4288
 
3112
4289
  for (var i = 0; i < pairs.length; i++) {
3113
4290
  var orig = pairs[i].orig;
@@ -3149,14 +4326,19 @@ export function createCapture(config) {
3149
4326
  continue;
3150
4327
  }
3151
4328
 
3152
- // blockSelector: descendants of a blocked root get no nid assignment
3153
- // (the root swap discards the whole cloned subtree). The blocked root
3154
- // itself is still tracked, then replaced after this walk by a
3155
- // dimension-preserving placeholder whose identity travels in nodeIds.
3156
- if (blockedWithAncestors(orig.parentElement)) {
4329
+ // blockSelector / maskMediaSelector: descendants of a blocked OR masked
4330
+ // root get no nid assignment (the root swap discards the whole cloned
4331
+ // subtree). The root itself is still tracked, then replaced after this
4332
+ // walk by a dimension-preserving placeholder whose identity travels in
4333
+ // nodeIds. maskMediaSelector (MSEC-03) reuses the blockSelector placeholder
4334
+ // path verbatim so a masked <video>/<audio> degrades to the same identity-
4335
+ // only dimensioned <div> (A3: no distinct reason attr -- "masked" and
4336
+ // "blocked" are visually identical and the masked element legitimately
4337
+ // carries no identity-leaking attribute).
4338
+ if (blockedWithAncestors(orig.parentElement) || maskMediaWithAncestors(orig.parentElement)) {
3157
4339
  continue;
3158
4340
  }
3159
- if (blockMatches(orig)) {
4341
+ if (blockMatches(orig) || maskMediaMatches(orig)) {
3160
4342
  assignNodeId(orig, cl, cloneToNid);
3161
4343
  blockedPairs.push({ orig: orig, clone: cl });
3162
4344
  continue;
@@ -3213,6 +4395,29 @@ export function createCapture(config) {
3213
4395
  cl.setAttribute('srcset', absolutifySrcset(srcsetVal));
3214
4396
  }
3215
4397
 
4398
+ // ASST-04: detect non-shareable asset refs (blob:/oversized-data:) on the
4399
+ // already-absolutified clone. If the element degrades, record it for the
4400
+ // post-walk placeholder swap and skip the currentSrc enrich (the clone is
4401
+ // about to be replaced wholesale). The live element is never touched.
4402
+ var degradeReason = assetDegradeReason(cl);
4403
+ if (degradeReason) {
4404
+ assetUnavailablePairs.push({ orig: orig, clone: cl, reason: degradeReason });
4405
+ } else if (tag === 'img') {
4406
+ // ASST-03: clone-only data-ps-currentsrc variant pin. Enrich ONLY when
4407
+ // the live element's currentSrc is present AND differs from the
4408
+ // resolved src (a responsive srcset/<picture> negotiated a non-default
4409
+ // variant). currentSrc is set on the CLONE, never the live page
4410
+ // (Pitfall 4: preserves the Phase 7 no-mutation invariant). jsdom
4411
+ // returns currentSrc === "" so this never fires under unit/oracle tests
4412
+ // unless the scenario injects a divergent currentSrc.
4413
+ var resolvedCurrent = absolutifyUrl(orig.currentSrc || '');
4414
+ var resolvedSrc = cl.getAttribute('src') || '';
4415
+ if (currentSrcDiffers(resolvedCurrent, resolvedSrc)
4416
+ && !hasDangerousScheme(resolvedCurrent)) {
4417
+ cl.setAttribute('data-ps-currentsrc', resolvedCurrent);
4418
+ }
4419
+ }
4420
+
3216
4421
  // Capture generated computed styles only in the default compatibility mode.
3217
4422
  if (styleMode !== 'cssom') captureComputedStyles(orig, cl);
3218
4423
 
@@ -3231,6 +4436,12 @@ export function createCapture(config) {
3231
4436
  for (var bp = 0; bp < blockedPairs.length; bp++) {
3232
4437
  blockedRects.push(readBlockRect(blockedPairs[bp].orig));
3233
4438
  }
4439
+ // ASST-04: read non-shareable asset rects in the same single-pass region
4440
+ // (dimensions from the ORIG live element, never the detached clone).
4441
+ var assetUnavailableRects = [];
4442
+ for (var ap = 0; ap < assetUnavailablePairs.length; ap++) {
4443
+ assetUnavailableRects.push(readBlockRect(assetUnavailablePairs[ap].orig));
4444
+ }
3234
4445
 
3235
4446
  // Remove marked elements
3236
4447
  for (var r = 0; r < toRemove.length; r++) {
@@ -3242,6 +4453,21 @@ export function createCapture(config) {
3242
4453
  for (var br = 0; br < blockedPairs.length; br++) {
3243
4454
  replaceWithBlockPlaceholder(blockedPairs[br].orig, blockedPairs[br].clone, blockedRects[br], cloneToNid);
3244
4455
  }
4456
+ // ASST-04: swap each non-shareable asset clone for its dimensioned
4457
+ // placeholder, transferring the nid (clone-only; live page untouched).
4458
+ for (var aur = 0; aur < assetUnavailablePairs.length; aur++) {
4459
+ replaceWithAssetUnavailablePlaceholder(
4460
+ assetUnavailablePairs[aur].orig,
4461
+ assetUnavailablePairs[aur].clone,
4462
+ assetUnavailableRects[aur],
4463
+ assetUnavailablePairs[aur].reason,
4464
+ cloneToNid
4465
+ );
4466
+ }
4467
+
4468
+ // Parser-safe serialization (quick task 261202-jwf): after the last
4469
+ // sanitizeForWire and the placeholder swaps, before html and nodeIds.
4470
+ neutralizeParserHostileNesting(clone, cloneToNid, { rootContext: 'container' });
3245
4471
 
3246
4472
  // Collect stylesheet URLs from document.head
3247
4473
  var stylesheets = collectStylesheetsFrom(document);
@@ -3288,10 +4514,11 @@ export function createCapture(config) {
3288
4514
  }
3289
4515
  } catch (e) { /* TreeWalker unavailable in this realm; truncation falls back to no-op */ }
3290
4516
 
3291
- // SNAPSHOT_BUDGET_BYTES is the imported 80%-of-relay-cap budget. Compare
3292
- // UTF-8 wire bytes, not UTF-16 code units, so non-ASCII snapshots respect
3293
- // the relay's byte cap.
3294
- if (wireByteLength(html) > SNAPSHOT_BUDGET_BYTES) {
4517
+ // snapshotBudgetBytes is this instance's snapshot budget: by default the
4518
+ // imported 80%-of-relay-cap SNAPSHOT_BUDGET_BYTES, or the host's
4519
+ // snapshotBudgetBytes option (quick task 261202-jwf). Compare UTF-8 wire
4520
+ // bytes, not UTF-16 code units, so non-ASCII snapshots respect the byte cap.
4521
+ if (wireByteLength(html) > snapshotBudgetBytes) {
3295
4522
  truncated = true;
3296
4523
  var viewportCutoff = window.innerHeight * TRUNCATION_VIEWPORT_MULTIPLIER;
3297
4524
 
@@ -3318,9 +4545,9 @@ export function createCapture(config) {
3318
4545
  // elements in document order and drops complete subtrees until under
3319
4546
  // cap. Only complete subtrees are removed -- never a mid-element cut.
3320
4547
  html = clone.innerHTML;
3321
- if (wireByteLength(html) > SNAPSHOT_BUDGET_BYTES) {
4548
+ if (wireByteLength(html) > snapshotBudgetBytes) {
3322
4549
  var cloneEls2 = cloneElementsWithNodeIds(clone, cloneToNid);
3323
- for (var u = cloneEls2.length - 1; u >= 0 && wireByteLength(clone.innerHTML) > SNAPSHOT_BUDGET_BYTES; u--) {
4550
+ for (var u = cloneEls2.length - 1; u >= 0 && wireByteLength(clone.innerHTML) > snapshotBudgetBytes; u--) {
3324
4551
  var placeholder2 = replaceWithTruncatedPlaceholder(cloneEls2[u], cloneToNid);
3325
4552
  if (placeholder2) {
3326
4553
  var placeholderNid2 = cloneToNid.get(placeholder2);
@@ -3343,6 +4570,7 @@ export function createCapture(config) {
3343
4570
  var budgetInput = {
3344
4571
  html: html,
3345
4572
  nodeIds: nodeIds,
4573
+ bodyNid: BODY_NID,
3346
4574
  truncated: truncated,
3347
4575
  missingDescendants: missingDescendants,
3348
4576
  stylesheets: stylesheets,
@@ -3384,6 +4612,7 @@ export function createCapture(config) {
3384
4612
  var snapshotPayload = {
3385
4613
  html: html,
3386
4614
  nodeIds: nodeIds,
4615
+ bodyNid: BODY_NID,
3387
4616
  shadowRoots: shadowRoots,
3388
4617
  frames: frames,
3389
4618
  truncated: truncated,
@@ -3409,7 +4638,31 @@ export function createCapture(config) {
3409
4638
  snapshotPayload.styleSources = documentCssom.sources;
3410
4639
  snapshotPayload.styleStrategy = documentCssom.strategy;
3411
4640
  }
3412
- return fitSnapshotPayloadForBudget(snapshotPayload, clone, cloneToNid, truncatedNodeIds);
4641
+ // MEDIA-02 / MEDIA-04: append a media[] playback-state baseline keyed by
4642
+ // nid -- one entry per tracked <video>/<audio> in document order, read from
4643
+ // the LIVE DOM. This mirrors the DIFF_OP.VALUE side-channel precedent
4644
+ // (live property state travels keyed by nid, never baked into the clone),
4645
+ // so payload.html stays byte-identical (differential-oracle invariant) and
4646
+ // the live page is never mutated (Phase 7 capture-no-mutation invariant).
4647
+ // The media[] key is added ONLY when at least one <video>/<audio> exists.
4648
+ // A media-free page emits NO media key at all, so existing fixtures stay
4649
+ // byte-identical to the FSB reference and the differential oracle needs no
4650
+ // new ledger entry yet (RESEARCH A4 / Pitfall 7 -- the ledger entry + media
4651
+ // fixture land with Plan 13-04, once a fixture instantiates media).
4652
+ var trackedMedia = collectTrackedMediaElements();
4653
+ if (trackedMedia.length > 0) {
4654
+ snapshotPayload.media = trackedMedia.map(buildMediaBaselineEntry);
4655
+ }
4656
+ var fitted = fitSnapshotPayloadForBudget(snapshotPayload, clone, cloneToNid, truncatedNodeIds);
4657
+ // WR-02: media[] is read from the LIVE DOM, so it carries an entry for a
4658
+ // <video>/<audio> even when its clone subtree was dropped by ANY truncation
4659
+ // pass -- the serializeDOM below-fold/over-cap pre-pass (above), the sidecar
4660
+ // prune, the budget loop, or the over-cap hard reset. Reconcile media[]
4661
+ // against the FINAL nodeIds here (the single point every pass funnels
4662
+ // through) so the emitted baseline can never address a node nodeIds no
4663
+ // longer contains. No-op for a media-free page (media stays absent).
4664
+ pruneMediaToNodeIds(fitted);
4665
+ return fitted;
3413
4666
  }
3414
4667
 
3415
4668
  // =========================================================================
@@ -3504,6 +4757,50 @@ export function createCapture(config) {
3504
4757
  appendStyleDeclaration(cloneDescendants[c], descStyleText);
3505
4758
  }
3506
4759
  }
4760
+
4761
+ // ASST-03/04 on the added-node path. CRITICAL (Pitfall 4): the live node
4762
+ // was mutated above for URL absolutify (reference parity), but the
4763
+ // currentSrc enrich and the asset-unavailable degrade land on the
4764
+ // wireClone ONLY -- never the live node, so the framework attributes never
4765
+ // leak to the observed page. Descendants first (parent-replacement is safe
4766
+ // on the detached clone), then the root.
4767
+ for (var ce = 0; ce < liveDescendants.length; ce++) {
4768
+ var liveDesc2 = liveDescendants[ce];
4769
+ var cloneDesc2 = cloneDescendants[ce];
4770
+ if (!cloneDesc2) continue;
4771
+ var descReason = assetDegradeReason(cloneDesc2);
4772
+ if (descReason) {
4773
+ replaceWithAssetUnavailablePlaceholder(
4774
+ liveDesc2, cloneDesc2, readBlockRect(liveDesc2), descReason, cloneToNid
4775
+ );
4776
+ } else if (cloneDesc2.tagName && String(cloneDesc2.tagName).toLowerCase() === 'img') {
4777
+ var descCurrent = absolutifyUrl(liveDesc2.currentSrc || '', liveDesc2.ownerDocument || baseDoc);
4778
+ var descSrc = cloneDesc2.getAttribute('src') || '';
4779
+ if (currentSrcDiffers(descCurrent, descSrc) && !hasDangerousScheme(descCurrent)) {
4780
+ cloneDesc2.setAttribute('data-ps-currentsrc', descCurrent);
4781
+ }
4782
+ }
4783
+ }
4784
+ // Root: the detached wireClone has no parent, so a degrade swaps the
4785
+ // reference held by `wireClone` (preserving rootNid in cloneToNid) rather
4786
+ // than calling replaceWithAssetUnavailablePlaceholder.
4787
+ var rootReason = assetDegradeReason(wireClone);
4788
+ if (rootReason) {
4789
+ var rootPlaceholder = createAssetUnavailablePlaceholder(
4790
+ wireClone.ownerDocument || document, readBlockRect(el), rootReason
4791
+ );
4792
+ cloneToNid.delete(wireClone);
4793
+ if (rootNid) cloneToNid.set(rootPlaceholder, rootNid);
4794
+ sanitizeCounters.blockedSubtrees++;
4795
+ wireClone = rootPlaceholder;
4796
+ } else if (rootTag === 'img') {
4797
+ var rootCurrent = absolutifyUrl(el.currentSrc || '', baseDoc);
4798
+ var rootSrc = wireClone.getAttribute('src') || '';
4799
+ if (currentSrcDiffers(rootCurrent, rootSrc) && !hasDangerousScheme(rootCurrent)) {
4800
+ wireClone.setAttribute('data-ps-currentsrc', rootCurrent);
4801
+ }
4802
+ }
4803
+
3507
4804
  prepareIframeWireShellsForClone(el, wireClone);
3508
4805
  var subtreeResult = sanitizeForWire('subtree', {
3509
4806
  root: wireClone,
@@ -3511,6 +4808,8 @@ export function createCapture(config) {
3511
4808
  cloneToNid: cloneToNid
3512
4809
  });
3513
4810
  if (subtreeResult && subtreeResult.drop) return null;
4811
+ // Also serves subtree-fetch responses (serializeRequestedSubtree).
4812
+ wireClone = neutralizeParserHostileNesting(wireClone, cloneToNid, { rootContext: 'fragment' });
3514
4813
  var nodeIds = buildNodeIdSidecar(wireClone, cloneToNid, true);
3515
4814
  var shadowRoots = collectShadowRootPayloads(el, nodeIds);
3516
4815
  var frames = collectFramePayloads(el, cloneToNid);
@@ -3590,7 +4889,7 @@ export function createCapture(config) {
3590
4889
  streamSessionId: streamSessionId || '',
3591
4890
  snapshotId: currentSnapshotId || 0
3592
4891
  }, result);
3593
- if (response.status === 'ok' && wireByteLength(response) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
4892
+ if (response.status === 'ok' && wireByteLength(response) > messageLimitBytes) {
3594
4893
  response = Object.assign({
3595
4894
  requestId: request && request.requestId != null ? String(request.requestId) : '',
3596
4895
  nid: request && request.nid != null ? String(request.nid) : '',
@@ -3689,7 +4988,7 @@ export function createCapture(config) {
3689
4988
  if (wireDroppedWithAncestors(added.parentElement)) continue;
3690
4989
  if (blockedWithAncestors(added.parentElement)) continue;
3691
4990
 
3692
- var parentNid = getTrackedNodeId(m.target);
4991
+ var parentNid = mutationTargetNid(m.target);
3693
4992
  if (!parentNid) continue; // Parent not tracked
3694
4993
 
3695
4994
  var addedPayload = processAddedNode(added);
@@ -3711,6 +5010,10 @@ export function createCapture(config) {
3711
5010
  frames: addedPayload.frames || []
3712
5011
  }, frameRecord);
3713
5012
  diffs.push(boundMutationDiffForBudget(addDiff));
5013
+ // STREAM.MEDIA: a mutation-added <video>/<audio> (or a subtree
5014
+ // containing one) must receive listeners -- media events do not
5015
+ // bubble, so they are not caught by any delegated handler.
5016
+ attachMediaListenersUnder(added);
3714
5017
  } else if (added.nodeType === Node.TEXT_NODE || added.nodeType === Node.CDATA_SECTION_NODE) {
3715
5018
  sawBareTextNode = true;
3716
5019
  }
@@ -3720,6 +5023,10 @@ export function createCapture(config) {
3720
5023
  for (var r = 0; r < m.removedNodes.length; r++) {
3721
5024
  var removed = m.removedNodes[r];
3722
5025
  if (removed.nodeType === Node.ELEMENT_NODE) {
5026
+ // STREAM.MEDIA: release listeners for a removed <video>/<audio>
5027
+ // subtree before any wire-drop short-circuit, so a tracked media
5028
+ // element can never emit after it leaves the live DOM.
5029
+ detachMediaListenersUnder(removed);
3723
5030
  if (wireDroppedWithAncestors(removed)) continue;
3724
5031
  var nid = getTrackedNodeId(removed);
3725
5032
  if (!nid) continue; // Not tracked
@@ -3776,8 +5083,13 @@ export function createCapture(config) {
3776
5083
  && (attrNameLower === 'href' || attrNameLower === 'media' || attrNameLower === 'disabled')) {
3777
5084
  markStyleOwnerDirty(m.target, 'link-attr-mutated');
3778
5085
  }
3779
- var targetNid = getTrackedNodeId(m.target);
5086
+ var targetNid = mutationTargetNid(m.target);
3780
5087
  if (!targetNid) continue;
5088
+ // The snapshot's computed shell bodyStyle owns the mirror body's style
5089
+ // attribute (serializeShellAttributes already excludes style), so a
5090
+ // raw style op on the body would overwrite it with the page's inline
5091
+ // declarations only. Body style changes are never streamed.
5092
+ if (targetNid === BODY_NID && attrNameLower === 'style') continue;
3781
5093
 
3782
5094
  if (attrTargetTag === 'iframe' && attrNameLower === 'src') {
3783
5095
  registerFrameLoadListener(m.target, targetNid);
@@ -3793,6 +5105,28 @@ export function createCapture(config) {
3793
5105
  attrVal = absolutifySrcset(attrVal, m.target.ownerDocument);
3794
5106
  }
3795
5107
 
5108
+ // ASST-04: a mutation that sets src/poster/srcset to a non-shareable
5109
+ // ref (blob:/oversized-data:) must NOT ship the dead reference. Drop
5110
+ // the offending URL from the wire (empty value) and emit a sibling
5111
+ // data-ps-asset-unavailable op so the viewer shows the dimensioned
5112
+ // placeholder instead of fetching a dead ref. The live element is
5113
+ // unchanged (we only shape the wire diff).
5114
+ var attrIsAssetUrl = (attrNameLower === 'src' || attrNameLower === 'poster' || attrNameLower === 'srcset');
5115
+ if (attrIsAssetUrl && attrVal) {
5116
+ var mutClass = (attrNameLower === 'srcset')
5117
+ ? assetDegradeReasonForSrcset(attrVal)
5118
+ : (function () { var c = classifyAssetRef(attrVal, ASSET_DATA_URI_MAX_BYTES); return c.ok ? '' : c.reason; })();
5119
+ if (mutClass) {
5120
+ diffs.push(scopeFrameDiff({
5121
+ op: 'attr',
5122
+ nid: targetNid,
5123
+ attr: 'data-ps-asset-unavailable',
5124
+ val: mutClass
5125
+ }, frameRecord));
5126
+ attrVal = '';
5127
+ }
5128
+ }
5129
+
3796
5130
  // SEC-01: route through the chokepoint AFTER absolutification so
3797
5131
  // the scheme check runs on final wire values (Pitfall 5: this
3798
5132
  // branch was the snapshot sanitizer's bypass).
@@ -3946,13 +5280,13 @@ export function createCapture(config) {
3946
5280
 
3947
5281
  function boundMutationDiffForBudget(diff, options) {
3948
5282
  if (!diff) return null;
3949
- if (wireByteLength(mutationPayloadForBudget([diff], options)) <= RELAY_PER_MESSAGE_LIMIT_BYTES) return diff;
5283
+ if (wireByteLength(mutationPayloadForBudget([diff], options)) <= messageLimitBytes) return diff;
3950
5284
  var bounded = null;
3951
5285
  if (diff.op === DIFF_OP.ADD) bounded = boundedAddPlaceholder(diff);
3952
5286
  if (diff.op === DIFF_OP.FRAME) bounded = boundedFramePlaceholder(diff);
3953
5287
  if (diff.op === DIFF_OP.SHADOW_ROOT) bounded = boundedShadowRootPlaceholder(diff);
3954
5288
  if (!bounded) return null;
3955
- return wireByteLength(mutationPayloadForBudget([bounded], options)) <= RELAY_PER_MESSAGE_LIMIT_BYTES
5289
+ return wireByteLength(mutationPayloadForBudget([bounded], options)) <= messageLimitBytes
3956
5290
  ? bounded
3957
5291
  : null;
3958
5292
  }
@@ -3971,14 +5305,14 @@ export function createCapture(config) {
3971
5305
  continue;
3972
5306
  }
3973
5307
  var singlePayload = mutationPayloadForBudget([diff], options);
3974
- if (wireByteLength(singlePayload) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
5308
+ if (wireByteLength(singlePayload) > messageLimitBytes) {
3975
5309
  logger.warn('[DOM Stream] mutation diff dropped over budget', {
3976
5310
  op: diff && diff.op ? diff.op : ''
3977
5311
  });
3978
5312
  continue;
3979
5313
  }
3980
5314
  var nextChunk = chunk.concat([diff]);
3981
- if (chunk.length && wireByteLength(mutationPayloadForBudget(nextChunk, options)) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
5315
+ if (chunk.length && wireByteLength(mutationPayloadForBudget(nextChunk, options)) > messageLimitBytes) {
3982
5316
  safeSend(STREAM.MUTATIONS, mutationPayloadForBudget(chunk, options));
3983
5317
  chunk = [diff];
3984
5318
  } else {
@@ -4187,6 +5521,231 @@ export function createCapture(config) {
4187
5521
  logger.info('[DOM Stream] Scroll tracker stopped');
4188
5522
  }
4189
5523
 
5524
+ // =========================================================================
5525
+ // 3.5 Media Tracker (STREAM.MEDIA -- scroll-twin side channel)
5526
+ // =========================================================================
5527
+
5528
+ /**
5529
+ * Every <video>/<audio> currently in the live document, in document order.
5530
+ * Read from the LIVE DOM only (never the clone) so the media[] baseline and
5531
+ * tracker walk the same real elements capture sees.
5532
+ * @returns {HTMLMediaElement[]}
5533
+ */
5534
+ function collectTrackedMediaElements() {
5535
+ var out = [];
5536
+ if (!document || typeof document.querySelectorAll !== 'function') return out;
5537
+ var nodes = document.querySelectorAll('video, audio');
5538
+ for (var i = 0; i < nodes.length; i++) {
5539
+ // WR-01: a <video>/<audio> the host excludes (skipElement / a blocked or
5540
+ // wire-dropped ancestor -- e.g. the host's own viewer UI in a same-page
5541
+ // loopback mirror) must NOT be media-tracked. The value tracker already
5542
+ // gates on these predicates (buildValueDiff); the media baseline now
5543
+ // matches so a deliberately-excluded element emits no media[] entry.
5544
+ if (skipElementWithAncestors(nodes[i])
5545
+ || blockedWithAncestors(nodes[i])
5546
+ || wireDroppedWithAncestors(nodes[i])
5547
+ || maskMediaWithAncestors(nodes[i])) {
5548
+ continue;
5549
+ }
5550
+ out.push(nodes[i]);
5551
+ }
5552
+ return out;
5553
+ }
5554
+
5555
+ /**
5556
+ * Build one MediaBaselineEntry (MEDIA-02/MEDIA-04) from a LIVE media element.
5557
+ * Reads playback-state properties only; assigns/reuses the element nid via
5558
+ * ensureNodeId so the renderer can address it. NEVER writes an attribute on
5559
+ * the element (Phase 7 no-mutation invariant) and NEVER touches the clone.
5560
+ *
5561
+ * duration|live are mutually exclusive: a finite duration is sent as-is; a
5562
+ * non-finite duration (live stream / unloaded element) sets live:true and
5563
+ * omits duration, closing the JSON Infinity->null trap (13-RESEARCH Pitfall
5564
+ * 2) so the reconciler branches on live before any duration arithmetic.
5565
+ * @param {HTMLMediaElement} el
5566
+ * @returns {import('../protocol/messages.js').MediaBaselineEntry}
5567
+ */
5568
+ function buildMediaBaselineEntry(el) {
5569
+ var entry = {
5570
+ nid: ensureNodeId(el),
5571
+ currentTime: el.currentTime,
5572
+ paused: !!el.paused,
5573
+ muted: !!el.muted,
5574
+ volume: el.volume,
5575
+ playbackRate: el.playbackRate,
5576
+ loop: !!el.loop,
5577
+ ended: !!el.ended
5578
+ };
5579
+ if (isFinite(el.duration)) entry.duration = el.duration;
5580
+ else entry.live = true;
5581
+ return entry;
5582
+ }
5583
+
5584
+ /**
5585
+ * Build a MediaSyncPayload from a LIVE media element and emit it on the wire
5586
+ * (MWIRE-01). The payload is the baseline entry enriched with the triggering
5587
+ * event name, a capture-side sentAt latency stamp, and the stream identity
5588
+ * stamps so the renderer's isCurrentStream guard rejects stale cross-
5589
+ * generation frames. nid reuses the tracked id (or assigns one). No media
5590
+ * BYTES are ever sent -- only nid-addressed playback state (T-13-05).
5591
+ * @param {HTMLMediaElement} el
5592
+ * @param {string} eventName
5593
+ */
5594
+ function sendMediaState(el, eventName) {
5595
+ var payload = {
5596
+ nid: getTrackedNodeId(el) || ensureNodeId(el),
5597
+ event: eventName,
5598
+ currentTime: el.currentTime,
5599
+ paused: !!el.paused,
5600
+ muted: !!el.muted,
5601
+ volume: el.volume,
5602
+ playbackRate: el.playbackRate,
5603
+ loop: !!el.loop,
5604
+ ended: !!el.ended,
5605
+ sentAt: Date.now(),
5606
+ streamSessionId: streamSessionId || '',
5607
+ snapshotId: currentSnapshotId || 0
5608
+ };
5609
+ if (isFinite(el.duration)) payload.duration = el.duration;
5610
+ else payload.live = true;
5611
+ safeSend(STREAM.MEDIA, payload);
5612
+ }
5613
+
5614
+ /**
5615
+ * Attach per-element media listeners to one <video>/<audio>. Discrete
5616
+ * transition events flush a STREAM.MEDIA immediately; timeupdate is the
5617
+ * throttled drift heartbeat -- it returns early while paused (heartbeat is
5618
+ * playing-only) then applies a per-element MEDIA_SYNC_THROTTLE_MS gate
5619
+ * (mirrors the scroll tracker's now-lastSend timestamp check), bounding the
5620
+ * 1 MiB-capped relay against timeupdate flooding (T-13-06). Idempotent:
5621
+ * re-attaching a tracked element is a no-op (added-node + startMediaTracker
5622
+ * can both reach the same element).
5623
+ * @param {Element} el
5624
+ */
5625
+ function attachMediaListeners(el) {
5626
+ if (!mediaTrackingActive || !el || el.nodeType !== Node.ELEMENT_NODE) return;
5627
+ if (typeof el.addEventListener !== 'function') return;
5628
+ var tag = el.tagName ? String(el.tagName).toLowerCase() : '';
5629
+ if (tag !== 'video' && tag !== 'audio') return;
5630
+ // WR-01 / MSEC-03: never track a host-excluded OR masked media element. This
5631
+ // is the chokepoint every attach path funnels through (startMediaTracker, the
5632
+ // added-node path, attachMediaListenersUnder), so gating here guarantees a
5633
+ // skipped/blocked/wire-dropped/masked <video>/<audio> emits no STREAM.MEDIA
5634
+ // frames -- matching the value tracker's exclusion (buildValueDiff) so the
5635
+ // wire never leaks the play/pause/seek timeline of deliberately-excluded
5636
+ // host-UI media or maskMediaSelector-redacted private media.
5637
+ if (skipElementWithAncestors(el) || blockedWithAncestors(el)
5638
+ || wireDroppedWithAncestors(el) || maskMediaWithAncestors(el)) return;
5639
+ if (mediaTracked.has(el)) return;
5640
+
5641
+ var record = { lastMediaSend: 0, handlers: {} };
5642
+
5643
+ // Discrete transition events: emit immediately (coalesced by the browser's
5644
+ // own one-event-per-transition delivery).
5645
+ var discrete = ['play', 'pause', 'seeked', 'ratechange', 'ended', 'volumechange', 'loadedmetadata'];
5646
+ for (var i = 0; i < discrete.length; i++) {
5647
+ (function (name) {
5648
+ var handler = function () {
5649
+ if (!mediaTrackingActive) return;
5650
+ sendMediaState(el, name);
5651
+ };
5652
+ record.handlers[name] = handler;
5653
+ el.addEventListener(name, handler);
5654
+ })(discrete[i]);
5655
+ }
5656
+
5657
+ // timeupdate: throttled drift heartbeat, only while playing.
5658
+ var timeupdateHandler = function () {
5659
+ if (!mediaTrackingActive) return;
5660
+ if (el.paused) return; // heartbeat is playing-only
5661
+ var now = Date.now();
5662
+ if (now - record.lastMediaSend < MEDIA_SYNC_THROTTLE_MS) return;
5663
+ record.lastMediaSend = now;
5664
+ sendMediaState(el, 'timeupdate');
5665
+ };
5666
+ record.handlers.timeupdate = timeupdateHandler;
5667
+ el.addEventListener('timeupdate', timeupdateHandler);
5668
+
5669
+ mediaTracked.set(el, record);
5670
+ mediaTrackedRecords.push(el);
5671
+ }
5672
+
5673
+ /**
5674
+ * Detach the media listeners from one element and forget it. Safe on an
5675
+ * untracked element (no-op). Called on element removal and on teardown.
5676
+ * @param {Element} el
5677
+ */
5678
+ function detachMediaListeners(el) {
5679
+ var record = mediaTracked.get(el);
5680
+ if (!record) return;
5681
+ if (typeof el.removeEventListener === 'function') {
5682
+ for (var name in record.handlers) {
5683
+ if (Object.prototype.hasOwnProperty.call(record.handlers, name)) {
5684
+ el.removeEventListener(name, record.handlers[name]);
5685
+ }
5686
+ }
5687
+ }
5688
+ mediaTracked.delete(el);
5689
+ var idx = mediaTrackedRecords.indexOf(el);
5690
+ if (idx !== -1) mediaTrackedRecords.splice(idx, 1);
5691
+ }
5692
+
5693
+ /**
5694
+ * Attach media listeners to a root (if it is a media element) and to every
5695
+ * <video>/<audio> descendant. Used by the added-node mutation path so a
5696
+ * mutation-inserted media element (or a subtree containing one) is tracked.
5697
+ * @param {Element} root
5698
+ */
5699
+ function attachMediaListenersUnder(root) {
5700
+ if (!mediaTrackingActive || !root || root.nodeType !== Node.ELEMENT_NODE) return;
5701
+ var tag = root.tagName ? String(root.tagName).toLowerCase() : '';
5702
+ if (tag === 'video' || tag === 'audio') attachMediaListeners(root);
5703
+ if (typeof root.querySelectorAll !== 'function') return;
5704
+ var nested = root.querySelectorAll('video, audio');
5705
+ for (var i = 0; i < nested.length; i++) attachMediaListeners(nested[i]);
5706
+ }
5707
+
5708
+ /**
5709
+ * Detach media listeners from a removed root and any tracked <video>/<audio>
5710
+ * descendant. Used by the removed-node mutation path so a detached subtree's
5711
+ * media listeners are released (no leak, no post-removal emissions).
5712
+ * @param {Element} root
5713
+ */
5714
+ function detachMediaListenersUnder(root) {
5715
+ if (!root || root.nodeType !== Node.ELEMENT_NODE) return;
5716
+ detachMediaListeners(root);
5717
+ if (typeof root.querySelectorAll !== 'function') return;
5718
+ var nested = root.querySelectorAll('video, audio');
5719
+ for (var i = 0; i < nested.length; i++) detachMediaListeners(nested[i]);
5720
+ }
5721
+
5722
+ /**
5723
+ * Start the media tracker: walk every current <video>/<audio> and attach
5724
+ * per-element listeners (scroll-twin lifecycle; armed in start()/resume()).
5725
+ * Idempotent -- re-arming first tears down any prior listeners so a restart
5726
+ * cannot double-bind.
5727
+ */
5728
+ function startMediaTracker() {
5729
+ stopMediaTracker();
5730
+ mediaTrackingActive = true;
5731
+ var els = collectTrackedMediaElements();
5732
+ for (var i = 0; i < els.length; i++) attachMediaListeners(els[i]);
5733
+ logger.info('[DOM Stream] Media tracker started');
5734
+ }
5735
+
5736
+ /**
5737
+ * Stop the media tracker: detach every per-element listener and clear the
5738
+ * bookkeeping (torn down in start() re-arm, stop(), and pause()).
5739
+ */
5740
+ function stopMediaTracker() {
5741
+ mediaTrackingActive = false;
5742
+ var els = mediaTrackedRecords.slice();
5743
+ for (var i = 0; i < els.length; i++) detachMediaListeners(els[i]);
5744
+ mediaTracked = new Map();
5745
+ mediaTrackedRecords = [];
5746
+ logger.info('[DOM Stream] Media tracker stopped');
5747
+ }
5748
+
4190
5749
  // =========================================================================
4191
5750
  // 4. Overlay Event Broadcaster
4192
5751
  // =========================================================================
@@ -4264,15 +5823,19 @@ export function createCapture(config) {
4264
5823
  if (streaming) {
4265
5824
  stopMutationStream();
4266
5825
  stopScrollTracker();
5826
+ stopMediaTracker();
4267
5827
  }
4268
5828
  beginStreamSession();
4269
5829
  clearNodeMirror();
4270
5830
  nextNodeId = 1;
4271
5831
  var snapshot = serializeDOM();
4272
5832
  safeSend(STREAM.SNAPSHOT, snapshot);
5833
+ seedStyleSourceFingerprints(snapshot);
5834
+ healPrunedStyleScopes(snapshot);
4273
5835
  startMutationStream();
4274
5836
  startValueCapture();
4275
5837
  startScrollTracker();
5838
+ startMediaTracker();
4276
5839
  streaming = true;
4277
5840
  broadcastOverlayState(true);
4278
5841
  }
@@ -4285,6 +5848,7 @@ export function createCapture(config) {
4285
5848
  logger.info('[DOM Stream] Stop requested');
4286
5849
  stopMutationStream();
4287
5850
  stopScrollTracker();
5851
+ stopMediaTracker();
4288
5852
  streaming = false;
4289
5853
  clearNodeMirror();
4290
5854
  safeFlush();
@@ -4298,6 +5862,7 @@ export function createCapture(config) {
4298
5862
  logger.info('[DOM Stream] Pause requested');
4299
5863
  stopMutationStream();
4300
5864
  stopScrollTracker();
5865
+ stopMediaTracker();
4301
5866
  // Keep streaming = true (paused state, not stopped)
4302
5867
  }
4303
5868
 
@@ -4315,6 +5880,7 @@ export function createCapture(config) {
4315
5880
  startMutationStream();
4316
5881
  startValueCapture();
4317
5882
  startScrollTracker();
5883
+ startMediaTracker();
4318
5884
  streaming = true;
4319
5885
  }
4320
5886
 
@@ -4322,6 +5888,7 @@ export function createCapture(config) {
4322
5888
  if (!streaming) return null;
4323
5889
  if (!element || element.nodeType !== Node.ELEMENT_NODE) return null;
4324
5890
  if (element.isConnected === false && !getMutationFrameRecord(element)) return null;
5891
+ // document.body deliberately resolves to null: BODY_NID is a structural anchor for body-level diffs, not an addressable element.
4325
5892
  return getTrackedNodeId(element);
4326
5893
  }
4327
5894
 
@@ -4356,6 +5923,71 @@ export function createCapture(config) {
4356
5923
  resume: resume,
4357
5924
  handleControl: handleControl,
4358
5925
  getNodeId: getNodeId,
4359
- getObservedFrameDocuments: getObservedFrameDocuments
5926
+ getObservedFrameDocuments: getObservedFrameDocuments,
5927
+ // One-shot snapshot serializer over the ambient document. Exposed for the
5928
+ // serializeSnapshot() top-level helper (capture-asset-degrade unit tests)
5929
+ // and any host that wants a single payload without arming observers.
5930
+ serializeSnapshot: serializeDOM
4360
5931
  };
4361
5932
  }
5933
+
5934
+ // Ambient globals the snapshot serializer dereferences (audited from the
5935
+ // reference source, mirrors the differential harness AMBIENT_GLOBALS). The
5936
+ // serializeSnapshot() helper swaps these from the passed document's window for
5937
+ // the duration of one serialization, then restores them unconditionally.
5938
+ var SNAPSHOT_AMBIENT_GLOBALS = [
5939
+ 'window', 'document', 'Node', 'NodeFilter', 'MutationObserver',
5940
+ 'requestAnimationFrame', 'cancelAnimationFrame', 'CustomEvent',
5941
+ 'ShadowRoot', 'location', 'getComputedStyle', 'URL'
5942
+ ];
5943
+
5944
+ /**
5945
+ * Serialize ONE snapshot of the given document and return the snapshot payload
5946
+ * (`{ html, nodeIds, ... }`). A convenience top-level entry that swaps the
5947
+ * ambient globals from `doc.defaultView` for the lifetime of one serialization
5948
+ * (mirroring the differential harness's createExtractedSide), runs a fresh
5949
+ * capture's serializer against it, and restores the globals unconditionally.
5950
+ *
5951
+ * This is the no-observer path used by the capture-asset-degrade unit tests to
5952
+ * prove the clone-only currentSrc enrichment and the blob:/oversized-data:
5953
+ * placeholder degrade WITHOUT mutating the live document.
5954
+ *
5955
+ * @param {Document} doc the document to snapshot (must have a defaultView)
5956
+ * @returns {{html: string, nodeIds: string[]}} the snapshot payload
5957
+ */
5958
+ export function serializeSnapshot(doc) {
5959
+ var win = doc && doc.defaultView;
5960
+ if (!win) throw new Error('serializeSnapshot-requires-document-with-defaultView');
5961
+
5962
+ var saved = SNAPSHOT_AMBIENT_GLOBALS.map(function (name) {
5963
+ return {
5964
+ name: name,
5965
+ had: Object.prototype.hasOwnProperty.call(globalThis, name),
5966
+ value: globalThis[name]
5967
+ };
5968
+ });
5969
+ function restore() {
5970
+ for (var i = 0; i < saved.length; i++) {
5971
+ if (saved[i].had) {
5972
+ globalThis[saved[i].name] = saved[i].value;
5973
+ } else {
5974
+ delete globalThis[saved[i].name];
5975
+ }
5976
+ }
5977
+ }
5978
+
5979
+ for (var g = 0; g < SNAPSHOT_AMBIENT_GLOBALS.length; g++) {
5980
+ var n = SNAPSHOT_AMBIENT_GLOBALS[g];
5981
+ globalThis[n] = n === 'window' ? win : win[n];
5982
+ }
5983
+
5984
+ try {
5985
+ var capture = createCapture({
5986
+ transport: { send: function () {} },
5987
+ logger: { info: function () {}, warn: function () {}, error: function () {} }
5988
+ });
5989
+ return capture.serializeSnapshot();
5990
+ } finally {
5991
+ restore();
5992
+ }
5993
+ }