@full-self-browsing/phantom-stream 0.2.1 → 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.
@@ -42,6 +42,7 @@
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,
47
48
  MEDIA_SYNC_THROTTLE_MS,
@@ -51,13 +52,108 @@ import {
51
52
  INLINE_STYLE_MAX_BYTES,
52
53
  ASSET_DATA_URI_MAX_BYTES,
53
54
  } from '../protocol/constants.js';
54
- 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';
55
64
 
56
65
  // RELAY_PER_MESSAGE_LIMIT_BYTES is the relay's hard per-message cap;
57
66
  // SNAPSHOT_BUDGET_BYTES is the 80% truncation budget derived from it
58
67
  // (replaces the reference's inline Math.floor(limit * 0.8) computation).
59
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.
60
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 };
61
157
 
62
158
  // Attributes that need URL absolutification
63
159
  var URL_ATTRS = ['src', 'href', 'action', 'poster', 'data'];
@@ -533,6 +629,23 @@ function defaultMaskText(text) {
533
629
  * raw URL). Stricter than maskTextFn: a thrown text mask falls back to the
534
630
  * asterisk default, but a thrown URL redactor blocks (a half-redacted URL
535
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.
536
649
  */
537
650
 
538
651
  /**
@@ -581,6 +694,19 @@ export function createCapture(config) {
581
694
  ? cfg.fetchStylesheet
582
695
  : null;
583
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
+
584
710
  // SEC-03 privacy-masking config (plan 03-03, rrweb-compatible vocabulary
585
711
  // per 03-RESEARCH Pattern 5). Every option defaults OFF: with no masking
586
712
  // config the wire is byte-identical to the unmasked output. The one
@@ -738,6 +864,16 @@ export function createCapture(config) {
738
864
  var styleSourceRegistry = new Map();
739
865
  var styleOwnerToSourceKey = typeof WeakMap === 'function' ? new WeakMap() : null;
740
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;
741
877
  var nativeCssStyleSheetMethods = null;
742
878
  var flushingMutations = false;
743
879
 
@@ -778,6 +914,10 @@ export function createCapture(config) {
778
914
  styleSourceRegistry.clear();
779
915
  styleScopeRoots.clear();
780
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;
781
921
  }
782
922
 
783
923
  function getCurrentStreamMetadata() {
@@ -813,6 +953,22 @@ export function createCapture(config) {
813
953
  return nid;
814
954
  }
815
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
+
816
972
  function clearNodeMirror() {
817
973
  elementToNid = new WeakMap();
818
974
  nidToElement.clear();
@@ -968,6 +1124,7 @@ export function createCapture(config) {
968
1124
  cloneToNid: cloneToNid
969
1125
  });
970
1126
  if (subtreeResult && subtreeResult.drop) return null;
1127
+ neutralizeParserHostileNesting(container, cloneToNid, { rootContext: 'container' });
971
1128
 
972
1129
  var shadowPayload = {
973
1130
  hostNid: String(hostNid),
@@ -1206,6 +1363,36 @@ export function createCapture(config) {
1206
1363
  };
1207
1364
  }
1208
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
+
1209
1396
  function safeStylesheetHref(href, doc) {
1210
1397
  if (!href) return '';
1211
1398
  var resolved = absolutifyUrl(String(href), doc);
@@ -1293,6 +1480,50 @@ export function createCapture(config) {
1293
1480
  return entries;
1294
1481
  }
1295
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
+
1296
1527
  function sourceFromStyleSheetEntry(entry, scope, order, doc, root) {
1297
1528
  var e = entry || {};
1298
1529
  var ownerKind = ownerKindForStyleNode(e.ownerNode, e.adopted);
@@ -1417,12 +1648,21 @@ export function createCapture(config) {
1417
1648
  if (!sourceId) return;
1418
1649
  var safeSource = null;
1419
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;
1420
1655
  safeSource = Object.assign({}, source, {
1421
1656
  sourceId: sourceId,
1422
1657
  scope: cloneStyleScope(scope || source.scope),
1423
1658
  cssText: sanitizeCssTextForSource(source.cssText || '')
1424
1659
  });
1425
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);
1426
1666
  }
1427
1667
  pendingStyleSourceChanges.set(sourceId, {
1428
1668
  op: DIFF_OP.STYLE_SOURCE,
@@ -1480,6 +1720,43 @@ export function createCapture(config) {
1480
1720
  scope: entry ? entry.scope : cloneStyleScope(scope)
1481
1721
  }, entry ? entry.scope : scope, reason || 'cssom-style-source-stale');
1482
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;
1483
1760
  }
1484
1761
 
1485
1762
  function markStyleOwnerDirty(owner, reason) {
@@ -1487,6 +1764,14 @@ export function createCapture(config) {
1487
1764
  var key = owner && styleOwnerToSourceKey ? styleOwnerToSourceKey.get(owner) : '';
1488
1765
  var entry = key ? styleSourceRegistry.get(key) : null;
1489
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
+ }
1490
1775
  sendCssomFreshSnapshot('cssom-style-source-stale');
1491
1776
  return;
1492
1777
  }
@@ -1537,10 +1822,19 @@ export function createCapture(config) {
1537
1822
  nativeCssStyleSheetMethods = null;
1538
1823
  }
1539
1824
 
1540
- 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) {
1541
1830
  if (styleMode !== 'cssom') return;
1542
1831
  try {
1543
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
+ }
1544
1838
  queueStyleScopeReplacement(scope, root, 'adoptedStyleSheets');
1545
1839
  }
1546
1840
  } catch (err) {
@@ -1550,9 +1844,78 @@ export function createCapture(config) {
1550
1844
 
1551
1845
  function reconcileAllKnownStyleScopes() {
1552
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;
1553
1852
  styleScopeRoots.forEach(function(info) {
1554
1853
  if (!info || !info.root || !info.scope) return;
1555
- 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
+ }
1556
1919
  });
1557
1920
  }
1558
1921
 
@@ -1561,7 +1924,10 @@ export function createCapture(config) {
1561
1924
  logger.warn('[DOM Stream] cssom resnapshot', {
1562
1925
  reason: reason || 'cssom-style-source-stale'
1563
1926
  });
1564
- safeSend(STREAM.SNAPSHOT, serializeDOM());
1927
+ var snapshot = serializeDOM();
1928
+ safeSend(STREAM.SNAPSHOT, snapshot);
1929
+ seedStyleSourceFingerprints(snapshot);
1930
+ healPrunedStyleScopes(snapshot);
1565
1931
  }
1566
1932
 
1567
1933
  function prepareFrameDocumentClone(frameDoc, bodyClone, cloneToNid) {
@@ -1671,6 +2037,7 @@ export function createCapture(config) {
1671
2037
  cloneToNid: cloneToNid
1672
2038
  });
1673
2039
  if (subtreeResult && subtreeResult.drop) return null;
2040
+ neutralizeParserHostileNesting(bodyClone, cloneToNid, { rootContext: 'container' });
1674
2041
 
1675
2042
  var nodeIds = buildNodeIdSidecar(bodyClone, cloneToNid, false);
1676
2043
  var frameShadowRoots = collectShadowRootPayloads(frameDoc.body, nodeIds);
@@ -2683,6 +3050,190 @@ export function createCapture(config) {
2683
3050
  return placeholder;
2684
3051
  }
2685
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
+
2686
3237
  function utf8ByteLength(text) {
2687
3238
  var str = String(text || '');
2688
3239
  var bytes = 0;
@@ -2774,7 +3325,7 @@ export function createCapture(config) {
2774
3325
  }));
2775
3326
  }
2776
3327
 
2777
- while (currentWireLength() > SNAPSHOT_BUDGET_BYTES && (keptShadowRoots.length || keptFrames.length)) {
3328
+ while (currentWireLength() > snapshotBudgetBytes && (keptShadowRoots.length || keptFrames.length)) {
2778
3329
  var largestKind = '';
2779
3330
  var largestIndex = -1;
2780
3331
  var largestLength = -1;
@@ -2855,49 +3406,49 @@ export function createCapture(config) {
2855
3406
  next.media = next.media.slice();
2856
3407
  }
2857
3408
 
2858
- while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.inlineStyles.length) {
3409
+ while (wireByteLength(next) > snapshotBudgetBytes && next.inlineStyles.length) {
2859
3410
  next.inlineStyles.pop();
2860
3411
  markSnapshotPayloadTruncated(next);
2861
3412
  }
2862
- while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.stylesheets.length) {
3413
+ while (wireByteLength(next) > snapshotBudgetBytes && next.stylesheets.length) {
2863
3414
  next.stylesheets.pop();
2864
3415
  markSnapshotPayloadTruncated(next);
2865
3416
  }
2866
3417
  // A single large CSSOM source can dominate the payload; shed sources before
2867
3418
  // dropping DOM structure so an oversized stylesheet cannot blow the cap.
2868
- while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Array.isArray(next.styleSources) && next.styleSources.length) {
3419
+ while (wireByteLength(next) > snapshotBudgetBytes && Array.isArray(next.styleSources) && next.styleSources.length) {
2869
3420
  next.styleSources.pop();
2870
3421
  markSnapshotPayloadTruncated(next);
2871
3422
  }
2872
3423
 
2873
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.htmlStyle) {
3424
+ if (wireByteLength(next) > snapshotBudgetBytes && next.htmlStyle) {
2874
3425
  next.htmlStyle = '';
2875
3426
  markSnapshotPayloadTruncated(next);
2876
3427
  }
2877
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.bodyStyle) {
3428
+ if (wireByteLength(next) > snapshotBudgetBytes && next.bodyStyle) {
2878
3429
  next.bodyStyle = '';
2879
3430
  markSnapshotPayloadTruncated(next);
2880
3431
  }
2881
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Object.keys(next.htmlAttrs).length) {
3432
+ if (wireByteLength(next) > snapshotBudgetBytes && Object.keys(next.htmlAttrs).length) {
2882
3433
  next.htmlAttrs = {};
2883
3434
  markSnapshotPayloadTruncated(next);
2884
3435
  }
2885
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Object.keys(next.bodyAttrs).length) {
3436
+ if (wireByteLength(next) > snapshotBudgetBytes && Object.keys(next.bodyAttrs).length) {
2886
3437
  next.bodyAttrs = {};
2887
3438
  markSnapshotPayloadTruncated(next);
2888
3439
  }
2889
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.title) {
3440
+ if (wireByteLength(next) > snapshotBudgetBytes && next.title) {
2890
3441
  next.title = '';
2891
3442
  markSnapshotPayloadTruncated(next);
2892
3443
  }
2893
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.url) {
3444
+ if (wireByteLength(next) > snapshotBudgetBytes && next.url) {
2894
3445
  next.url = '';
2895
3446
  markSnapshotPayloadTruncated(next);
2896
3447
  }
2897
3448
 
2898
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && clone && cloneToNid) {
3449
+ if (wireByteLength(next) > snapshotBudgetBytes && clone && cloneToNid) {
2899
3450
  var cloneEls = cloneElementsWithNodeIds(clone, cloneToNid);
2900
- 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--) {
2901
3452
  var nid = cloneToNid.get(cloneEls[i]);
2902
3453
  if (markCloneNidTruncated(clone, cloneToNid, nid, truncatedNodeIds)) {
2903
3454
  next.html = clone.innerHTML || '';
@@ -2916,7 +3467,7 @@ export function createCapture(config) {
2916
3467
  }
2917
3468
  }
2918
3469
 
2919
- if (wireByteLength(next) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
3470
+ if (wireByteLength(next) > messageLimitBytes) {
2920
3471
  next.html = '';
2921
3472
  next.nodeIds = [];
2922
3473
  next.shadowRoots = [];
@@ -3176,6 +3727,10 @@ export function createCapture(config) {
3176
3727
  // 5. E2 text-childlist branch -- 'text' dispatch (same seam)
3177
3728
  // 6. input/change value branch -- 'input' dispatch (CAPT-05
3178
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.
3179
3734
  // Head inline <style> text additionally routes through the 'css' dispatch
3180
3735
  // at the serializeDOM collection site (a value scrub, not a markup walk).
3181
3736
  // Side channels that BYPASS the markup scrub AND the masking helpers BY
@@ -3910,6 +4465,10 @@ export function createCapture(config) {
3910
4465
  );
3911
4466
  }
3912
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' });
4471
+
3913
4472
  // Collect stylesheet URLs from document.head
3914
4473
  var stylesheets = collectStylesheetsFrom(document);
3915
4474
 
@@ -3955,10 +4514,11 @@ export function createCapture(config) {
3955
4514
  }
3956
4515
  } catch (e) { /* TreeWalker unavailable in this realm; truncation falls back to no-op */ }
3957
4516
 
3958
- // SNAPSHOT_BUDGET_BYTES is the imported 80%-of-relay-cap budget. Compare
3959
- // UTF-8 wire bytes, not UTF-16 code units, so non-ASCII snapshots respect
3960
- // the relay's byte cap.
3961
- 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) {
3962
4522
  truncated = true;
3963
4523
  var viewportCutoff = window.innerHeight * TRUNCATION_VIEWPORT_MULTIPLIER;
3964
4524
 
@@ -3985,9 +4545,9 @@ export function createCapture(config) {
3985
4545
  // elements in document order and drops complete subtrees until under
3986
4546
  // cap. Only complete subtrees are removed -- never a mid-element cut.
3987
4547
  html = clone.innerHTML;
3988
- if (wireByteLength(html) > SNAPSHOT_BUDGET_BYTES) {
4548
+ if (wireByteLength(html) > snapshotBudgetBytes) {
3989
4549
  var cloneEls2 = cloneElementsWithNodeIds(clone, cloneToNid);
3990
- 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--) {
3991
4551
  var placeholder2 = replaceWithTruncatedPlaceholder(cloneEls2[u], cloneToNid);
3992
4552
  if (placeholder2) {
3993
4553
  var placeholderNid2 = cloneToNid.get(placeholder2);
@@ -4010,6 +4570,7 @@ export function createCapture(config) {
4010
4570
  var budgetInput = {
4011
4571
  html: html,
4012
4572
  nodeIds: nodeIds,
4573
+ bodyNid: BODY_NID,
4013
4574
  truncated: truncated,
4014
4575
  missingDescendants: missingDescendants,
4015
4576
  stylesheets: stylesheets,
@@ -4051,6 +4612,7 @@ export function createCapture(config) {
4051
4612
  var snapshotPayload = {
4052
4613
  html: html,
4053
4614
  nodeIds: nodeIds,
4615
+ bodyNid: BODY_NID,
4054
4616
  shadowRoots: shadowRoots,
4055
4617
  frames: frames,
4056
4618
  truncated: truncated,
@@ -4246,6 +4808,8 @@ export function createCapture(config) {
4246
4808
  cloneToNid: cloneToNid
4247
4809
  });
4248
4810
  if (subtreeResult && subtreeResult.drop) return null;
4811
+ // Also serves subtree-fetch responses (serializeRequestedSubtree).
4812
+ wireClone = neutralizeParserHostileNesting(wireClone, cloneToNid, { rootContext: 'fragment' });
4249
4813
  var nodeIds = buildNodeIdSidecar(wireClone, cloneToNid, true);
4250
4814
  var shadowRoots = collectShadowRootPayloads(el, nodeIds);
4251
4815
  var frames = collectFramePayloads(el, cloneToNid);
@@ -4325,7 +4889,7 @@ export function createCapture(config) {
4325
4889
  streamSessionId: streamSessionId || '',
4326
4890
  snapshotId: currentSnapshotId || 0
4327
4891
  }, result);
4328
- if (response.status === 'ok' && wireByteLength(response) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
4892
+ if (response.status === 'ok' && wireByteLength(response) > messageLimitBytes) {
4329
4893
  response = Object.assign({
4330
4894
  requestId: request && request.requestId != null ? String(request.requestId) : '',
4331
4895
  nid: request && request.nid != null ? String(request.nid) : '',
@@ -4424,7 +4988,7 @@ export function createCapture(config) {
4424
4988
  if (wireDroppedWithAncestors(added.parentElement)) continue;
4425
4989
  if (blockedWithAncestors(added.parentElement)) continue;
4426
4990
 
4427
- var parentNid = getTrackedNodeId(m.target);
4991
+ var parentNid = mutationTargetNid(m.target);
4428
4992
  if (!parentNid) continue; // Parent not tracked
4429
4993
 
4430
4994
  var addedPayload = processAddedNode(added);
@@ -4519,8 +5083,13 @@ export function createCapture(config) {
4519
5083
  && (attrNameLower === 'href' || attrNameLower === 'media' || attrNameLower === 'disabled')) {
4520
5084
  markStyleOwnerDirty(m.target, 'link-attr-mutated');
4521
5085
  }
4522
- var targetNid = getTrackedNodeId(m.target);
5086
+ var targetNid = mutationTargetNid(m.target);
4523
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;
4524
5093
 
4525
5094
  if (attrTargetTag === 'iframe' && attrNameLower === 'src') {
4526
5095
  registerFrameLoadListener(m.target, targetNid);
@@ -4711,13 +5280,13 @@ export function createCapture(config) {
4711
5280
 
4712
5281
  function boundMutationDiffForBudget(diff, options) {
4713
5282
  if (!diff) return null;
4714
- if (wireByteLength(mutationPayloadForBudget([diff], options)) <= RELAY_PER_MESSAGE_LIMIT_BYTES) return diff;
5283
+ if (wireByteLength(mutationPayloadForBudget([diff], options)) <= messageLimitBytes) return diff;
4715
5284
  var bounded = null;
4716
5285
  if (diff.op === DIFF_OP.ADD) bounded = boundedAddPlaceholder(diff);
4717
5286
  if (diff.op === DIFF_OP.FRAME) bounded = boundedFramePlaceholder(diff);
4718
5287
  if (diff.op === DIFF_OP.SHADOW_ROOT) bounded = boundedShadowRootPlaceholder(diff);
4719
5288
  if (!bounded) return null;
4720
- return wireByteLength(mutationPayloadForBudget([bounded], options)) <= RELAY_PER_MESSAGE_LIMIT_BYTES
5289
+ return wireByteLength(mutationPayloadForBudget([bounded], options)) <= messageLimitBytes
4721
5290
  ? bounded
4722
5291
  : null;
4723
5292
  }
@@ -4736,14 +5305,14 @@ export function createCapture(config) {
4736
5305
  continue;
4737
5306
  }
4738
5307
  var singlePayload = mutationPayloadForBudget([diff], options);
4739
- if (wireByteLength(singlePayload) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
5308
+ if (wireByteLength(singlePayload) > messageLimitBytes) {
4740
5309
  logger.warn('[DOM Stream] mutation diff dropped over budget', {
4741
5310
  op: diff && diff.op ? diff.op : ''
4742
5311
  });
4743
5312
  continue;
4744
5313
  }
4745
5314
  var nextChunk = chunk.concat([diff]);
4746
- if (chunk.length && wireByteLength(mutationPayloadForBudget(nextChunk, options)) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
5315
+ if (chunk.length && wireByteLength(mutationPayloadForBudget(nextChunk, options)) > messageLimitBytes) {
4747
5316
  safeSend(STREAM.MUTATIONS, mutationPayloadForBudget(chunk, options));
4748
5317
  chunk = [diff];
4749
5318
  } else {
@@ -5261,6 +5830,8 @@ export function createCapture(config) {
5261
5830
  nextNodeId = 1;
5262
5831
  var snapshot = serializeDOM();
5263
5832
  safeSend(STREAM.SNAPSHOT, snapshot);
5833
+ seedStyleSourceFingerprints(snapshot);
5834
+ healPrunedStyleScopes(snapshot);
5264
5835
  startMutationStream();
5265
5836
  startValueCapture();
5266
5837
  startScrollTracker();
@@ -5317,6 +5888,7 @@ export function createCapture(config) {
5317
5888
  if (!streaming) return null;
5318
5889
  if (!element || element.nodeType !== Node.ELEMENT_NODE) return null;
5319
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.
5320
5892
  return getTrackedNodeId(element);
5321
5893
  }
5322
5894