@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.
@@ -8,6 +8,7 @@
8
8
 
9
9
  var RELAY_PER_MESSAGE_LIMIT_BYTES = 1048576;
10
10
  var SNAPSHOT_BUDGET_BYTES = Math.floor(RELAY_PER_MESSAGE_LIMIT_BYTES * 0.8);
11
+ var SNAPSHOT_BUDGET_FRACTION = 0.8;
11
12
  var TRUNCATION_VIEWPORT_MULTIPLIER = 3;
12
13
  var SCROLL_THROTTLE_MS = 200;
13
14
  var OVERLAY_THROTTLE_MS = 500;
@@ -18,6 +19,9 @@
18
19
  var CONTROL = { START: "dash:dom-stream-start", STOP: "dash:dom-stream-stop", PAUSE: "dash:dom-stream-pause", RESUME: "dash:dom-stream-resume", SUBTREE_REQUEST: "dash:ps-subtree-request" };
19
20
  var STREAM = { SNAPSHOT: "ext:dom-snapshot", MUTATIONS: "ext:dom-mutations", SCROLL: "ext:dom-scroll", OVERLAY: "ext:dom-overlay", DIALOG: "ext:dom-dialog", READY: "ext:dom-ready", REQUEST_SNAPSHOT: "ext:request-snapshot", STATE: "ext:stream-state", SUBTREE_RESPONSE: "ext:ps-subtree-response" };
20
21
  var DIFF_OP = { ADD: "add", REMOVE: "rm", ATTR: "attr", TEXT: "text", VALUE: "value", SHADOW_ROOT: "shadow-root", FRAME: "frame", STYLE_SOURCE: "style-source" };
22
+ var BODY_NID = "body";
23
+ var PARSER_SAFE_TAG = "ps-node";
24
+ var PARSER_SAFE_TAG_ATTR = "data-ps-tag";
21
25
 
22
26
  function createStreamSessionId(nowMs, rand) { return "stream_" + nowMs.toString(36) + "_" + rand; }
23
27
  // PhantomStream capture core: DOM snapshot + MutationObserver diff streaming.
@@ -66,7 +70,94 @@
66
70
  // SNAPSHOT_BUDGET_BYTES is the 80% truncation budget derived from it
67
71
  // (replaces the reference's inline Math.floor(limit * 0.8) computation).
68
72
  // Both are imported, never redefined, so capture and relay stay in sync.
73
+ // They are the DEFAULTS: createCapture's messageLimitBytes and
74
+ // snapshotBudgetBytes options override them per instance for local recorders
75
+ // that never pass through a relay (quick task 261202-jwf), and every budget
76
+ // pass compares against those instance values.
69
77
  void RELAY_PER_MESSAGE_LIMIT_BYTES;
78
+ void SNAPSHOT_BUDGET_BYTES;
79
+
80
+ // Cadence of the CSSOM full style re-collect safety net, in ms (quick task
81
+ // 261202-jwf, D 1.2). The per-flush reconcile skips a scope whose cheap
82
+ // signature is unchanged; at most once per this interval it re-collects every
83
+ // known scope anyway, which catches a rule edit that keeps cssRules.length.
84
+ // Fingerprints still dedupe the result, so an unchanged sheet sends nothing.
85
+ var STYLE_FULL_RECONCILE_MS = 2000; // 2 s
86
+
87
+ // Parser-safe serialization tag sets (quick task 261202-jwf, D 3.2). They
88
+ // mirror the HTML tree-construction rules that rewrite script-built nesting
89
+ // when serialized markup is parsed again; neutralizeParserHostileNesting reads
90
+ // them. Only HTML-namespace elements are renamed or count as matches.
91
+ var PARSER_SAFE_HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
92
+ var PARSER_SAFE_SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
93
+ var PARSER_SAFE_MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
94
+ // (a) an element of one of these tags inside a same-tag ancestor
95
+ var PARSER_SAFE_SAME_TAG = { button: true, a: true, form: true, nobr: true };
96
+ // (b) a start tag that closes an open <p>
97
+ var PARSER_SAFE_BLOCK_CLOSERS = {
98
+ address: true, article: true, aside: true, blockquote: true, center: true,
99
+ details: true, dialog: true, dir: true, div: true, dl: true, fieldset: true,
100
+ figcaption: true, figure: true, footer: true, header: true, hgroup: true,
101
+ main: true, menu: true, nav: true, ol: true, p: true, search: true,
102
+ section: true, summary: true, ul: true, h1: true, h2: true, h3: true,
103
+ h4: true, h5: true, h6: true, pre: true, listing: true, form: true,
104
+ plaintext: true, xmp: true, table: true, hr: true, li: true, dd: true, dt: true
105
+ };
106
+ // (c) headings
107
+ var PARSER_SAFE_HEADINGS = { h1: true, h2: true, h3: true, h4: true, h5: true, h6: true };
108
+ // (d) the HTML "special" category, which stops the li/dd/dt scope walk
109
+ var PARSER_SAFE_SPECIAL = {
110
+ address: true, applet: true, area: true, article: true, aside: true,
111
+ base: true, basefont: true, bgsound: true, blockquote: true, body: true,
112
+ br: true, button: true, caption: true, center: true, col: true,
113
+ colgroup: true, dd: true, details: true, dir: true, div: true, dl: true,
114
+ dt: true, embed: true, fieldset: true, figcaption: true, figure: true,
115
+ footer: true, form: true, frame: true, frameset: true, h1: true, h2: true,
116
+ h3: true, h4: true, h5: true, h6: true, head: true, header: true,
117
+ hgroup: true, hr: true, html: true, iframe: true, img: true, input: true,
118
+ keygen: true, li: true, link: true, listing: true, main: true,
119
+ marquee: true, menu: true, meta: true, nav: true, noembed: true,
120
+ noframes: true, noscript: true, object: true, ol: true, p: true,
121
+ param: true, plaintext: true, pre: true, script: true, search: true,
122
+ section: true, select: true, source: true, style: true, summary: true,
123
+ table: true, tbody: true, td: true, template: true, textarea: true,
124
+ tfoot: true, th: true, thead: true, title: true, tr: true, track: true,
125
+ ul: true, wbr: true, xmp: true
126
+ };
127
+ var PARSER_SAFE_LIST_WALK_EXEMPT = { address: true, div: true, p: true };
128
+ var PARSER_SAFE_LI = { li: true };
129
+ var PARSER_SAFE_DD_DT = { dd: true, dt: true };
130
+ var PARSER_SAFE_SVG_INTEGRATION_POINTS = { foreignObject: true, desc: true, title: true };
131
+ var PARSER_SAFE_MATHML_INTEGRATION_POINTS = { mi: true, mo: true, mn: true, ms: true, mtext: true, 'annotation-xml': true };
132
+ // (e) the only element content a <select> keeps through a parse
133
+ var PARSER_SAFE_SELECT_CONTENT = { option: true, optgroup: true, hr: true, script: true, template: true };
134
+ // (f) elements whose content parses as text
135
+ var PARSER_SAFE_TEXT_ONLY = { textarea: true, xmp: true, plaintext: true };
136
+ // (g) void elements, which cannot hold child nodes in markup
137
+ var PARSER_SAFE_VOID = { img: true, input: true, br: true, hr: true, wbr: true, area: true, col: true, source: true, track: true };
138
+ // (h) table structure
139
+ var PARSER_SAFE_TABLE_PARTS = { caption: true, colgroup: true, col: true, thead: true, tbody: true, tfoot: true, tr: true, td: true, th: true };
140
+ var PARSER_SAFE_TABLE_CHILDREN = { caption: true, colgroup: true, thead: true, tbody: true, tfoot: true, script: true, template: true, style: true };
141
+ var PARSER_SAFE_VALID_PARENTS = {
142
+ caption: { table: true },
143
+ colgroup: { table: true },
144
+ thead: { table: true },
145
+ tbody: { table: true },
146
+ tfoot: { table: true },
147
+ tr: { thead: true, tbody: true, tfoot: true },
148
+ td: { tr: true },
149
+ th: { tr: true },
150
+ col: { colgroup: true }
151
+ };
152
+ var PARSER_SAFE_PART_CHILDREN = {
153
+ thead: { tr: true, script: true, template: true },
154
+ tbody: { tr: true, script: true, template: true },
155
+ tfoot: { tr: true, script: true, template: true },
156
+ tr: { td: true, th: true, script: true, template: true },
157
+ colgroup: { col: true, template: true }
158
+ };
159
+ // (i) document shell elements
160
+ var PARSER_SAFE_SHELL = { html: true, head: true, body: true, frameset: true };
70
161
 
71
162
  // Attributes that need URL absolutification
72
163
  var URL_ATTRS = ['src', 'href', 'action', 'poster', 'data'];
@@ -435,6 +526,23 @@ function defaultMaskText(text) {
435
526
  * @property {(text: string, element: Element) => string} [maskInputFn]
436
527
  * Optional (SEC-03). Custom input-value mask (rrweb signature). Same
437
528
  * fail-closed containment as maskTextFn.
529
+ * @property {number} [messageLimitBytes]
530
+ * Optional (quick task 261202-jwf), default RELAY_PER_MESSAGE_LIMIT_BYTES
531
+ * (1 MiB). The largest wire message this capture emits, in UTF-8 bytes of
532
+ * the JSON payload: it governs the snapshot hard reset, single mutation
533
+ * diffs, mutation chunking and subtree responses. Only a positive finite
534
+ * number is accepted; any other value falls back to the default. Relay
535
+ * users keep the default, because the relay drops messages over 1 MiB;
536
+ * local recorders that never pass through a relay (FSB records with 8 MiB)
537
+ * may raise it.
538
+ * @property {number} [snapshotBudgetBytes]
539
+ * Optional (quick task 261202-jwf), default
540
+ * floor(messageLimitBytes * SNAPSHOT_BUDGET_FRACTION). The budget the
541
+ * snapshot truncation passes and sidecar pruning aim for, in UTF-8 wire
542
+ * bytes. Only a positive finite number is accepted; any other value falls
543
+ * back to the default. Clamped to at most messageLimitBytes. Relay users
544
+ * keep the default; local recorders may raise it (FSB records with 4 MiB)
545
+ * so large pages keep every stylesheet.
438
546
  */
439
547
 
440
548
  /**
@@ -483,6 +591,19 @@ function createCapture(config) {
483
591
  ? cfg.fetchStylesheet
484
592
  : null;
485
593
 
594
+ // Per-instance budgets (quick task 261202-jwf, D 2.1). Only positive finite
595
+ // numbers are accepted; anything else falls back to the relay-sized
596
+ // defaults, so with no options the wire is unchanged. The snapshot budget
597
+ // never exceeds the message limit, or the hard reset in
598
+ // fitSnapshotPayloadForBudget would empty an over-budget snapshot instead
599
+ // of pruning it.
600
+ function positiveFiniteOption(value) {
601
+ return typeof value === 'number' && isFinite(value) && value > 0 ? value : null;
602
+ }
603
+ var messageLimitBytes = positiveFiniteOption(cfg.messageLimitBytes) || RELAY_PER_MESSAGE_LIMIT_BYTES;
604
+ var snapshotBudgetBytes = positiveFiniteOption(cfg.snapshotBudgetBytes) || Math.floor(messageLimitBytes * SNAPSHOT_BUDGET_FRACTION);
605
+ snapshotBudgetBytes = Math.min(snapshotBudgetBytes, messageLimitBytes);
606
+
486
607
  // SEC-03 privacy-masking config (plan 03-03, rrweb-compatible vocabulary
487
608
  // per 03-RESEARCH Pattern 5). Every option defaults OFF: with no masking
488
609
  // config the wire is byte-identical to the unmasked output. The one
@@ -622,6 +743,16 @@ function createCapture(config) {
622
743
  var styleSourceRegistry = new Map();
623
744
  var styleOwnerToSourceKey = typeof WeakMap === 'function' ? new WeakMap() : null;
624
745
  var styleScopeRoots = new Map();
746
+ // CSSOM dedupe state (quick task 261202-jwf, D 1.1 / D 1.2), per session:
747
+ // styleSourceFingerprints maps sourceId -> fingerprint of the source the
748
+ // viewer holds, seeded from every emitted snapshot; styleScopeSignatures maps
749
+ // styleScopeKey -> cheap scope signature; styleSheetIdentities gives each
750
+ // CSSStyleSheet a stable counter for those signatures.
751
+ var styleSourceFingerprints = new Map();
752
+ var styleScopeSignatures = new Map();
753
+ var styleSheetIdentities = typeof WeakMap === 'function' ? new WeakMap() : null;
754
+ var nextStyleSheetIdentity = 1;
755
+ var lastFullStyleReconcileAt = 0;
625
756
  var nativeCssStyleSheetMethods = null;
626
757
  var flushingMutations = false;
627
758
 
@@ -660,6 +791,10 @@ function createCapture(config) {
660
791
  styleSourceRegistry.clear();
661
792
  styleScopeRoots.clear();
662
793
  styleOwnerToSourceKey = typeof WeakMap === 'function' ? new WeakMap() : null;
794
+ styleSourceFingerprints.clear();
795
+ styleScopeSignatures.clear();
796
+ styleSheetIdentities = typeof WeakMap === 'function' ? new WeakMap() : null;
797
+ lastFullStyleReconcileAt = 0;
663
798
  }
664
799
 
665
800
  function getCurrentStreamMetadata() {
@@ -695,6 +830,22 @@ function createCapture(config) {
695
830
  return nid;
696
831
  }
697
832
 
833
+ // Resolve the nid a childList add op uses as its parent, or an attributes
834
+ // op uses as its target (quick task 261127-u5c). The MAIN document <body>
835
+ // never receives a counter nid (the snapshot sidecar starts below it), so
836
+ // it resolves to the reserved BODY_NID; every other node resolves exactly
837
+ // as getTrackedNodeId does. Main document only: same-origin frame bodies
838
+ // are different elements that already carry counter nids from
839
+ // serializeFrameDocument. The body is deliberately kept out of
840
+ // elementToNid/nidToElement, so getNodeId, rm ops, subtree requests, and
841
+ // shadow hosts never see it. Used only for the add-op parent and the
842
+ // attr-op target: text ops keep getTrackedNodeId because a text op applies
843
+ // as textContent = text and would flatten the whole mirror body.
844
+ function mutationTargetNid(target) {
845
+ if (target && target === document.body) return BODY_NID;
846
+ return getTrackedNodeId(target);
847
+ }
848
+
698
849
  function clearNodeMirror() {
699
850
  elementToNid = new WeakMap();
700
851
  nidToElement.clear();
@@ -850,6 +1001,7 @@ function createCapture(config) {
850
1001
  cloneToNid: cloneToNid
851
1002
  });
852
1003
  if (subtreeResult && subtreeResult.drop) return null;
1004
+ neutralizeParserHostileNesting(container, cloneToNid, { rootContext: 'container' });
853
1005
 
854
1006
  var shadowPayload = {
855
1007
  hostNid: String(hostNid),
@@ -1088,6 +1240,36 @@ function createCapture(config) {
1088
1240
  };
1089
1241
  }
1090
1242
 
1243
+ // 32-bit FNV-1a over UTF-16 code units (quick task 261202-jwf, D 1.1). Not a
1244
+ // security hash: it only tells whether the viewer already holds a source.
1245
+ function fnv1a32(text) {
1246
+ var str = String(text || '');
1247
+ var hash = 0x811c9dc5; // FNV-1a 32-bit offset basis
1248
+ for (var i = 0; i < str.length; i++) {
1249
+ hash ^= str.charCodeAt(i);
1250
+ hash = Math.imul(hash, 0x01000193); // FNV-1a 32-bit prime
1251
+ }
1252
+ return (hash >>> 0).toString(16);
1253
+ }
1254
+
1255
+ // Fingerprint of a style source as the viewer holds it: ownerKind, order,
1256
+ // href, media, disabled, plus the length and FNV-1a hash of its cssText.
1257
+ // Callers pass the source as collected (the same once-sanitized text a
1258
+ // snapshot carries), so an unchanged source never pays a second CSS scrub.
1259
+ function styleSourceFingerprint(source) {
1260
+ var s = source || {};
1261
+ var cssText = String(s.cssText || '');
1262
+ return [
1263
+ s.ownerKind || '',
1264
+ s.order,
1265
+ s.href || '',
1266
+ s.media || '',
1267
+ s.disabled ? 1 : 0,
1268
+ cssText.length,
1269
+ fnv1a32(cssText)
1270
+ ].join('|');
1271
+ }
1272
+
1091
1273
  function safeStylesheetHref(href, doc) {
1092
1274
  if (!href) return '';
1093
1275
  var resolved = absolutifyUrl(String(href), doc);
@@ -1175,6 +1357,50 @@ function createCapture(config) {
1175
1357
  return entries;
1176
1358
  }
1177
1359
 
1360
+ function styleSheetIdentity(sheet) {
1361
+ if (!sheet || !styleSheetIdentities) return 0;
1362
+ var identity = styleSheetIdentities.get(sheet);
1363
+ if (!identity) {
1364
+ identity = nextStyleSheetIdentity++;
1365
+ styleSheetIdentities.set(sheet, identity);
1366
+ }
1367
+ return identity;
1368
+ }
1369
+
1370
+ // Cheap per-scope signature (quick task 261202-jwf, D 1.2): per stylesheet
1371
+ // entry, its sheet identity, cssRules.length (-1 when unreadable), disabled,
1372
+ // media and RAW href. It never serializes rules, so the per-flush reconcile
1373
+ // costs no CSS text. It reads the raw href attribute instead of calling
1374
+ // styleOwnerHref, which counts blocked URL schemes as a side effect.
1375
+ function styleScopeSignature(doc, root) {
1376
+ var entries = styleSheetEntriesForScope(doc, root);
1377
+ var parts = [];
1378
+ for (var i = 0; i < entries.length; i++) {
1379
+ var entry = entries[i] || {};
1380
+ var sheet = entry.sheet || null;
1381
+ var ownerNode = entry.ownerNode || null;
1382
+ var ruleCount = -1;
1383
+ try {
1384
+ ruleCount = sheet && sheet.cssRules ? sheet.cssRules.length : -1;
1385
+ } catch (err) {
1386
+ ruleCount = -1; // cross-origin sheets throw on cssRules
1387
+ }
1388
+ var rawHref = '';
1389
+ if (ownerNode && typeof ownerNode.getAttribute === 'function') {
1390
+ rawHref = ownerNode.getAttribute('href') || '';
1391
+ }
1392
+ if (!rawHref && sheet && sheet.href) rawHref = String(sheet.href);
1393
+ parts.push([
1394
+ styleSheetIdentity(sheet),
1395
+ ruleCount,
1396
+ styleOwnerDisabled(ownerNode, sheet) ? 1 : 0,
1397
+ styleOwnerMedia(ownerNode, sheet),
1398
+ rawHref
1399
+ ].join(','));
1400
+ }
1401
+ return parts.join(';');
1402
+ }
1403
+
1178
1404
  function sourceFromStyleSheetEntry(entry, scope, order, doc, root) {
1179
1405
  var e = entry || {};
1180
1406
  var ownerKind = ownerKindForStyleNode(e.ownerNode, e.adopted);
@@ -1299,12 +1525,21 @@ function createCapture(config) {
1299
1525
  if (!sourceId) return;
1300
1526
  var safeSource = null;
1301
1527
  if (action !== 'remove') {
1528
+ // Quick task 261202-jwf (D 1.1): skip a source the viewer already
1529
+ // holds. The fingerprint is taken before the re-sanitize below.
1530
+ var fingerprint = styleSourceFingerprint(source);
1531
+ if (styleSourceFingerprints.get(sourceId) === fingerprint) return;
1302
1532
  safeSource = Object.assign({}, source, {
1303
1533
  sourceId: sourceId,
1304
1534
  scope: cloneStyleScope(scope || source.scope),
1305
1535
  cssText: sanitizeCssTextForSource(source.cssText || '')
1306
1536
  });
1307
1537
  safeSource.approxBytes = wireByteLength(safeSource.cssText || '');
1538
+ styleSourceFingerprints.set(sourceId, fingerprint);
1539
+ } else {
1540
+ // A remove is only meaningful for a source the viewer holds.
1541
+ if (!styleSourceFingerprints.has(sourceId)) return;
1542
+ styleSourceFingerprints.delete(sourceId);
1308
1543
  }
1309
1544
  pendingStyleSourceChanges.set(sourceId, {
1310
1545
  op: DIFF_OP.STYLE_SOURCE,
@@ -1362,6 +1597,43 @@ function createCapture(config) {
1362
1597
  scope: entry ? entry.scope : cloneStyleScope(scope)
1363
1598
  }, entry ? entry.scope : scope, reason || 'cssom-style-source-stale');
1364
1599
  });
1600
+ styleScopeSignatures.set(scopeKey, styleScopeSignature(docForScope, rootForScope));
1601
+ }
1602
+
1603
+ // Quick task 261202-jwf (D 1.4): find the known style scope an owner lives
1604
+ // in. An element (or a sheet's ownerNode) resolves through getRootNode(); a
1605
+ // constructable sheet matches the first scope whose adoptedStyleSheets holds
1606
+ // it. Returns a styleScopeRoots value, or null when no known scope matches.
1607
+ function resolveStyleScopeForOwner(owner) {
1608
+ if (!owner) return null;
1609
+ var match = null;
1610
+ var node = owner.nodeType ? owner : owner.ownerNode;
1611
+ if (node) {
1612
+ var rootNode = null;
1613
+ try {
1614
+ rootNode = typeof node.getRootNode === 'function' ? node.getRootNode() : null;
1615
+ } catch (err) {
1616
+ rootNode = null;
1617
+ }
1618
+ if (!rootNode) return null;
1619
+ styleScopeRoots.forEach(function(info) {
1620
+ if (!match && info && info.root === rootNode) match = info;
1621
+ });
1622
+ if (!match) {
1623
+ styleScopeRoots.forEach(function(info) {
1624
+ if (!match && info && info.doc === rootNode) match = info;
1625
+ });
1626
+ }
1627
+ return match;
1628
+ }
1629
+ styleScopeRoots.forEach(function(info) {
1630
+ if (match || !info || !info.root) return;
1631
+ try {
1632
+ var adopted = info.root.adoptedStyleSheets;
1633
+ if (adopted && Array.prototype.indexOf.call(adopted, owner) !== -1) match = info;
1634
+ } catch (err) { /* adoptedStyleSheets unreadable in this scope */ }
1635
+ });
1636
+ return match;
1365
1637
  }
1366
1638
 
1367
1639
  function markStyleOwnerDirty(owner, reason) {
@@ -1369,6 +1641,14 @@ function createCapture(config) {
1369
1641
  var key = owner && styleOwnerToSourceKey ? styleOwnerToSourceKey.get(owner) : '';
1370
1642
  var entry = key ? styleSourceRegistry.get(key) : null;
1371
1643
  if (!entry) {
1644
+ // An owner added after the snapshot is not registered yet: reconcile
1645
+ // the scope it lives in, and fall back to a fresh snapshot only when no
1646
+ // known scope matches (quick task 261202-jwf, D 1.4).
1647
+ var info = resolveStyleScopeForOwner(owner);
1648
+ if (info) {
1649
+ queueStyleScopeReplacement(info.scope, info.root, reason || 'cssom-style-source-stale');
1650
+ return;
1651
+ }
1372
1652
  sendCssomFreshSnapshot('cssom-style-source-stale');
1373
1653
  return;
1374
1654
  }
@@ -1419,10 +1699,19 @@ function createCapture(config) {
1419
1699
  nativeCssStyleSheetMethods = null;
1420
1700
  }
1421
1701
 
1422
- function reconcileAdoptedStyleSheetsForScope(root, scope) {
1702
+ // Periodic reconcile, run on every flush. It catches rule changes the
1703
+ // patched prototype cannot see, such as a page insertRule from an extension's
1704
+ // isolated world. It skips a scope whose cheap signature is unchanged unless
1705
+ // forceFull is set (quick task 261202-jwf, D 1.2).
1706
+ function reconcileAdoptedStyleSheetsForScope(root, scope, forceFull) {
1423
1707
  if (styleMode !== 'cssom') return;
1424
1708
  try {
1425
1709
  if (root && root.adoptedStyleSheets) {
1710
+ if (!forceFull) {
1711
+ var info = styleScopeRoots.get(styleScopeKey(scope)) || {};
1712
+ var signature = styleScopeSignature(info.doc || root.ownerDocument || document, root);
1713
+ if (styleScopeSignatures.get(styleScopeKey(scope)) === signature) return;
1714
+ }
1426
1715
  queueStyleScopeReplacement(scope, root, 'adoptedStyleSheets');
1427
1716
  }
1428
1717
  } catch (err) {
@@ -1432,9 +1721,78 @@ function createCapture(config) {
1432
1721
 
1433
1722
  function reconcileAllKnownStyleScopes() {
1434
1723
  if (styleMode !== 'cssom') return;
1724
+ // Safety net: at most once every STYLE_FULL_RECONCILE_MS, re-collect every
1725
+ // scope even when its signature is unchanged (a same-count rule edit).
1726
+ var now = Date.now();
1727
+ var forceFull = (now - lastFullStyleReconcileAt) >= STYLE_FULL_RECONCILE_MS;
1728
+ if (forceFull) lastFullStyleReconcileAt = now;
1435
1729
  styleScopeRoots.forEach(function(info) {
1436
1730
  if (!info || !info.root || !info.scope) return;
1437
- reconcileAdoptedStyleSheetsForScope(info.root, info.scope);
1731
+ reconcileAdoptedStyleSheetsForScope(info.root, info.scope, forceFull);
1732
+ });
1733
+ }
1734
+
1735
+ // Visit every style scope an emitted snapshot payload carries: the document
1736
+ // scope, each shadowRoots[] entry and each frames[] entry, recursing into
1737
+ // each frame's own shadowRoots and frames. Entries without arrays are skipped.
1738
+ function forEachEmittedStyleScope(payload, visit) {
1739
+ var p = payload || {};
1740
+ function visitSidecars(container) {
1741
+ var shadowRoots = Array.isArray(container.shadowRoots) ? container.shadowRoots : [];
1742
+ for (var s = 0; s < shadowRoots.length; s++) {
1743
+ var shadow = shadowRoots[s] || {};
1744
+ if (Array.isArray(shadow.styleSources)) {
1745
+ visit({ kind: 'shadow', hostNid: String(shadow.hostNid) }, shadow.styleSources, shadow.styleStrategy || null);
1746
+ }
1747
+ }
1748
+ var frames = Array.isArray(container.frames) ? container.frames : [];
1749
+ for (var f = 0; f < frames.length; f++) {
1750
+ var frame = frames[f] || {};
1751
+ if (Array.isArray(frame.styleSources)) {
1752
+ visit({ kind: 'frame', frameNid: String(frame.frameNid) }, frame.styleSources, frame.styleStrategy || null);
1753
+ }
1754
+ visitSidecars(frame);
1755
+ }
1756
+ }
1757
+ if (Array.isArray(p.styleSources)) {
1758
+ visit({ kind: 'document' }, p.styleSources, p.styleStrategy || null);
1759
+ }
1760
+ visitSidecars(p);
1761
+ }
1762
+
1763
+ // Seed the dedupe state from an EMITTED snapshot (quick task 261202-jwf,
1764
+ // D 1.1): the viewer now holds exactly the style sources the payload carries
1765
+ // after budget pruning, and the snapshot supersedes any queued change.
1766
+ function seedStyleSourceFingerprints(payload) {
1767
+ if (styleMode !== 'cssom') return;
1768
+ styleSourceFingerprints.clear();
1769
+ pendingStyleSourceChanges.clear();
1770
+ forEachEmittedStyleScope(payload, function(scope, styleSources) {
1771
+ for (var i = 0; i < styleSources.length; i++) {
1772
+ var source = styleSources[i];
1773
+ if (!source || !source.sourceId) continue;
1774
+ styleSourceFingerprints.set(String(source.sourceId), styleSourceFingerprint(source));
1775
+ }
1776
+ });
1777
+ styleScopeSignatures.clear();
1778
+ styleScopeRoots.forEach(function(info, scopeKey) {
1779
+ if (!info || !info.root) return;
1780
+ styleScopeSignatures.set(scopeKey, styleScopeSignature(info.doc || document, info.root));
1781
+ });
1782
+ lastFullStyleReconcileAt = Date.now();
1783
+ }
1784
+
1785
+ // Heal a pruned snapshot (quick task 261202-jwf, D 1.3): when an emitted
1786
+ // scope carries fewer styleSources than it collected, reconcile that scope
1787
+ // now, so the dropped sources go out as style-source diffs in the next
1788
+ // flush. Scopes the snapshot dropped whole have no viewer host to heal.
1789
+ function healPrunedStyleScopes(payload) {
1790
+ if (styleMode !== 'cssom') return;
1791
+ forEachEmittedStyleScope(payload, function(scope, styleSources, styleStrategy) {
1792
+ if (!styleStrategy) return;
1793
+ if (styleSources.length < styleStrategy.sourceCount) {
1794
+ queueStyleScopeReplacement(scope, null, 'snapshot-style-pruned');
1795
+ }
1438
1796
  });
1439
1797
  }
1440
1798
 
@@ -1443,7 +1801,10 @@ function createCapture(config) {
1443
1801
  logger.warn('[DOM Stream] cssom resnapshot', {
1444
1802
  reason: reason || 'cssom-style-source-stale'
1445
1803
  });
1446
- safeSend(STREAM.SNAPSHOT, serializeDOM());
1804
+ var snapshot = serializeDOM();
1805
+ safeSend(STREAM.SNAPSHOT, snapshot);
1806
+ seedStyleSourceFingerprints(snapshot);
1807
+ healPrunedStyleScopes(snapshot);
1447
1808
  }
1448
1809
 
1449
1810
  function prepareFrameDocumentClone(frameDoc, bodyClone, cloneToNid) {
@@ -1528,6 +1889,7 @@ function createCapture(config) {
1528
1889
  cloneToNid: cloneToNid
1529
1890
  });
1530
1891
  if (subtreeResult && subtreeResult.drop) return null;
1892
+ neutralizeParserHostileNesting(bodyClone, cloneToNid, { rootContext: 'container' });
1531
1893
 
1532
1894
  var nodeIds = buildNodeIdSidecar(bodyClone, cloneToNid, false);
1533
1895
  var frameShadowRoots = collectShadowRootPayloads(frameDoc.body, nodeIds);
@@ -2399,6 +2761,190 @@ function createCapture(config) {
2399
2761
  return placeholder;
2400
2762
  }
2401
2763
 
2764
+ // Parser-safe serialization (quick task 261202-jwf, D 3.2). A DOM built by
2765
+ // scripts can hold nesting that HTML text cannot express (a button inside a
2766
+ // button, a link inside a link, a div inside a paragraph, a row without a
2767
+ // tbody). The viewer's parse would rewrite it, moving content and breaking
2768
+ // the positional nodeIds pairing. This pass renames such elements in the
2769
+ // DETACHED clone to <ps-node data-ps-tag="original-tag"> placeholders, which
2770
+ // the renderer restores right after its parse. It collects every element to
2771
+ // rename from the ORIGINAL clone structure first, then renames: each
2772
+ // placeholder takes the element's attributes, children, position and
2773
+ // cloneToNid entry, so element order and count are unchanged and the
2774
+ // nodeIds sidecar stays aligned. Renaming too much is harmless.
2775
+ //
2776
+ // options.rootContext: 'container' (snapshot body, frame body, shadow
2777
+ // container) never renames the root, and the root bounds every walk;
2778
+ // 'fragment' (add op and subtree response) evaluates the root too, and a
2779
+ // fragment-root table part is never stray, because the viewer's <template>
2780
+ // parse accepts table parts at its root. Returns the root to serialize,
2781
+ // which is the placeholder when a fragment root was renamed. It runs after
2782
+ // each site's last sanitizeForWire, so masking always sees original tags.
2783
+ function neutralizeParserHostileNesting(root, cloneToNid, options) {
2784
+ if (!root || typeof root.querySelectorAll !== 'function') return root;
2785
+ var opts = options || {};
2786
+ var fragment = opts.rootContext === 'fragment';
2787
+ var evaluated = fragment ? [root] : [];
2788
+ var descendants = root.querySelectorAll('*');
2789
+ for (var d = 0; d < descendants.length; d++) evaluated.push(descendants[d]);
2790
+
2791
+ function scopedParent(el) {
2792
+ if (!el || el === root) return null;
2793
+ var parent = el.parentElement;
2794
+ if (!parent) return null;
2795
+ if (parent === root) return fragment ? root : null;
2796
+ return parent;
2797
+ }
2798
+ function isHtmlIn(el, names) {
2799
+ return !!(el && el.namespaceURI === PARSER_SAFE_HTML_NAMESPACE && names && names[el.localName] === true);
2800
+ }
2801
+ function isHtmlTag(el, tag) {
2802
+ return !!(el && el.namespaceURI === PARSER_SAFE_HTML_NAMESPACE && el.localName === tag);
2803
+ }
2804
+ function hasNonWhitespaceText(el) {
2805
+ for (var n = el.firstChild; n; n = n.nextSibling) {
2806
+ if (n.nodeType === Node.TEXT_NODE && /[^ \t\n\f\r]/.test(n.data)) return true;
2807
+ }
2808
+ return false;
2809
+ }
2810
+ function stopsListWalk(el) {
2811
+ if (el.namespaceURI === PARSER_SAFE_HTML_NAMESPACE) {
2812
+ return PARSER_SAFE_SPECIAL[el.localName] === true && PARSER_SAFE_LIST_WALK_EXEMPT[el.localName] !== true;
2813
+ }
2814
+ if (el.namespaceURI === PARSER_SAFE_SVG_NAMESPACE) return PARSER_SAFE_SVG_INTEGRATION_POINTS[el.localName] === true;
2815
+ if (el.namespaceURI === PARSER_SAFE_MATHML_NAMESPACE) return PARSER_SAFE_MATHML_INTEGRATION_POINTS[el.localName] === true;
2816
+ return false;
2817
+ }
2818
+
2819
+ var marked = new Set();
2820
+ var renames = [];
2821
+ function mark(el) {
2822
+ if (marked.has(el)) return;
2823
+ marked.add(el);
2824
+ renames.push(el);
2825
+ }
2826
+ function markTablePartsUnder(node) {
2827
+ for (var c = node.firstElementChild; c; c = c.nextElementSibling) {
2828
+ if (isHtmlTag(c, 'table')) continue; // a nested table is judged on its own
2829
+ if (isHtmlIn(c, PARSER_SAFE_TABLE_PARTS)) mark(c);
2830
+ markTablePartsUnder(c);
2831
+ }
2832
+ }
2833
+ function markTable(start) {
2834
+ mark(start);
2835
+ markTablePartsUnder(start);
2836
+ }
2837
+
2838
+ // 1. A page-owned <ps-node> must never be upgraded by the viewer.
2839
+ for (var s = 0; s < evaluated.length; s++) {
2840
+ if (evaluated[s].localName === PARSER_SAFE_TAG) evaluated[s].removeAttribute(PARSER_SAFE_TAG_ATTR);
2841
+ }
2842
+
2843
+ // 2. Collect from the original structure (rules a-i).
2844
+ for (var e = 0; e < evaluated.length; e++) {
2845
+ var el = evaluated[e];
2846
+ if (el.namespaceURI !== PARSER_SAFE_HTML_NAMESPACE) continue;
2847
+ var tag = el.localName;
2848
+ var p = null;
2849
+ if (PARSER_SAFE_SAME_TAG[tag] === true) {
2850
+ for (p = scopedParent(el); p; p = scopedParent(p)) {
2851
+ if (isHtmlTag(p, tag)) { mark(el); break; }
2852
+ }
2853
+ }
2854
+ if (PARSER_SAFE_BLOCK_CLOSERS[tag] === true) {
2855
+ for (p = scopedParent(el); p; p = scopedParent(p)) {
2856
+ if (isHtmlTag(p, 'p')) mark(p);
2857
+ }
2858
+ }
2859
+ if (PARSER_SAFE_HEADINGS[tag] === true && isHtmlIn(scopedParent(el), PARSER_SAFE_HEADINGS)) mark(el);
2860
+ if (tag === 'li' || tag === 'dd' || tag === 'dt') {
2861
+ var listMatch = tag === 'li' ? PARSER_SAFE_LI : PARSER_SAFE_DD_DT;
2862
+ for (p = scopedParent(el); p; p = scopedParent(p)) {
2863
+ if (isHtmlIn(p, listMatch)) { mark(el); break; }
2864
+ if (stopsListWalk(p)) break;
2865
+ }
2866
+ }
2867
+ if ((tag === 'option' || tag === 'optgroup') && isHtmlTag(scopedParent(el), 'option')) mark(el);
2868
+ if (tag === 'optgroup' && isHtmlTag(scopedParent(el), 'optgroup')) mark(el);
2869
+ if (tag === 'select') {
2870
+ var selectDescendants = el.querySelectorAll('*');
2871
+ for (var sd = 0; sd < selectDescendants.length; sd++) {
2872
+ if (!isHtmlIn(selectDescendants[sd], PARSER_SAFE_SELECT_CONTENT)) { mark(el); break; }
2873
+ }
2874
+ }
2875
+ if (PARSER_SAFE_TEXT_ONLY[tag] === true && el.firstElementChild) mark(el);
2876
+ if (PARSER_SAFE_VOID[tag] === true && el.firstChild) mark(el);
2877
+ if (PARSER_SAFE_SHELL[tag] === true && el !== root) mark(el);
2878
+
2879
+ // 3. Tables (rule h). A table the parser would restructure is renamed
2880
+ // with all its table parts, stopping at nested tables.
2881
+ if (tag === 'table') {
2882
+ var badTable = hasNonWhitespaceText(el);
2883
+ for (var tc = el.firstElementChild; tc && !badTable; tc = tc.nextElementSibling) {
2884
+ if (isHtmlIn(tc, PARSER_SAFE_TABLE_CHILDREN)) continue;
2885
+ if (isHtmlTag(tc, 'input') && String(tc.getAttribute('type') || '').toLowerCase() === 'hidden') continue;
2886
+ badTable = true;
2887
+ }
2888
+ if (badTable) markTable(el);
2889
+ }
2890
+ if (PARSER_SAFE_TABLE_PARTS[tag] === true) {
2891
+ var partParent = scopedParent(el);
2892
+ if (!(fragment && el === root) && !isHtmlIn(partParent, PARSER_SAFE_VALID_PARENTS[tag])) {
2893
+ markTable(el); // a stray table part
2894
+ }
2895
+ var allowedChildren = PARSER_SAFE_PART_CHILDREN[tag];
2896
+ if (allowedChildren) {
2897
+ var badPart = hasNonWhitespaceText(el);
2898
+ for (var pc = el.firstElementChild; pc && !badPart; pc = pc.nextElementSibling) {
2899
+ if (!isHtmlIn(pc, allowedChildren)) badPart = true;
2900
+ }
2901
+ if (badPart) {
2902
+ // The nearest enclosing table, or the topmost part of the chain.
2903
+ var top = el;
2904
+ for (p = partParent; p; p = scopedParent(p)) {
2905
+ if (isHtmlTag(p, 'table')) { top = p; break; }
2906
+ if (isHtmlIn(p, PARSER_SAFE_TABLE_PARTS)) top = p;
2907
+ else break;
2908
+ }
2909
+ markTable(top);
2910
+ }
2911
+ }
2912
+ }
2913
+ }
2914
+
2915
+ // 4. Rename. Order and count of elements are unchanged.
2916
+ var result = root;
2917
+ for (var r = 0; r < renames.length; r++) {
2918
+ var original = renames[r];
2919
+ var placeholder = (original.ownerDocument || document).createElement(PARSER_SAFE_TAG);
2920
+ // The tag goes first, and a page-owned data-ps-tag on the original is
2921
+ // not copied, so it can never override the real tag.
2922
+ placeholder.setAttribute(PARSER_SAFE_TAG_ATTR, String(original.localName).toLowerCase());
2923
+ var attrs = original.attributes;
2924
+ for (var at = 0; at < attrs.length; at++) {
2925
+ if (String(attrs[at].name).toLowerCase() === PARSER_SAFE_TAG_ATTR) continue;
2926
+ try {
2927
+ placeholder.setAttribute(attrs[at].name, attrs[at].value);
2928
+ } catch (err) {
2929
+ try {
2930
+ placeholder.setAttributeNode(attrs[at].cloneNode(true));
2931
+ } catch (err2) { /* an attribute no element can carry is dropped */ }
2932
+ }
2933
+ }
2934
+ while (original.firstChild) placeholder.appendChild(original.firstChild);
2935
+ if (original.parentNode) {
2936
+ original.parentNode.replaceChild(placeholder, original);
2937
+ } else {
2938
+ result = placeholder;
2939
+ }
2940
+ if (cloneToNid && cloneToNid.has(original)) {
2941
+ cloneToNid.set(placeholder, cloneToNid.get(original));
2942
+ cloneToNid.delete(original);
2943
+ }
2944
+ }
2945
+ return result;
2946
+ }
2947
+
2402
2948
  function utf8ByteLength(text) {
2403
2949
  var str = String(text || '');
2404
2950
  var bytes = 0;
@@ -2490,7 +3036,7 @@ function createCapture(config) {
2490
3036
  }));
2491
3037
  }
2492
3038
 
2493
- while (currentWireLength() > SNAPSHOT_BUDGET_BYTES && (keptShadowRoots.length || keptFrames.length)) {
3039
+ while (currentWireLength() > snapshotBudgetBytes && (keptShadowRoots.length || keptFrames.length)) {
2494
3040
  var largestKind = '';
2495
3041
  var largestIndex = -1;
2496
3042
  var largestLength = -1;
@@ -2564,49 +3110,49 @@ function createCapture(config) {
2564
3110
  next.styleSources = next.styleSources.slice();
2565
3111
  }
2566
3112
 
2567
- while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.inlineStyles.length) {
3113
+ while (wireByteLength(next) > snapshotBudgetBytes && next.inlineStyles.length) {
2568
3114
  next.inlineStyles.pop();
2569
3115
  markSnapshotPayloadTruncated(next);
2570
3116
  }
2571
- while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.stylesheets.length) {
3117
+ while (wireByteLength(next) > snapshotBudgetBytes && next.stylesheets.length) {
2572
3118
  next.stylesheets.pop();
2573
3119
  markSnapshotPayloadTruncated(next);
2574
3120
  }
2575
3121
  // A single large CSSOM source can dominate the payload; shed sources before
2576
3122
  // dropping DOM structure so an oversized stylesheet cannot blow the cap.
2577
- while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Array.isArray(next.styleSources) && next.styleSources.length) {
3123
+ while (wireByteLength(next) > snapshotBudgetBytes && Array.isArray(next.styleSources) && next.styleSources.length) {
2578
3124
  next.styleSources.pop();
2579
3125
  markSnapshotPayloadTruncated(next);
2580
3126
  }
2581
3127
 
2582
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.htmlStyle) {
3128
+ if (wireByteLength(next) > snapshotBudgetBytes && next.htmlStyle) {
2583
3129
  next.htmlStyle = '';
2584
3130
  markSnapshotPayloadTruncated(next);
2585
3131
  }
2586
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.bodyStyle) {
3132
+ if (wireByteLength(next) > snapshotBudgetBytes && next.bodyStyle) {
2587
3133
  next.bodyStyle = '';
2588
3134
  markSnapshotPayloadTruncated(next);
2589
3135
  }
2590
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Object.keys(next.htmlAttrs).length) {
3136
+ if (wireByteLength(next) > snapshotBudgetBytes && Object.keys(next.htmlAttrs).length) {
2591
3137
  next.htmlAttrs = {};
2592
3138
  markSnapshotPayloadTruncated(next);
2593
3139
  }
2594
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Object.keys(next.bodyAttrs).length) {
3140
+ if (wireByteLength(next) > snapshotBudgetBytes && Object.keys(next.bodyAttrs).length) {
2595
3141
  next.bodyAttrs = {};
2596
3142
  markSnapshotPayloadTruncated(next);
2597
3143
  }
2598
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.title) {
3144
+ if (wireByteLength(next) > snapshotBudgetBytes && next.title) {
2599
3145
  next.title = '';
2600
3146
  markSnapshotPayloadTruncated(next);
2601
3147
  }
2602
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.url) {
3148
+ if (wireByteLength(next) > snapshotBudgetBytes && next.url) {
2603
3149
  next.url = '';
2604
3150
  markSnapshotPayloadTruncated(next);
2605
3151
  }
2606
3152
 
2607
- if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && clone && cloneToNid) {
3153
+ if (wireByteLength(next) > snapshotBudgetBytes && clone && cloneToNid) {
2608
3154
  var cloneEls = cloneElementsWithNodeIds(clone, cloneToNid);
2609
- for (var i = cloneEls.length - 1; i >= 0 && wireByteLength(next) > SNAPSHOT_BUDGET_BYTES; i--) {
3155
+ for (var i = cloneEls.length - 1; i >= 0 && wireByteLength(next) > snapshotBudgetBytes; i--) {
2610
3156
  var nid = cloneToNid.get(cloneEls[i]);
2611
3157
  if (markCloneNidTruncated(clone, cloneToNid, nid, truncatedNodeIds)) {
2612
3158
  next.html = clone.innerHTML || '';
@@ -2619,7 +3165,7 @@ function createCapture(config) {
2619
3165
  }
2620
3166
  }
2621
3167
 
2622
- if (wireByteLength(next) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
3168
+ if (wireByteLength(next) > messageLimitBytes) {
2623
3169
  next.html = '';
2624
3170
  next.nodeIds = [];
2625
3171
  next.shadowRoots = [];
@@ -2699,6 +3245,10 @@ function createCapture(config) {
2699
3245
  // 5. E2 text-childlist branch -- 'text' dispatch (same seam)
2700
3246
  // 6. input/change value branch -- 'input' dispatch (CAPT-05
2701
3247
  // masking seam for event-driven form state)
3248
+ // Markup paths (1, 2 and the shadow-root, frame and subtree-response
3249
+ // clones) also run neutralizeParserHostileNesting AFTER their last
3250
+ // sanitizeForWire call: a structural rename (quick task 261202-jwf), never a
3251
+ // scrub, so masking and the URL and handler strips always see original tags.
2702
3252
  // Head inline <style> text additionally routes through the 'css' dispatch
2703
3253
  // at the serializeDOM collection site (a value scrub, not a markup walk).
2704
3254
  // Side channels that BYPASS the markup scrub AND the masking helpers BY
@@ -3304,6 +3854,10 @@ function createCapture(config) {
3304
3854
  replaceWithBlockPlaceholder(blockedPairs[br].orig, blockedPairs[br].clone, blockedRects[br], cloneToNid);
3305
3855
  }
3306
3856
 
3857
+ // Parser-safe serialization (quick task 261202-jwf): after the last
3858
+ // sanitizeForWire and the placeholder swaps, before html and nodeIds.
3859
+ neutralizeParserHostileNesting(clone, cloneToNid, { rootContext: 'container' });
3860
+
3307
3861
  // Collect stylesheet URLs from document.head
3308
3862
  var stylesheets = collectStylesheetsFrom(document);
3309
3863
 
@@ -3349,10 +3903,11 @@ function createCapture(config) {
3349
3903
  }
3350
3904
  } catch (e) { /* TreeWalker unavailable in this realm; truncation falls back to no-op */ }
3351
3905
 
3352
- // SNAPSHOT_BUDGET_BYTES is the imported 80%-of-relay-cap budget. Compare
3353
- // UTF-8 wire bytes, not UTF-16 code units, so non-ASCII snapshots respect
3354
- // the relay's byte cap.
3355
- if (wireByteLength(html) > SNAPSHOT_BUDGET_BYTES) {
3906
+ // snapshotBudgetBytes is this instance's snapshot budget: by default the
3907
+ // imported 80%-of-relay-cap SNAPSHOT_BUDGET_BYTES, or the host's
3908
+ // snapshotBudgetBytes option (quick task 261202-jwf). Compare UTF-8 wire
3909
+ // bytes, not UTF-16 code units, so non-ASCII snapshots respect the byte cap.
3910
+ if (wireByteLength(html) > snapshotBudgetBytes) {
3356
3911
  truncated = true;
3357
3912
  var viewportCutoff = window.innerHeight * TRUNCATION_VIEWPORT_MULTIPLIER;
3358
3913
 
@@ -3379,9 +3934,9 @@ function createCapture(config) {
3379
3934
  // elements in document order and drops complete subtrees until under
3380
3935
  // cap. Only complete subtrees are removed -- never a mid-element cut.
3381
3936
  html = clone.innerHTML;
3382
- if (wireByteLength(html) > SNAPSHOT_BUDGET_BYTES) {
3937
+ if (wireByteLength(html) > snapshotBudgetBytes) {
3383
3938
  var cloneEls2 = cloneElementsWithNodeIds(clone, cloneToNid);
3384
- for (var u = cloneEls2.length - 1; u >= 0 && wireByteLength(clone.innerHTML) > SNAPSHOT_BUDGET_BYTES; u--) {
3939
+ for (var u = cloneEls2.length - 1; u >= 0 && wireByteLength(clone.innerHTML) > snapshotBudgetBytes; u--) {
3385
3940
  var placeholder2 = replaceWithTruncatedPlaceholder(cloneEls2[u], cloneToNid);
3386
3941
  if (placeholder2) {
3387
3942
  var placeholderNid2 = cloneToNid.get(placeholder2);
@@ -3404,6 +3959,7 @@ function createCapture(config) {
3404
3959
  var budgetInput = {
3405
3960
  html: html,
3406
3961
  nodeIds: nodeIds,
3962
+ bodyNid: BODY_NID,
3407
3963
  truncated: truncated,
3408
3964
  missingDescendants: missingDescendants,
3409
3965
  stylesheets: stylesheets,
@@ -3445,6 +4001,7 @@ function createCapture(config) {
3445
4001
  var snapshotPayload = {
3446
4002
  html: html,
3447
4003
  nodeIds: nodeIds,
4004
+ bodyNid: BODY_NID,
3448
4005
  shadowRoots: shadowRoots,
3449
4006
  frames: frames,
3450
4007
  truncated: truncated,
@@ -3572,6 +4129,8 @@ function createCapture(config) {
3572
4129
  cloneToNid: cloneToNid
3573
4130
  });
3574
4131
  if (subtreeResult && subtreeResult.drop) return null;
4132
+ // Also serves subtree-fetch responses (serializeRequestedSubtree).
4133
+ wireClone = neutralizeParserHostileNesting(wireClone, cloneToNid, { rootContext: 'fragment' });
3575
4134
  var nodeIds = buildNodeIdSidecar(wireClone, cloneToNid, true);
3576
4135
  var shadowRoots = collectShadowRootPayloads(el, nodeIds);
3577
4136
  var frames = collectFramePayloads(el, cloneToNid);
@@ -3651,7 +4210,7 @@ function createCapture(config) {
3651
4210
  streamSessionId: streamSessionId || '',
3652
4211
  snapshotId: currentSnapshotId || 0
3653
4212
  }, result);
3654
- if (response.status === 'ok' && wireByteLength(response) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
4213
+ if (response.status === 'ok' && wireByteLength(response) > messageLimitBytes) {
3655
4214
  response = Object.assign({
3656
4215
  requestId: request && request.requestId != null ? String(request.requestId) : '',
3657
4216
  nid: request && request.nid != null ? String(request.nid) : '',
@@ -3750,7 +4309,7 @@ function createCapture(config) {
3750
4309
  if (wireDroppedWithAncestors(added.parentElement)) continue;
3751
4310
  if (blockedWithAncestors(added.parentElement)) continue;
3752
4311
 
3753
- var parentNid = getTrackedNodeId(m.target);
4312
+ var parentNid = mutationTargetNid(m.target);
3754
4313
  if (!parentNid) continue; // Parent not tracked
3755
4314
 
3756
4315
  var addedPayload = processAddedNode(added);
@@ -3837,8 +4396,13 @@ function createCapture(config) {
3837
4396
  && (attrNameLower === 'href' || attrNameLower === 'media' || attrNameLower === 'disabled')) {
3838
4397
  markStyleOwnerDirty(m.target, 'link-attr-mutated');
3839
4398
  }
3840
- var targetNid = getTrackedNodeId(m.target);
4399
+ var targetNid = mutationTargetNid(m.target);
3841
4400
  if (!targetNid) continue;
4401
+ // The snapshot's computed shell bodyStyle owns the mirror body's style
4402
+ // attribute (serializeShellAttributes already excludes style), so a
4403
+ // raw style op on the body would overwrite it with the page's inline
4404
+ // declarations only. Body style changes are never streamed.
4405
+ if (targetNid === BODY_NID && attrNameLower === 'style') continue;
3842
4406
 
3843
4407
  if (attrTargetTag === 'iframe' && attrNameLower === 'src') {
3844
4408
  registerFrameLoadListener(m.target, targetNid);
@@ -4007,13 +4571,13 @@ function createCapture(config) {
4007
4571
 
4008
4572
  function boundMutationDiffForBudget(diff, options) {
4009
4573
  if (!diff) return null;
4010
- if (wireByteLength(mutationPayloadForBudget([diff], options)) <= RELAY_PER_MESSAGE_LIMIT_BYTES) return diff;
4574
+ if (wireByteLength(mutationPayloadForBudget([diff], options)) <= messageLimitBytes) return diff;
4011
4575
  var bounded = null;
4012
4576
  if (diff.op === DIFF_OP.ADD) bounded = boundedAddPlaceholder(diff);
4013
4577
  if (diff.op === DIFF_OP.FRAME) bounded = boundedFramePlaceholder(diff);
4014
4578
  if (diff.op === DIFF_OP.SHADOW_ROOT) bounded = boundedShadowRootPlaceholder(diff);
4015
4579
  if (!bounded) return null;
4016
- return wireByteLength(mutationPayloadForBudget([bounded], options)) <= RELAY_PER_MESSAGE_LIMIT_BYTES
4580
+ return wireByteLength(mutationPayloadForBudget([bounded], options)) <= messageLimitBytes
4017
4581
  ? bounded
4018
4582
  : null;
4019
4583
  }
@@ -4032,14 +4596,14 @@ function createCapture(config) {
4032
4596
  continue;
4033
4597
  }
4034
4598
  var singlePayload = mutationPayloadForBudget([diff], options);
4035
- if (wireByteLength(singlePayload) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
4599
+ if (wireByteLength(singlePayload) > messageLimitBytes) {
4036
4600
  logger.warn('[DOM Stream] mutation diff dropped over budget', {
4037
4601
  op: diff && diff.op ? diff.op : ''
4038
4602
  });
4039
4603
  continue;
4040
4604
  }
4041
4605
  var nextChunk = chunk.concat([diff]);
4042
- if (chunk.length && wireByteLength(mutationPayloadForBudget(nextChunk, options)) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
4606
+ if (chunk.length && wireByteLength(mutationPayloadForBudget(nextChunk, options)) > messageLimitBytes) {
4043
4607
  safeSend(STREAM.MUTATIONS, mutationPayloadForBudget(chunk, options));
4044
4608
  chunk = [diff];
4045
4609
  } else {
@@ -4331,6 +4895,8 @@ function createCapture(config) {
4331
4895
  nextNodeId = 1;
4332
4896
  var snapshot = serializeDOM();
4333
4897
  safeSend(STREAM.SNAPSHOT, snapshot);
4898
+ seedStyleSourceFingerprints(snapshot);
4899
+ healPrunedStyleScopes(snapshot);
4334
4900
  startMutationStream();
4335
4901
  startValueCapture();
4336
4902
  startScrollTracker();
@@ -4383,6 +4949,7 @@ function createCapture(config) {
4383
4949
  if (!streaming) return null;
4384
4950
  if (!element || element.nodeType !== Node.ELEMENT_NODE) return null;
4385
4951
  if (element.isConnected === false && !getMutationFrameRecord(element)) return null;
4952
+ // document.body deliberately resolves to null: BODY_NID is a structural anchor for body-level diffs, not an addressable element.
4386
4953
  return getTrackedNodeId(element);
4387
4954
  }
4388
4955