@full-self-browsing/phantom-stream 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +263 -0
  3. package/bin/phantom-stream.js +193 -0
  4. package/dist/types/adapters/bookmarklet.d.ts +22 -0
  5. package/dist/types/adapters/bookmarklet.d.ts.map +1 -0
  6. package/dist/types/adapters/browser-inject.d.ts +7 -0
  7. package/dist/types/adapters/browser-inject.d.ts.map +1 -0
  8. package/dist/types/adapters/extension.d.ts +43 -0
  9. package/dist/types/adapters/extension.d.ts.map +1 -0
  10. package/dist/types/adapters/playwright-inject.d.ts +2 -0
  11. package/dist/types/adapters/playwright-inject.d.ts.map +1 -0
  12. package/dist/types/adapters/playwright.d.ts +14 -0
  13. package/dist/types/adapters/playwright.d.ts.map +1 -0
  14. package/dist/types/capture/index.d.ts +241 -0
  15. package/dist/types/capture/index.d.ts.map +1 -0
  16. package/dist/types/index.d.ts +6 -0
  17. package/dist/types/index.d.ts.map +1 -0
  18. package/dist/types/protocol/constants.d.ts +35 -0
  19. package/dist/types/protocol/constants.d.ts.map +1 -0
  20. package/dist/types/protocol/envelope.d.ts +41 -0
  21. package/dist/types/protocol/envelope.d.ts.map +1 -0
  22. package/dist/types/protocol/index.d.ts +5 -0
  23. package/dist/types/protocol/index.d.ts.map +1 -0
  24. package/dist/types/protocol/messages.d.ts +520 -0
  25. package/dist/types/protocol/messages.d.ts.map +1 -0
  26. package/dist/types/protocol/remote-control.d.ts +70 -0
  27. package/dist/types/protocol/remote-control.d.ts.map +1 -0
  28. package/dist/types/relay/backends/ws.d.ts +39 -0
  29. package/dist/types/relay/backends/ws.d.ts.map +1 -0
  30. package/dist/types/relay/index.d.ts +4 -0
  31. package/dist/types/relay/index.d.ts.map +1 -0
  32. package/dist/types/relay/limits.d.ts +54 -0
  33. package/dist/types/relay/limits.d.ts.map +1 -0
  34. package/dist/types/relay/relay.d.ts +73 -0
  35. package/dist/types/relay/relay.d.ts.map +1 -0
  36. package/dist/types/renderer/diff.d.ts +62 -0
  37. package/dist/types/renderer/diff.d.ts.map +1 -0
  38. package/dist/types/renderer/index.d.ts +211 -0
  39. package/dist/types/renderer/index.d.ts.map +1 -0
  40. package/dist/types/renderer/overlays.d.ts +166 -0
  41. package/dist/types/renderer/overlays.d.ts.map +1 -0
  42. package/dist/types/renderer/sanitize.d.ts +73 -0
  43. package/dist/types/renderer/sanitize.d.ts.map +1 -0
  44. package/dist/types/renderer/snapshot.d.ts +41 -0
  45. package/dist/types/renderer/snapshot.d.ts.map +1 -0
  46. package/dist/types/transport/websocket.d.ts +44 -0
  47. package/dist/types/transport/websocket.d.ts.map +1 -0
  48. package/docs/ARCHITECTURE.md +273 -0
  49. package/docs/DESIGN-HISTORY.md +120 -0
  50. package/docs/QUICKSTARTS.md +289 -0
  51. package/docs/RELEASE.md +60 -0
  52. package/docs/SECURITY.md +156 -0
  53. package/docs/paper/OUTLINE.md +100 -0
  54. package/examples/bookmarklet-demo/demo.css +102 -0
  55. package/examples/bookmarklet-demo/server.js +297 -0
  56. package/examples/bookmarklet-demo/source.html +52 -0
  57. package/examples/bookmarklet-demo/viewer.html +48 -0
  58. package/examples/extension-mv3/demo.css +102 -0
  59. package/examples/extension-mv3/server.js +350 -0
  60. package/examples/extension-mv3/source.html +48 -0
  61. package/examples/extension-mv3/viewer.html +48 -0
  62. package/examples/loopback-mirror.html +369 -0
  63. package/examples/loopback-transport.js +65 -0
  64. package/examples/playwright-demo/demo.css +462 -0
  65. package/examples/playwright-demo/fixture.html +56 -0
  66. package/examples/playwright-demo/fixture.js +57 -0
  67. package/examples/playwright-demo/server.js +517 -0
  68. package/examples/playwright-demo/viewer.html +112 -0
  69. package/examples/playwright-demo/viewer.js +414 -0
  70. package/examples/serve.js +97 -0
  71. package/examples/two-tab-demo/demo.css +266 -0
  72. package/examples/two-tab-demo/server.js +233 -0
  73. package/examples/two-tab-demo/source.html +70 -0
  74. package/examples/two-tab-demo/source.js +213 -0
  75. package/examples/two-tab-demo/viewer.html +72 -0
  76. package/examples/two-tab-demo/viewer.js +121 -0
  77. package/package.json +107 -0
  78. package/src/adapters/bookmarklet.js +98 -0
  79. package/src/adapters/browser-inject.js +17 -0
  80. package/src/adapters/extension.js +322 -0
  81. package/src/adapters/playwright-inject.js +4401 -0
  82. package/src/adapters/playwright.js +540 -0
  83. package/src/capture/README.md +302 -0
  84. package/src/capture/index.js +4361 -0
  85. package/src/index.js +5 -0
  86. package/src/protocol/constants.js +49 -0
  87. package/src/protocol/envelope.js +75 -0
  88. package/src/protocol/index.js +4 -0
  89. package/src/protocol/messages.js +268 -0
  90. package/src/protocol/remote-control.js +300 -0
  91. package/src/relay/README.md +22 -0
  92. package/src/relay/backends/ws.js +186 -0
  93. package/src/relay/index.js +3 -0
  94. package/src/relay/limits.js +105 -0
  95. package/src/relay/relay.js +397 -0
  96. package/src/renderer/README.md +443 -0
  97. package/src/renderer/diff.js +389 -0
  98. package/src/renderer/index.js +1401 -0
  99. package/src/renderer/overlays.js +528 -0
  100. package/src/renderer/sanitize.js +366 -0
  101. package/src/renderer/snapshot.js +202 -0
  102. package/src/transport/websocket.js +553 -0
@@ -0,0 +1,4361 @@
1
+ // PhantomStream capture core: DOM snapshot + MutationObserver diff streaming.
2
+ //
3
+ // Single-file extraction of the FSB reference implementation
4
+ // (reference/extension/dom-stream.js, shipped as FSB milestone v0.9.9.1).
5
+ // Behavior is ported verbatim (parity-only, decision D-11) with exactly two
6
+ // kinds of seams applied:
7
+ //
8
+ // 1. Transport seam (D-07): every chrome.runtime.sendMessage call becomes
9
+ // transport.send(type, payload) on the host-injected Transport. Transport
10
+ // errors are routed to the injected logger and NEVER propagate into the
11
+ // capture path.
12
+ // 2. Options seams (D-08): the window.FSB namespace reads become injected
13
+ // options — logger (console-backed default), overlayProvider (overlay
14
+ // side-channel state, replaces FSB.actionGlowOverlay / FSB.highlightManager /
15
+ // FSB.overlayState reads), skipElement (the "skip our own UI" predicate,
16
+ // replaces isFsbOverlay).
17
+ //
18
+ // Lifecycle divergence (D-06, USER OVERRIDE — divergence-ledger entry D1):
19
+ // resume() re-arms observers and continues the SAME streamSessionId /
20
+ // snapshotId without re-serializing; the reference re-snapshots on resume.
21
+ // Mutations occurring while paused are missed by design (host contract).
22
+ //
23
+ // This module runs in any injection context (extension content script,
24
+ // addInitScript, bookmarklet, embedded SDK): window/document and friends are
25
+ // ambient globals dereferenced only inside createCapture and the functions it
26
+ // builds — never at module top level — so importing this file in bare Node is
27
+ // side-effect free.
28
+ //
29
+ // The 5-module split (serializer/differ/side-channels/session) is deliberately
30
+ // deferred beyond Phase 1 (D-10); parity against the reference, proven by the
31
+ // differential oracle, is the exit bar. Phase 8 replaces the inherited
32
+ // html.length truncation quirk with UTF-8 wire-byte budgeting for relay
33
+ // safety. Phase 3 SEC-01 DIVERGENCE: the
34
+ // sanitizeForWire chokepoint (a named inner function of createCapture) now
35
+ // strips on* handlers, dangerous URL schemes, srcdoc attributes and
36
+ // object/embed subtrees, and value-scrubs CSS on every serialization path --
37
+ // the reference stripped on* only on the html/body shells and passed
38
+ // javascript: URLs straight through. All strips are counted + logged (never
39
+ // silent), and ONLY detached clones / wire values are touched: the live
40
+ // observed page keeps its attributes and handlers.
41
+
42
+ import {
43
+ RELAY_PER_MESSAGE_LIMIT_BYTES,
44
+ SNAPSHOT_BUDGET_BYTES,
45
+ TRUNCATION_VIEWPORT_MULTIPLIER,
46
+ SCROLL_THROTTLE_MS,
47
+ OVERLAY_THROTTLE_MS,
48
+ MUTATION_STALE_THRESHOLD_MS,
49
+ WATCHDOG_TICK_MS,
50
+ INLINE_STYLE_MAX_BYTES,
51
+ } from '../protocol/constants.js';
52
+ import { STREAM, CONTROL, DIFF_OP, createStreamSessionId } from '../protocol/messages.js';
53
+
54
+ // RELAY_PER_MESSAGE_LIMIT_BYTES is the relay's hard per-message cap;
55
+ // SNAPSHOT_BUDGET_BYTES is the 80% truncation budget derived from it
56
+ // (replaces the reference's inline Math.floor(limit * 0.8) computation).
57
+ // Both are imported, never redefined, so capture and relay stay in sync.
58
+ void RELAY_PER_MESSAGE_LIMIT_BYTES;
59
+
60
+ // Attributes that need URL absolutification
61
+ var URL_ATTRS = ['src', 'href', 'action', 'poster', 'data'];
62
+
63
+ // Default computed style values to skip (reduces payload size)
64
+ // Keys are kebab-case to match getComputedStyle property iteration
65
+ var STYLE_DEFAULTS = {
66
+ 'display': 'block',
67
+ 'position': 'static',
68
+ 'opacity': '1',
69
+ 'visibility': 'visible',
70
+ 'overflow': 'visible',
71
+ 'transform': 'none',
72
+ 'box-shadow': 'none',
73
+ 'z-index': 'auto',
74
+ 'float': 'none',
75
+ 'clear': 'none',
76
+ 'cursor': 'auto',
77
+ 'pointer-events': 'auto',
78
+ 'text-decoration': 'none solid rgb(0, 0, 0)',
79
+ 'text-align': 'start',
80
+ 'vertical-align': 'baseline',
81
+ 'font-style': 'normal',
82
+ 'font-variant': 'normal',
83
+ 'text-transform': 'none',
84
+ 'white-space': 'normal',
85
+ 'word-break': 'normal',
86
+ 'overflow-wrap': 'normal',
87
+ 'list-style-type': 'disc',
88
+ 'border-collapse': 'separate',
89
+ 'resize': 'none'
90
+ };
91
+
92
+ // Curated list of ~85 CSS properties that matter for visual fidelity.
93
+ // Replaces iterating all 300+ computed properties which crushed performance
94
+ // on heavy pages (YouTube DOM fetch took 45s). Per D-04.
95
+ var CURATED_PROPS = [
96
+ // Layout & Box Model
97
+ 'display', 'position', 'top', 'right', 'bottom', 'left',
98
+ 'float', 'clear', 'box-sizing',
99
+ 'width', 'height', 'min-width', 'min-height', 'max-width', 'max-height',
100
+ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
101
+ 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
102
+ // Flexbox
103
+ 'flex-direction', 'flex-wrap', 'justify-content', 'align-items', 'align-self',
104
+ 'align-content', 'flex-grow', 'flex-shrink', 'flex-basis', 'order', 'gap',
105
+ // Grid
106
+ 'grid-template-columns', 'grid-template-rows', 'grid-column', 'grid-row',
107
+ 'grid-auto-flow', 'grid-gap', 'column-gap', 'row-gap',
108
+ // Visual
109
+ 'background-color', 'background-image', 'background-position', 'background-size',
110
+ 'background-repeat', 'color', 'opacity', 'visibility',
111
+ 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width',
112
+ 'border-top-style', 'border-right-style', 'border-bottom-style', 'border-left-style',
113
+ 'border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color',
114
+ 'border-radius',
115
+ 'border-top-left-radius', 'border-top-right-radius',
116
+ 'border-bottom-left-radius', 'border-bottom-right-radius',
117
+ 'box-shadow', 'outline', 'outline-color', 'outline-style', 'outline-width',
118
+ // Typography
119
+ 'font-family', 'font-size', 'font-weight', 'font-style', 'font-variant',
120
+ 'line-height', 'letter-spacing', 'word-spacing', 'text-align', 'text-decoration',
121
+ 'text-transform', 'text-indent', 'text-overflow', 'white-space', 'word-break',
122
+ 'overflow-wrap',
123
+ // Overflow & Clipping
124
+ 'overflow', 'overflow-x', 'overflow-y', 'clip', 'clip-path',
125
+ // Transform & Transition
126
+ 'transform', 'transform-origin', 'transition', 'animation',
127
+ // Table
128
+ 'border-collapse', 'border-spacing', 'table-layout',
129
+ // List
130
+ 'list-style-type', 'list-style-position',
131
+ // Misc
132
+ 'z-index', 'cursor', 'pointer-events', 'user-select',
133
+ 'vertical-align', 'resize', 'object-fit', 'object-position',
134
+ 'content', 'direction', 'unicode-bidi'
135
+ ];
136
+
137
+ var SHELL_PROPS = [
138
+ 'background-color', 'background-image', 'background-position', 'background-size',
139
+ 'background-repeat', 'color', 'font-family', 'font-size', 'font-weight',
140
+ 'font-style', 'font-variant', 'line-height', 'letter-spacing', 'word-spacing',
141
+ 'text-align', 'text-transform', 'direction', 'unicode-bidi',
142
+ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
143
+ 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
144
+ 'overflow', 'overflow-x', 'overflow-y', 'box-sizing'
145
+ ];
146
+
147
+ // =========================================================================
148
+ // SEC-01 sanitization pure helpers (module scope; absolutifyUrl shape:
149
+ // string in, string out, early-return guards, exception-to-identity).
150
+ // Blocklist policy per the Phase 3 CONTEXT locked decision: fidelity-first,
151
+ // allowlist explicitly rejected -- benign content passes byte-identical.
152
+ // =========================================================================
153
+
154
+ /**
155
+ * Remove every character with code <= 0x20 (C0 controls + space) from a
156
+ * string. Browsers' URL parsers strip tab/LF/CR anywhere in a URL and trim
157
+ * leading/trailing C0-or-space, so an obfuscated "jav\tascript:" normalizes
158
+ * to a live javascript: URL at navigation time; stripping the FULL <= 0x20
159
+ * range before scheme-matching is strictly more aggressive than the parser,
160
+ * closing the whitespace-obfuscation class (threat T-03-02).
161
+ * @param {string} value
162
+ * @returns {string}
163
+ */
164
+ function stripLowChars(value) {
165
+ var out = '';
166
+ for (var i = 0; i < value.length; i++) {
167
+ if (value.charCodeAt(i) > 0x20) out += value.charAt(i);
168
+ }
169
+ return out;
170
+ }
171
+
172
+ /**
173
+ * True when a URL-ish attribute value carries a script-capable scheme:
174
+ * javascript:, vbscript:, or data:text/html. The check runs AFTER stripping
175
+ * chars <= 0x20 (see stripLowChars) and is case-insensitive. data:image/*
176
+ * values are allowed (canvas swaps and inline images depend on them); the
177
+ * scheme list is centralized HERE -- one place to add schemes.
178
+ * @param {string} value
179
+ * @returns {boolean}
180
+ */
181
+ function hasDangerousScheme(value) {
182
+ if (!value || typeof value !== 'string') return false;
183
+ var compact = stripLowChars(value).toLowerCase();
184
+ return compact.indexOf('javascript:') === 0
185
+ || compact.indexOf('vbscript:') === 0
186
+ || compact.indexOf('data:text/html') === 0;
187
+ }
188
+
189
+ /**
190
+ * Minimal srcset candidate parser for the URL+descriptor forms this project
191
+ * emits. Unlike split(','), it keeps commas inside data:image URLs attached
192
+ * to the URL token, so a benign data candidate cannot turn into a bogus
193
+ * relative fetch candidate when one hostile sibling forces a rebuild.
194
+ * @param {string} srcset
195
+ * @returns {{url: string, descriptor: string}[]}
196
+ */
197
+ function parseSrcsetCandidates(srcset) {
198
+ var raw = String(srcset == null ? '' : srcset);
199
+ var out = [];
200
+ var i = 0;
201
+ while (i < raw.length) {
202
+ while (i < raw.length && /[\s,]/.test(raw.charAt(i))) i++;
203
+ var urlStart = i;
204
+ var isData = raw.slice(i, i + 5).toLowerCase() === 'data:';
205
+ while (i < raw.length
206
+ && !/\s/.test(raw.charAt(i))
207
+ && (isData || raw.charAt(i) !== ',')) {
208
+ i++;
209
+ }
210
+ var url = raw.slice(urlStart, i);
211
+ while (i < raw.length && /\s/.test(raw.charAt(i))) i++;
212
+ var descriptorStart = i;
213
+ while (i < raw.length && raw.charAt(i) !== ',') i++;
214
+ var descriptor = raw.slice(descriptorStart, i).trim();
215
+ if (url) out.push({ url: url, descriptor: descriptor });
216
+ if (raw.charAt(i) === ',') i++;
217
+ }
218
+ return out;
219
+ }
220
+
221
+ function formatSrcsetCandidate(candidate) {
222
+ return candidate.descriptor ? candidate.url + ' ' + candidate.descriptor : candidate.url;
223
+ }
224
+
225
+ /**
226
+ * Neutralize dangerous-scheme candidate URLs inside a srcset value
227
+ * (comma-separated URL + descriptor entries). Returns the ORIGINAL string
228
+ * untouched when no candidate is dangerous, so benign srcset values stay
229
+ * byte-identical (separator re-joining only happens on the hostile path).
230
+ * @param {string} srcset
231
+ * @returns {string}
232
+ */
233
+ function scrubSrcset(srcset) {
234
+ if (!srcset) return srcset;
235
+ try {
236
+ var entries = parseSrcsetCandidates(srcset);
237
+ var kept = [];
238
+ var changed = false;
239
+ for (var i = 0; i < entries.length; i++) {
240
+ if (entries[i].url && hasDangerousScheme(entries[i].url)) {
241
+ changed = true;
242
+ continue;
243
+ }
244
+ kept.push(formatSrcsetCandidate(entries[i]));
245
+ }
246
+ return changed ? kept.join(', ') : srcset;
247
+ } catch (e) {
248
+ return srcset;
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Targeted CSS value scrub (CONTEXT decision: value scrub, not a CSS
254
+ * parser). Applied to head <style> text, style attribute values, and (plan
255
+ * 03-01 Task 2) style attr-op values. Four passes, each leaving benign CSS
256
+ * byte-identical and each idempotent (re-scrubbing scrubbed output is a
257
+ * no-op):
258
+ * 1. url() whose EXPLICIT scheme is not http/https/data:image* has its
259
+ * contents replaced with about:blank. NO-scheme url() values
260
+ * (relative paths, fragments, query-only) are ALLOWED: they resolve
261
+ * against the document base -- which is never a dangerous scheme --
262
+ * and rewriting them would break relative-asset fidelity (CONTEXT
263
+ * fidelity-first decision).
264
+ * 2. expression( occurrences are removed (legacy IE script-in-CSS).
265
+ * 3. -moz-binding declarations are removed (legacy XBL script binding).
266
+ * 4. CSS import statements survive ONLY with an explicit http(s) target
267
+ * (an import pulls a whole stylesheet -- script-equivalent blast
268
+ * radius -- so the conservative rule wins over relative fidelity);
269
+ * and the literal sequence "</style" is rewritten to "<\/style"
270
+ * (CSS string-escape, preserving evaluated string values) so captured
271
+ * CSS can never break out of the viewer's style tag.
272
+ * 5. Markup-breakout strip: any remaining tag-like sequence
273
+ * (< + optional / + letter ... up to > or end) is REMOVED, iterated to
274
+ * a fixpoint. This closes the namespace-confusion mXSS class (threat
275
+ * T-03-03, Pitfall 4): a MathML/SVG-confused parse can leave hostile
276
+ * markup (e.g. "</math><img onerror=...>") as RAW TEXT inside a style
277
+ * element, where a context-shifted re-parse materializes it as real
278
+ * elements. '<' is not valid anywhere in CSS syntax outside quoted
279
+ * strings and the legacy CDO token "<!--" (preserved -- '!' is not a
280
+ * tag start), so benign CSS passes byte-identical; content strings
281
+ * that embed literal markup are a deliberately accepted fidelity loss.
282
+ * @param {string} css
283
+ * @returns {string}
284
+ */
285
+ function scrubCssText(css) {
286
+ if (!css || typeof css !== 'string') return css;
287
+ try {
288
+ var out = css;
289
+ // Pass 1: url() scheme scrub (quoted forms may contain parens; the
290
+ // unquoted form ends at the first close-paren like the CSS tokenizer).
291
+ out = out.replace(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)"'][^)]*))?\s*\)/gi,
292
+ function (match, dq, sq, bare) {
293
+ var inner = dq !== undefined ? dq : (sq !== undefined ? sq : (bare || ''));
294
+ var compact = stripLowChars(inner);
295
+ var schemeMatch = /^([a-zA-Z][a-zA-Z0-9+.\-]*):/.exec(compact);
296
+ if (!schemeMatch) return match; // no explicit scheme: allowed (base-relative)
297
+ var scheme = schemeMatch[1].toLowerCase();
298
+ if (scheme === 'http' || scheme === 'https') return match;
299
+ if (scheme === 'data' && /^data:image\//i.test(compact)) return match;
300
+ return 'url(about:blank)';
301
+ });
302
+ // Pass 2: expression( removal.
303
+ out = out.replace(/expression\s*\(/gi, '');
304
+ // Pass 3: -moz-binding declaration removal (up to the next ; or }).
305
+ out = out.replace(/-moz-binding[^;}]*/gi, '');
306
+ // Pass 4a: @import scheme gate (statement removed unless explicit http(s)).
307
+ out = out.replace(/@import\b[^;]*(;|$)/gi, function (stmt) {
308
+ return /^@import\s+(?:url\(\s*)?['"]?\s*https?:/i.test(stmt) ? stmt : '';
309
+ });
310
+ // Pass 4b: </style breakout neutralization (string-escape rewrite runs
311
+ // BEFORE the markup strip so evaluated string values are preserved for
312
+ // the canonical breakout; the escaped "<\/style" no longer matches the
313
+ // tag-like pattern below).
314
+ out = out.replace(/<\/style/gi, '<\\/style');
315
+ // Pass 5: markup-breakout strip, iterated to a fixpoint so adversarial
316
+ // nesting ("<i<img x>mg ...") cannot reassemble a tag across passes.
317
+ var tagLike = /<\/?[a-zA-Z][^>]*(?:>|$)/g;
318
+ for (;;) {
319
+ var next = out.replace(tagLike, '');
320
+ if (next === out) break;
321
+ out = next;
322
+ }
323
+ return out;
324
+ } catch (e) {
325
+ return css;
326
+ }
327
+ }
328
+
329
+ /**
330
+ * rrweb-compatible default text mask (SEC-03, 03-RESEARCH Pattern 5 / Code
331
+ * Examples; cited from rrweb-snapshot snapshot.ts:
332
+ * textContent.replace(/[\S]/g, '*')). Every non-whitespace character becomes
333
+ * '*'; whitespace and string length are preserved so masked text keeps its
334
+ * layout shape. Idempotent: masking masked output is a no-op.
335
+ * @param {string} text
336
+ * @returns {string}
337
+ */
338
+ function defaultMaskText(text) {
339
+ return String(text).replace(/[\S]/g, '*');
340
+ }
341
+
342
+ /**
343
+ * The host-injected message sink. `send` mirrors the fire-and-forget
344
+ * semantics of the reference's messaging call: the capture core never awaits
345
+ * delivery and never lets a transport failure propagate into the capture
346
+ * path (errors are routed to the injected logger instead — D-07).
347
+ *
348
+ * The implementation is injected rather than imported so this module works
349
+ * in any runtime and injection context (same pattern as the LZCodec seam in
350
+ * src/protocol/envelope.js).
351
+ *
352
+ * @typedef {Object} Transport
353
+ * @property {(type: string, payload: Object) => void} send
354
+ * Deliver one wire message. `type` is a STREAM.* protocol type; `payload`
355
+ * is the message payload (snapshot object, mutation batch, etc.).
356
+ * @property {() => void} [flush]
357
+ * Optional: drain any host-side buffering. Defaults to a no-op; invoked
358
+ * once at the end of stop().
359
+ */
360
+
361
+ /**
362
+ * @typedef {Object} CaptureLogger
363
+ * @property {(...args: *) => void} info
364
+ * @property {(...args: *) => void} warn
365
+ * @property {(...args: *) => void} error
366
+ */
367
+
368
+ /**
369
+ * Overlay side-channel state returned by an overlayProvider. `glow` and
370
+ * `progress` are the reference built-ins; every OTHER own enumerable key is
371
+ * forwarded on the wire as a custom overlay kind (Phase 2 VIEW-04 pass-
372
+ * through -- see broadcastOverlayState and README entry E1). The identity
373
+ * keys `streamSessionId` / `snapshotId` are reserved: the capture core
374
+ * stamps them after the provider keys, so a provider can never overwrite
375
+ * stream identity.
376
+ * @typedef {Object} OverlayState
377
+ * @property {Object|null} [glow] Action-highlight rect/state, or null
378
+ * @property {Object|null} [progress] Progress-card state, or null
379
+ */
380
+
381
+ /**
382
+ * @typedef {Object} CaptureOptions
383
+ * @property {Transport} transport
384
+ * Required. Factory throws Error('transport-send-required') when
385
+ * transport.send is not a function (factory-time validation may throw;
386
+ * the capture path after start never does).
387
+ * @property {CaptureLogger} [logger]
388
+ * Optional. Defaults to a console-backed logger.
389
+ * @property {(() => OverlayState|null)} [overlayProvider]
390
+ * Optional. Called by the overlay broadcaster to read host overlay state.
391
+ * ALL own enumerable provider keys are forwarded as overlay kinds (custom
392
+ * kinds included); glow/progress default null when omitted; the identity
393
+ * keys (streamSessionId / snapshotId) are reserved and never overwritten.
394
+ * Default null: overlay messages carry { glow: null, progress: null },
395
+ * preserving the reference's wire shape when no overlay system is present.
396
+ * @property {(el: Element) => boolean} [skipElement]
397
+ * Optional. Predicate marking elements the host wants excluded from
398
+ * capture (its own UI). Default returns false (nothing skipped).
399
+ * Applied ancestor-inclusively (closest()-like, reference parity): an
400
+ * element is excluded when the predicate matches it OR any of its
401
+ * ancestors, and skipped subtrees receive NO node-id assignment during
402
+ * serialization -- a root-only predicate (e.g. el.id === 'my-overlay')
403
+ * therefore excludes its whole subtree from both snapshots and diffs.
404
+ * @property {string} [blockSelector]
405
+ * Optional (SEC-03). CSS selector: matching elements are replaced on the
406
+ * wire by a dimension-preserving placeholder carrying ONLY rr_width /
407
+ * rr_height (px, from the live rect) and the nid -- no attributes, no
408
+ * children, no text; mutations anywhere inside a blocked subtree emit
409
+ * nothing. Invalid selectors THROW Error('invalid-mask-selector') at
410
+ * factory time (fail closed and loud -- a silently dropped mask selector
411
+ * would be a privacy leak).
412
+ * @property {string} [maskTextSelector]
413
+ * Optional (SEC-03). CSS selector: text of matching elements AND their
414
+ * descendants is masked (default mask: '*' per non-whitespace character,
415
+ * whitespace and length preserved -- rrweb-compatible). Same factory-time
416
+ * validation as blockSelector.
417
+ * @property {boolean} [maskInputs]
418
+ * Optional (SEC-03), default false. When true, ALL input/textarea/select
419
+ * values are masked. Independent of this option, input[type=password]
420
+ * values are ALWAYS masked (non-configurable rrweb-parity default).
421
+ * @property {(text: string, element: Element) => string} [maskTextFn]
422
+ * Optional (SEC-03). Custom text mask (rrweb signature). A THROWING fn
423
+ * falls back to the default asterisk mask -- raw text never leaks.
424
+ * @property {(text: string, element: Element) => string} [maskInputFn]
425
+ * Optional (SEC-03). Custom input-value mask (rrweb signature). Same
426
+ * fail-closed containment as maskTextFn.
427
+ */
428
+
429
+ /**
430
+ * @typedef {Object} CaptureHandle
431
+ * @property {() => void} start Fresh session: mint ids, snapshot, observe.
432
+ * @property {() => void} stop Stop observers (final flush included).
433
+ * @property {() => void} pause Stop observers, keep the session alive.
434
+ * @property {() => void} resume Re-arm observers; same session, no snapshot.
435
+ * @property {(element: Element) => string|null} getNodeId
436
+ * getNodeId(element) -> string|null
437
+ * Return the active PhantomStream nid for a tracked live element, or null
438
+ * for untracked, skipped, disconnected, or inactive-session nodes.
439
+ */
440
+
441
+ /**
442
+ * Create a capture instance bound to the ambient window/document.
443
+ *
444
+ * All reference module state lives in this closure, so multiple captures can
445
+ * coexist in one process (each against its own globals). No DOM access
446
+ * happens at module import time; the ambient globals are dereferenced when
447
+ * the factory and its functions run.
448
+ *
449
+ * @param {CaptureOptions} config
450
+ * @returns {CaptureHandle}
451
+ */
452
+ export function createCapture(config) {
453
+ var cfg = config || {};
454
+ var transport = cfg.transport;
455
+ // Factory-time validation is the one place allowed to throw (D-07);
456
+ // everything after start() routes errors to the logger instead.
457
+ if (!transport || typeof transport.send !== 'function') {
458
+ throw new Error('transport-send-required');
459
+ }
460
+ var logger = cfg.logger || {
461
+ info: function () { console.info.apply(console, arguments); },
462
+ warn: function () { console.warn.apply(console, arguments); },
463
+ error: function () { console.error.apply(console, arguments); }
464
+ };
465
+ var overlayProvider = cfg.overlayProvider || null;
466
+ var hostSkipElement = (typeof cfg.skipElement === 'function')
467
+ ? cfg.skipElement
468
+ : null;
469
+ var skipElement = hostSkipElement || function () { return false; };
470
+ var styleMode = cfg.styleMode === 'cssom' ? 'cssom' : 'computed';
471
+ var fetchStylesheet = typeof cfg.fetchStylesheet === 'function'
472
+ ? cfg.fetchStylesheet
473
+ : null;
474
+
475
+ // SEC-03 privacy-masking config (plan 03-03, rrweb-compatible vocabulary
476
+ // per 03-RESEARCH Pattern 5). Every option defaults OFF: with no masking
477
+ // config the wire is byte-identical to the unmasked output. The one
478
+ // non-configurable rule: input[type=password] values are ALWAYS masked
479
+ // regardless of these options. Selectors are compiled (validated) ONCE here
480
+ // at factory time -- an invalid selector THROWS Error('invalid-mask-
481
+ // selector') from compileMaskSelector (factory-time validation is the one
482
+ // allowed throwing site, the transport-send-required precedent above;
483
+ // silent masking failure would be a privacy leak, so misconfiguration
484
+ // fails closed and LOUD). Runtime matcher errors are contained
485
+ // per-element instead (Pitfall 6: capture never wedges).
486
+ var maskInputs = cfg.maskInputs === true;
487
+ var maskTextFn = (typeof cfg.maskTextFn === 'function') ? cfg.maskTextFn : null;
488
+ var maskInputFn = (typeof cfg.maskInputFn === 'function') ? cfg.maskInputFn : null;
489
+ var blockSelector = compileMaskSelector(cfg.blockSelector);
490
+ var maskTextSelector = compileMaskSelector(cfg.maskTextSelector);
491
+
492
+ /**
493
+ * Ancestor-inclusive form of the skipElement seam (reference parity:
494
+ * isFsbOverlay in reference/extension/dom-stream.js 266-276 used
495
+ * closest('[data-fsb-overlay]'), so descendants of a skipped element were
496
+ * excluded WITHOUT node-id assignment). Returns true when the host
497
+ * predicate matches el or any of its ancestor elements, so a root-only
498
+ * host predicate (e.g. el.id === 'my-overlay') excludes the whole subtree
499
+ * exactly like the reference. With no host predicate this returns false
500
+ * without walking -- wire-identical to the default seam.
501
+ *
502
+ * @param {Element} el
503
+ * @returns {boolean}
504
+ */
505
+ function skipElementWithAncestors(el) {
506
+ if (!hostSkipElement) return false;
507
+ var node = el;
508
+ while (node) {
509
+ try {
510
+ if (hostSkipElement(node)) return true;
511
+ } catch (err) {
512
+ // Host predicate errors are contained like the transport and
513
+ // overlayProvider seams (D-07): route to the logger and treat the
514
+ // element as not-skipped. The capture path never throws after the
515
+ // factory, and one bad predicate call must never lose a whole
516
+ // mutation batch.
517
+ logger.error('[DOM Stream] skipElement predicate failed', err);
518
+ return false;
519
+ }
520
+ node = node.parentElement;
521
+ }
522
+ return false;
523
+ }
524
+
525
+ /**
526
+ * Exception-contained direct (non-ancestor) form of the skipElement seam,
527
+ * used where the serializer mirrors the reference's own-element check.
528
+ * Same containment contract as skipElementWithAncestors: predicate errors
529
+ * go to the injected logger and the element is treated as not-skipped.
530
+ *
531
+ * @param {Element} el
532
+ * @returns {boolean}
533
+ */
534
+ function safeSkipElement(el) {
535
+ try {
536
+ return skipElement(el);
537
+ } catch (err) {
538
+ logger.error('[DOM Stream] skipElement predicate failed', err);
539
+ return false;
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Deliver one message through the injected transport. Mirrors the
545
+ * reference's send pattern (synchronous try/catch plus a rejection
546
+ * handler on any returned promise) with errors routed to the logger;
547
+ * transport failures never propagate into the capture path (D-07).
548
+ * @param {string} type
549
+ * @param {Object} payload
550
+ */
551
+ function safeSend(type, payload) {
552
+ try {
553
+ var result = transport.send(type, payload);
554
+ if (result && typeof result.catch === 'function') {
555
+ result.catch(function (err) {
556
+ logger.error('[DOM Stream] transport send failed', err);
557
+ });
558
+ }
559
+ } catch (err) {
560
+ logger.error('[DOM Stream] transport send failed', err);
561
+ }
562
+ }
563
+
564
+ /**
565
+ * Optional host flush hook (typeof-guarded no-op default). Invoked once at
566
+ * the end of stop() so buffering hosts get a deterministic drain point;
567
+ * with the default no-op this is wire-invisible.
568
+ */
569
+ function safeFlush() {
570
+ try {
571
+ if (typeof transport.flush === 'function') {
572
+ var result = transport.flush();
573
+ if (result && typeof result.catch === 'function') {
574
+ result.catch(function (err) {
575
+ logger.error('[DOM Stream] transport flush failed', err);
576
+ });
577
+ }
578
+ }
579
+ } catch (err) {
580
+ logger.error('[DOM Stream] transport flush failed', err);
581
+ }
582
+ }
583
+
584
+ // --- Module state (reference lines 13-34, now per-factory closure state) ---
585
+ var streaming = false;
586
+ var mutationObserver = null;
587
+ var batchTimer = null;
588
+ var pendingMutations = [];
589
+ var nextNodeId = 1;
590
+ var elementToNid = new WeakMap();
591
+ var nidToElement = new Map();
592
+ var scrollHandler = null;
593
+ var lastScrollSend = 0;
594
+ var dialogRelayActive = false;
595
+ var lastOverlayBroadcast = 0;
596
+ var streamSessionId = '';
597
+ var currentSnapshotId = 0;
598
+ var lastDrainTs = 0;
599
+ var staleFlushCount = 0;
600
+ var watchdogTimer = null;
601
+ var observedShadowRoots = new WeakSet();
602
+ var observedFrameDocuments = new Map();
603
+ var frameDocumentToNid = new WeakMap();
604
+ var frameLoadListeners = new Map();
605
+ var valueCaptureActive = false;
606
+ var valueListenerRoots = new WeakSet();
607
+ var valueListenerRecords = [];
608
+ var nativeAttachShadow = null;
609
+ var attachShadowProto = null;
610
+ var pendingStyleSourceChanges = new Map();
611
+ var styleSourceRegistry = new Map();
612
+ var styleOwnerToSourceKey = typeof WeakMap === 'function' ? new WeakMap() : null;
613
+ var styleScopeRoots = new Map();
614
+ var nativeCssStyleSheetMethods = null;
615
+ var flushingMutations = false;
616
+
617
+ // SEC-01 sanitization strip counters (closure state, staleFlushCount
618
+ // pattern). Lifecycle is PER-SESSION (03-RESEARCH.md Pitfall 3): reset in
619
+ // beginStreamSession only, never per snapshot or per flush, so strip
620
+ // totals accumulate across one whole stream session. The masked* pair is
621
+ // incremented by the SEC-03 masking pass (plan 03-03) through the same
622
+ // chokepoint.
623
+ var sanitizeCounters = {
624
+ strippedHandlers: 0, // on* handler attributes removed
625
+ blockedUrlSchemes: 0, // javascript:/vbscript:/data:text/html values neutralized
626
+ blockedSubtrees: 0, // object/embed subtrees dropped + srcdoc attrs dropped
627
+ cssScrubs: 0, // CSS values rewritten by scrubCssText
628
+ maskedTextNodes: 0, // (plan 03-03) maskTextSelector-matched text masked
629
+ maskedInputs: 0 // (plan 03-03) masked input values
630
+ };
631
+
632
+ function beginStreamSession() {
633
+ // Entropy is supplied here so the protocol helper stays pure; the wire
634
+ // format ('stream_<ts36>_<rand>') matches the reference byte-for-byte.
635
+ streamSessionId = createStreamSessionId(
636
+ Date.now(),
637
+ Math.random().toString(36).slice(2, 8)
638
+ );
639
+ currentSnapshotId = Date.now();
640
+ // SEC-01: per-session counter reset (the ONLY reset site -- see the
641
+ // declaration comment for the lifecycle rationale).
642
+ sanitizeCounters.strippedHandlers = 0;
643
+ sanitizeCounters.blockedUrlSchemes = 0;
644
+ sanitizeCounters.blockedSubtrees = 0;
645
+ sanitizeCounters.cssScrubs = 0;
646
+ sanitizeCounters.maskedTextNodes = 0;
647
+ sanitizeCounters.maskedInputs = 0;
648
+ pendingStyleSourceChanges.clear();
649
+ styleSourceRegistry.clear();
650
+ styleScopeRoots.clear();
651
+ styleOwnerToSourceKey = typeof WeakMap === 'function' ? new WeakMap() : null;
652
+ }
653
+
654
+ function getCurrentStreamMetadata() {
655
+ return {
656
+ streamSessionId: streamSessionId || '',
657
+ snapshotId: currentSnapshotId || 0
658
+ };
659
+ }
660
+
661
+ function attachStreamMetadata(payload) {
662
+ return Object.assign({}, payload || {}, getCurrentStreamMetadata());
663
+ }
664
+
665
+ function ensureNodeId(element) {
666
+ if (!element || element.nodeType !== Node.ELEMENT_NODE) return null;
667
+ var existing = elementToNid.get(element);
668
+ if (existing) return existing;
669
+ var nid = String(nextNodeId++);
670
+ elementToNid.set(element, nid);
671
+ nidToElement.set(nid, element);
672
+ return nid;
673
+ }
674
+
675
+ function reserveNodeId() {
676
+ nextNodeId++;
677
+ }
678
+
679
+ function getTrackedNodeId(element) {
680
+ if (!element || element.nodeType !== Node.ELEMENT_NODE) return null;
681
+ var nid = elementToNid.get(element);
682
+ if (!nid) return null;
683
+ if (nidToElement.get(nid) !== element) return null;
684
+ return nid;
685
+ }
686
+
687
+ function clearNodeMirror() {
688
+ elementToNid = new WeakMap();
689
+ nidToElement.clear();
690
+ }
691
+
692
+ function forgetSubtreeIdentity(root) {
693
+ if (!root || root.nodeType !== Node.ELEMENT_NODE) return;
694
+ var nodes = [root];
695
+ if (root.querySelectorAll) {
696
+ var descendants = root.querySelectorAll('*');
697
+ for (var i = 0; i < descendants.length; i++) nodes.push(descendants[i]);
698
+ }
699
+ for (var n = 0; n < nodes.length; n++) {
700
+ var nid = elementToNid.get(nodes[n]);
701
+ if (nid) {
702
+ elementToNid.delete(nodes[n]);
703
+ if (nidToElement.get(nid) === nodes[n]) nidToElement.delete(nid);
704
+ }
705
+ }
706
+ }
707
+
708
+ function assignNodeId(original, clone, cloneToNid) {
709
+ var nid = ensureNodeId(original);
710
+ if (nid && clone && clone.nodeType === Node.ELEMENT_NODE && cloneToNid) {
711
+ cloneToNid.set(clone, nid);
712
+ }
713
+ return nid;
714
+ }
715
+
716
+ function cloneElementsWithNodeIds(root, cloneToNid) {
717
+ var out = [];
718
+ if (!root || !cloneToNid) return out;
719
+ var walker = root.ownerDocument.createTreeWalker(
720
+ root,
721
+ NodeFilter.SHOW_ELEMENT,
722
+ null
723
+ );
724
+ var el;
725
+ while ((el = walker.nextNode())) {
726
+ if (cloneToNid.has(el)) out.push(el);
727
+ }
728
+ return out;
729
+ }
730
+
731
+ function buildNodeIdSidecar(root, cloneToNid, includeRoot) {
732
+ var nodeIds = [];
733
+ if (!root || !cloneToNid) return nodeIds;
734
+ if (includeRoot && root.nodeType === Node.ELEMENT_NODE && cloneToNid.has(root)) {
735
+ nodeIds.push(cloneToNid.get(root));
736
+ }
737
+ var walker = root.ownerDocument.createTreeWalker(
738
+ root,
739
+ NodeFilter.SHOW_ELEMENT,
740
+ null
741
+ );
742
+ var el;
743
+ while ((el = walker.nextNode())) {
744
+ if (cloneToNid.has(el)) nodeIds.push(cloneToNid.get(el));
745
+ }
746
+ return nodeIds;
747
+ }
748
+
749
+ function mutationObserverOptions() {
750
+ return {
751
+ childList: true,
752
+ attributes: true,
753
+ characterData: true,
754
+ subtree: true,
755
+ attributeOldValue: true
756
+ };
757
+ }
758
+
759
+ function isOpenShadowRoot(root) {
760
+ return !!(root
761
+ && root.nodeType === Node.DOCUMENT_FRAGMENT_NODE
762
+ && root.host
763
+ && root.mode === 'open');
764
+ }
765
+
766
+ function elementsUnderRoot(root) {
767
+ var elements = [];
768
+ if (!root) return elements;
769
+ if (root.nodeType === Node.ELEMENT_NODE) elements.push(root);
770
+ if (root.querySelectorAll) {
771
+ var descendants = root.querySelectorAll('*');
772
+ for (var i = 0; i < descendants.length; i++) elements.push(descendants[i]);
773
+ }
774
+ return elements;
775
+ }
776
+
777
+ function getMutationShadowHost(target) {
778
+ if (!target || typeof target.getRootNode !== 'function') return null;
779
+ var root = target.getRootNode();
780
+ if (!isOpenShadowRoot(root)) return null;
781
+ return root.host || null;
782
+ }
783
+
784
+ function shadowSlotAssignment(root) {
785
+ if (!root || !root.querySelectorAll) return 'none';
786
+ var slots = root.querySelectorAll('slot');
787
+ var hasDefault = false;
788
+ var hasNamed = false;
789
+ for (var i = 0; i < slots.length; i++) {
790
+ if (slots[i].getAttribute('name')) hasNamed = true;
791
+ else hasDefault = true;
792
+ }
793
+ if (hasNamed) return 'named';
794
+ if (hasDefault) return 'default';
795
+ return 'none';
796
+ }
797
+
798
+ function prepareShadowClone(root, container, cloneToNid) {
799
+ var liveDescendants = root && root.querySelectorAll ? root.querySelectorAll('*') : [];
800
+ var cloneDescendants = container.querySelectorAll('*');
801
+ var baseDoc = root && root.ownerDocument ? root.ownerDocument : document;
802
+ for (var i = 0; i < liveDescendants.length; i++) {
803
+ var live = liveDescendants[i];
804
+ var clone = cloneDescendants[i];
805
+ if (!clone) continue;
806
+ if (wireDroppedWithAncestors(live) || skipElementWithAncestors(live)) {
807
+ if (clone.parentNode) clone.parentNode.removeChild(clone);
808
+ continue;
809
+ }
810
+ if (blockedWithAncestors(live.parentElement)) continue;
811
+ var nid = ensureNodeId(live);
812
+ if (nid) cloneToNid.set(clone, nid);
813
+ for (var a = 0; a < URL_ATTRS.length; a++) {
814
+ var val = clone.getAttribute(URL_ATTRS[a]);
815
+ if (val) clone.setAttribute(URL_ATTRS[a], absolutifyUrl(val, baseDoc));
816
+ }
817
+ var srcset = clone.getAttribute('srcset');
818
+ if (srcset) clone.setAttribute('srcset', absolutifySrcset(srcset, baseDoc));
819
+ if (styleMode !== 'cssom') captureComputedStyles(live, clone);
820
+ }
821
+ }
822
+
823
+ function serializeOpenShadowRoot(host, hostNid) {
824
+ if (!host || !host.shadowRoot || !hostNid) return null;
825
+ var root = host.shadowRoot;
826
+ if (!isOpenShadowRoot(root)) return null;
827
+
828
+ var ownerDoc = host.ownerDocument || document;
829
+ var container = ownerDoc.createElement('div');
830
+ for (var child = root.firstChild; child; child = child.nextSibling) {
831
+ container.appendChild(child.cloneNode(true));
832
+ }
833
+
834
+ var cloneToNid = new Map();
835
+ prepareShadowClone(root, container, cloneToNid);
836
+ var subtreeResult = sanitizeForWire('subtree', {
837
+ root: container,
838
+ liveRoot: root,
839
+ cloneToNid: cloneToNid
840
+ });
841
+ if (subtreeResult && subtreeResult.drop) return null;
842
+
843
+ var shadowPayload = {
844
+ hostNid: String(hostNid),
845
+ mode: 'open',
846
+ html: container.innerHTML || '',
847
+ nodeIds: buildNodeIdSidecar(container, cloneToNid, false),
848
+ slotAssignment: shadowSlotAssignment(root)
849
+ };
850
+ if (styleMode === 'cssom') {
851
+ var shadowCssom = collectCssomStyleSourcesForScope(
852
+ ownerDoc,
853
+ { kind: 'shadow', hostNid: String(hostNid) },
854
+ { root: root }
855
+ );
856
+ shadowPayload.styleSources = shadowCssom.sources;
857
+ shadowPayload.styleStrategy = shadowCssom.strategy;
858
+ }
859
+ return shadowPayload;
860
+ }
861
+
862
+ function collectShadowRootPayloads(root, hostNodeIds, excludedHostNodeIds) {
863
+ var payloads = [];
864
+ var allowed = null;
865
+ if (Array.isArray(hostNodeIds)) {
866
+ allowed = new Set();
867
+ for (var h = 0; h < hostNodeIds.length; h++) allowed.add(String(hostNodeIds[h]));
868
+ }
869
+ var excluded = null;
870
+ if (excludedHostNodeIds && typeof excludedHostNodeIds.has === 'function') {
871
+ excluded = excludedHostNodeIds;
872
+ }
873
+
874
+ function visit(treeRoot) {
875
+ var elements = elementsUnderRoot(treeRoot);
876
+ for (var i = 0; i < elements.length; i++) {
877
+ var el = elements[i];
878
+ if (!el || !el.shadowRoot || !isOpenShadowRoot(el.shadowRoot)) continue;
879
+ var hostNid = getTrackedNodeId(el) || ensureNodeId(el);
880
+ if (!hostNid) continue;
881
+ if (allowed && !allowed.has(String(hostNid))) continue;
882
+ if (excluded && excluded.has(String(hostNid))) continue;
883
+ var payload = serializeOpenShadowRoot(el, hostNid);
884
+ if (payload) payloads.push(payload);
885
+ if (allowed && payload && Array.isArray(payload.nodeIds)) {
886
+ for (var n = 0; n < payload.nodeIds.length; n++) {
887
+ allowed.add(String(payload.nodeIds[n]));
888
+ }
889
+ }
890
+ visit(el.shadowRoot);
891
+ }
892
+ }
893
+
894
+ visit(root);
895
+ return payloads;
896
+ }
897
+
898
+ function observeOpenShadowRoot(root) {
899
+ if (!mutationObserver || !isOpenShadowRoot(root)) return;
900
+ if (observedShadowRoots.has(root)) return;
901
+ try {
902
+ mutationObserver.observe(root, mutationObserverOptions());
903
+ observedShadowRoots.add(root);
904
+ addValueListenerRoot(root);
905
+ } catch (err) {
906
+ logger.error('[DOM Stream] shadow root observe failed', err);
907
+ return;
908
+ }
909
+ observeOpenShadowRoots(root);
910
+ }
911
+
912
+ function observeOpenShadowRoots(root) {
913
+ var elements = elementsUnderRoot(root);
914
+ for (var i = 0; i < elements.length; i++) {
915
+ if (elements[i].shadowRoot && isOpenShadowRoot(elements[i].shadowRoot)) {
916
+ observeOpenShadowRoot(elements[i].shadowRoot);
917
+ }
918
+ }
919
+ }
920
+
921
+ function safeFrameSrc(src, baseDoc) {
922
+ if (!src) return '';
923
+ try {
924
+ var baseHref = baseDoc && baseDoc.location ? baseDoc.location.href : location.href;
925
+ return new URL(src, baseHref).href;
926
+ } catch (err) {
927
+ return '';
928
+ }
929
+ }
930
+
931
+ function safeFrameOrigin(src, baseDoc) {
932
+ if (!src) return '';
933
+ try {
934
+ var baseHref = baseDoc && baseDoc.location ? baseDoc.location.href : location.href;
935
+ return new URL(src, baseHref).origin;
936
+ } catch (err) {
937
+ return '';
938
+ }
939
+ }
940
+
941
+ function classifyFrame(iframe) {
942
+ var doc = null;
943
+ try {
944
+ doc = iframe && iframe.contentDocument;
945
+ } catch (err) {
946
+ logger.warn('[DOM Stream] iframe contentDocument unavailable', {
947
+ reason: 'cross-origin-or-inaccessible'
948
+ });
949
+ }
950
+ if (doc && doc.documentElement && doc.body) {
951
+ return { kind: 'same-origin', document: doc };
952
+ }
953
+ var src = iframe && iframe.getAttribute ? iframe.getAttribute('src') || '' : '';
954
+ var baseDoc = iframe && iframe.ownerDocument ? iframe.ownerDocument : document;
955
+ return {
956
+ kind: 'cross-origin',
957
+ label: 'Cross-origin iframe',
958
+ src: safeFrameSrc(src, baseDoc),
959
+ origin: safeFrameOrigin(src, baseDoc)
960
+ };
961
+ }
962
+
963
+ function appendStyleDeclaration(clone, declaration) {
964
+ if (!clone || !declaration) return;
965
+ var existing = clone.getAttribute('style') || '';
966
+ var suffix = declaration.charAt(declaration.length - 1) === ';'
967
+ ? declaration
968
+ : declaration + ';';
969
+ clone.setAttribute('style', existing ? existing + ';' + suffix : suffix);
970
+ }
971
+
972
+ function prepareIframeWireShell(live, clone) {
973
+ if (!clone || clone.nodeType !== Node.ELEMENT_NODE) return;
974
+ clone.removeAttribute('src');
975
+ clone.removeAttribute('srcdoc');
976
+ captureComputedStyles(live, clone);
977
+ appendStyleDeclaration(clone, 'pointer-events:none');
978
+ sanitizeForWire('element', { orig: live, clone: clone });
979
+ }
980
+
981
+ function prepareIframeWireShellsForClone(liveRoot, wireRoot) {
982
+ var liveElements = elementsUnderRoot(liveRoot);
983
+ var cloneElements = elementsUnderRoot(wireRoot);
984
+ for (var i = 0; i < liveElements.length && i < cloneElements.length; i++) {
985
+ var live = liveElements[i];
986
+ var clone = cloneElements[i];
987
+ var tag = clone && clone.tagName ? String(clone.tagName).toLowerCase() : '';
988
+ if (tag === 'iframe') prepareIframeWireShell(live, clone);
989
+ }
990
+ }
991
+
992
+ function collectStylesheetsFrom(doc) {
993
+ var stylesheets = [];
994
+ if (!doc || !doc.querySelectorAll) return stylesheets;
995
+ var links = doc.querySelectorAll('head link[rel="stylesheet"]');
996
+ for (var s = 0; s < links.length; s++) {
997
+ var href = links[s].getAttribute('href');
998
+ if (!href) continue;
999
+ var sheetHref = absolutifyUrl(href, doc);
1000
+ if (hasDangerousScheme(sheetHref)) {
1001
+ sanitizeCounters.blockedUrlSchemes++;
1002
+ } else {
1003
+ stylesheets.push(sheetHref);
1004
+ }
1005
+ }
1006
+ return stylesheets;
1007
+ }
1008
+
1009
+ function collectInlineStylesFrom(doc) {
1010
+ var inlineStyles = [];
1011
+ if (!doc || !doc.querySelectorAll) return inlineStyles;
1012
+ var styleTags = doc.querySelectorAll('head style');
1013
+ for (var st = 0; st < styleTags.length; st++) {
1014
+ var cssText = styleTags[st].textContent;
1015
+ if (cssText && cssText.length < INLINE_STYLE_MAX_BYTES) {
1016
+ inlineStyles.push(sanitizeForWire('css', { css: cssText }).css);
1017
+ }
1018
+ }
1019
+ return inlineStyles;
1020
+ }
1021
+
1022
+ function cloneStyleScope(scope) {
1023
+ var s = scope || {};
1024
+ var out = { kind: s.kind || 'document' };
1025
+ if (s.hostNid !== undefined && s.hostNid !== null) out.hostNid = String(s.hostNid);
1026
+ if (s.frameNid !== undefined && s.frameNid !== null) out.frameNid = String(s.frameNid);
1027
+ return out;
1028
+ }
1029
+
1030
+ function styleScopeKey(scope) {
1031
+ var s = scope || {};
1032
+ if (s.kind === 'shadow') return 'shadow:' + String(s.hostNid || '');
1033
+ if (s.kind === 'frame') return 'frame:' + String(s.frameNid || '');
1034
+ return 'document';
1035
+ }
1036
+
1037
+ function makeStyleSourceId(scope, order, ownerKind, ownerNid) {
1038
+ var prefix = styleScopeKey(scope);
1039
+ var suffix = ownerNid !== undefined && ownerNid !== null && String(ownerNid) !== ''
1040
+ ? ':' + String(ownerNid)
1041
+ : '';
1042
+ return prefix + ':' + String(order || 0) + ':' + String(ownerKind || 'style') + suffix;
1043
+ }
1044
+
1045
+ function cssRulesToText(ruleList) {
1046
+ var rules = [];
1047
+ if (!ruleList) return '';
1048
+ for (var i = 0; i < ruleList.length; i++) {
1049
+ if (ruleList[i] && ruleList[i].cssText) rules.push(String(ruleList[i].cssText));
1050
+ }
1051
+ return rules.join('\n');
1052
+ }
1053
+
1054
+ function sanitizeCssTextForSource(cssText) {
1055
+ return sanitizeForWire('css', { css: String(cssText || '') }).css;
1056
+ }
1057
+
1058
+ function buildStyleStrategy(mode, sources) {
1059
+ var list = Array.isArray(sources) ? sources : [];
1060
+ var fallbackCount = 0;
1061
+ var computedFallbackCount = 0;
1062
+ var approxCssBytes = 0;
1063
+ for (var i = 0; i < list.length; i++) {
1064
+ var source = list[i] || {};
1065
+ if (source.fallback) fallbackCount++;
1066
+ if (source.fallback && source.fallback.reason === 'computed-fallback') {
1067
+ computedFallbackCount++;
1068
+ }
1069
+ approxCssBytes += source.approxBytes || wireByteLength(source.cssText || '');
1070
+ }
1071
+ return {
1072
+ mode: mode || 'computed',
1073
+ sourceCount: list.length,
1074
+ fallbackCount: fallbackCount,
1075
+ computedFallbackCount: computedFallbackCount,
1076
+ approxCssBytes: approxCssBytes
1077
+ };
1078
+ }
1079
+
1080
+ function safeStylesheetHref(href, doc) {
1081
+ if (!href) return '';
1082
+ var resolved = absolutifyUrl(String(href), doc);
1083
+ if (!resolved || hasDangerousScheme(resolved)) {
1084
+ if (resolved) sanitizeCounters.blockedUrlSchemes++;
1085
+ return '';
1086
+ }
1087
+ return resolved;
1088
+ }
1089
+
1090
+ function ownerKindForStyleNode(node, adopted) {
1091
+ if (adopted) return 'adopted';
1092
+ var tag = node && node.tagName ? String(node.tagName).toLowerCase() : '';
1093
+ if (tag === 'link') return 'link';
1094
+ if (tag === 'style') return 'style';
1095
+ return adopted ? 'adopted' : 'constructable';
1096
+ }
1097
+
1098
+ function styleOwnerHref(ownerNode, sheet, doc) {
1099
+ var href = '';
1100
+ if (ownerNode && typeof ownerNode.getAttribute === 'function') {
1101
+ href = ownerNode.getAttribute('href') || '';
1102
+ }
1103
+ if (!href && sheet && sheet.href) href = sheet.href;
1104
+ return safeStylesheetHref(href, doc);
1105
+ }
1106
+
1107
+ function styleOwnerMedia(ownerNode, sheet) {
1108
+ if (ownerNode && typeof ownerNode.getAttribute === 'function') {
1109
+ return String(ownerNode.getAttribute('media') || '');
1110
+ }
1111
+ try {
1112
+ if (sheet && sheet.media && sheet.media.mediaText) return String(sheet.media.mediaText || '');
1113
+ } catch (err) { /* media is best-effort metadata */ }
1114
+ return '';
1115
+ }
1116
+
1117
+ function styleOwnerDisabled(ownerNode, sheet) {
1118
+ if (ownerNode && typeof ownerNode.disabled === 'boolean') return ownerNode.disabled;
1119
+ if (sheet && typeof sheet.disabled === 'boolean') return sheet.disabled;
1120
+ return false;
1121
+ }
1122
+
1123
+ function fallbackCssForScope(root) {
1124
+ var css = [];
1125
+ var elements = elementsUnderRoot(root && root.body ? root.body : root);
1126
+ for (var i = 0; i < elements.length; i++) {
1127
+ var styleText = collectComputedStyleText(elements[i], CURATED_PROPS);
1128
+ if (!styleText) continue;
1129
+ css.push('*{');
1130
+ css.push(styleText);
1131
+ css.push('}');
1132
+ break;
1133
+ }
1134
+ return css.join('');
1135
+ }
1136
+
1137
+ function styleSheetEntriesForScope(doc, root) {
1138
+ var entries = [];
1139
+ var seen = typeof WeakSet === 'function' ? new WeakSet() : null;
1140
+ var queryRoot = root && root.querySelectorAll ? root : doc;
1141
+ var nodes = [];
1142
+ if (queryRoot && queryRoot.querySelectorAll) {
1143
+ nodes = queryRoot.querySelectorAll('link[rel="stylesheet"], style');
1144
+ }
1145
+ for (var n = 0; n < nodes.length; n++) {
1146
+ var node = nodes[n];
1147
+ var sheet = node.sheet || null;
1148
+ if (sheet && seen) seen.add(sheet);
1149
+ entries.push({ sheet: sheet, ownerNode: node, adopted: false });
1150
+ }
1151
+ var adopted = [];
1152
+ try {
1153
+ adopted = root && root.adoptedStyleSheets ? root.adoptedStyleSheets : [];
1154
+ } catch (err) {
1155
+ adopted = [];
1156
+ }
1157
+ for (var a = 0; a < adopted.length; a++) {
1158
+ var adoptedSheet = adopted[a];
1159
+ if (!adoptedSheet) continue;
1160
+ if (seen && seen.has(adoptedSheet)) continue;
1161
+ if (seen) seen.add(adoptedSheet);
1162
+ entries.push({ sheet: adoptedSheet, ownerNode: null, adopted: true });
1163
+ }
1164
+ return entries;
1165
+ }
1166
+
1167
+ function sourceFromStyleSheetEntry(entry, scope, order, doc, root) {
1168
+ var e = entry || {};
1169
+ var ownerKind = ownerKindForStyleNode(e.ownerNode, e.adopted);
1170
+ var href = styleOwnerHref(e.ownerNode, e.sheet, doc);
1171
+ var cssText = '';
1172
+ var fallback = null;
1173
+ var sourceId = makeStyleSourceId(scope, order, ownerKind, '');
1174
+ var media = styleOwnerMedia(e.ownerNode, e.sheet);
1175
+ var disabled = styleOwnerDisabled(e.ownerNode, e.sheet);
1176
+
1177
+ try {
1178
+ if (e.sheet && e.sheet.cssRules) {
1179
+ cssText = cssRulesToText(e.sheet.cssRules);
1180
+ } else if (e.ownerNode && String(e.ownerNode.tagName || '').toLowerCase() === 'style') {
1181
+ cssText = String(e.ownerNode.textContent || '');
1182
+ }
1183
+ } catch (err) {
1184
+ fallback = { reason: 'cssRules-blocked' };
1185
+ }
1186
+
1187
+ if (cssText) {
1188
+ cssText = sanitizeCssTextForSource(cssText);
1189
+ } else if (fallback && href) {
1190
+ fallback = { reason: 'href-relinked' };
1191
+ } else if (fallback && fetchStylesheet) {
1192
+ try {
1193
+ var fetched = fetchStylesheet({ href: href || '', scope: cloneStyleScope(scope), ownerKind: ownerKind });
1194
+ var fetchedCss = typeof fetched === 'string'
1195
+ ? fetched
1196
+ : (fetched && typeof fetched.css === 'string' ? fetched.css : '');
1197
+ if (fetchedCss) {
1198
+ cssText = sanitizeCssTextForSource(fetchedCss);
1199
+ fallback = { reason: 'adapter-fetch' };
1200
+ }
1201
+ } catch (err2) {
1202
+ logger.warn('[DOM Stream] cssom fetch failed', {
1203
+ reason: 'adapter-fetch-failed',
1204
+ ownerKind: ownerKind
1205
+ });
1206
+ }
1207
+ }
1208
+
1209
+ if (!cssText && !href) {
1210
+ cssText = sanitizeCssTextForSource(fallbackCssForScope(root));
1211
+ ownerKind = 'fallback';
1212
+ fallback = { reason: 'computed-fallback' };
1213
+ sourceId = makeStyleSourceId(scope, order, ownerKind, '');
1214
+ }
1215
+
1216
+ return {
1217
+ sourceId: sourceId,
1218
+ scope: cloneStyleScope(scope),
1219
+ ownerKind: ownerKind,
1220
+ order: order,
1221
+ href: href || null,
1222
+ media: media,
1223
+ disabled: disabled,
1224
+ cssText: cssText || '',
1225
+ fallback: fallback,
1226
+ approxBytes: wireByteLength(cssText || '')
1227
+ };
1228
+ }
1229
+
1230
+ function registerStyleSource(source, entry, doc, root) {
1231
+ if (!source || !source.sourceId) return;
1232
+ var key = String(source.sourceId);
1233
+ styleSourceRegistry.set(key, {
1234
+ source: source,
1235
+ entry: entry || null,
1236
+ scope: cloneStyleScope(source.scope),
1237
+ doc: doc || document,
1238
+ root: root || doc || document
1239
+ });
1240
+ if (styleOwnerToSourceKey) {
1241
+ if (entry && entry.ownerNode) styleOwnerToSourceKey.set(entry.ownerNode, key);
1242
+ if (entry && entry.sheet) styleOwnerToSourceKey.set(entry.sheet, key);
1243
+ }
1244
+ }
1245
+
1246
+ function collectCssomStyleSourcesForScope(doc, scope, options) {
1247
+ var opts = options || {};
1248
+ var root = opts.root || doc;
1249
+ var sources = [];
1250
+ if (styleMode !== 'cssom' || !doc) {
1251
+ return { sources: sources, strategy: buildStyleStrategy('computed', sources) };
1252
+ }
1253
+ var entries = styleSheetEntriesForScope(doc, root);
1254
+ for (var i = 0; i < entries.length; i++) {
1255
+ var source = sourceFromStyleSheetEntry(entries[i], scope, i, doc, root);
1256
+ sources.push(source);
1257
+ registerStyleSource(source, entries[i], doc, root);
1258
+ }
1259
+ if (!sources.length) {
1260
+ var fallback = {
1261
+ sourceId: makeStyleSourceId(scope, 0, 'fallback', ''),
1262
+ scope: cloneStyleScope(scope),
1263
+ ownerKind: 'fallback',
1264
+ order: 0,
1265
+ href: null,
1266
+ media: '',
1267
+ disabled: false,
1268
+ cssText: sanitizeCssTextForSource(fallbackCssForScope(root)),
1269
+ fallback: { reason: 'computed-fallback' },
1270
+ approxBytes: 0
1271
+ };
1272
+ fallback.approxBytes = wireByteLength(fallback.cssText || '');
1273
+ sources.push(fallback);
1274
+ registerStyleSource(fallback, null, doc, root);
1275
+ }
1276
+ styleScopeRoots.set(styleScopeKey(scope), { doc: doc, root: root, scope: cloneStyleScope(scope) });
1277
+ return { sources: sources, strategy: buildStyleStrategy('cssom', sources) };
1278
+ }
1279
+
1280
+ function scheduleMutationFlush() {
1281
+ if (batchTimer) cancelAnimationFrame(batchTimer);
1282
+ batchTimer = requestAnimationFrame(flushMutations);
1283
+ }
1284
+
1285
+ function queueStyleSourceChange(action, source, scope, reason) {
1286
+ if (styleMode !== 'cssom') return;
1287
+ var sourceId = source && source.sourceId ? String(source.sourceId) : '';
1288
+ if (!sourceId) return;
1289
+ var safeSource = null;
1290
+ if (action !== 'remove') {
1291
+ safeSource = Object.assign({}, source, {
1292
+ sourceId: sourceId,
1293
+ scope: cloneStyleScope(scope || source.scope),
1294
+ cssText: sanitizeCssTextForSource(source.cssText || '')
1295
+ });
1296
+ safeSource.approxBytes = wireByteLength(safeSource.cssText || '');
1297
+ }
1298
+ pendingStyleSourceChanges.set(sourceId, {
1299
+ op: DIFF_OP.STYLE_SOURCE,
1300
+ action: action === 'remove' ? 'remove' : (action === 'upsert' ? 'upsert' : 'replace'),
1301
+ sourceId: sourceId,
1302
+ scope: cloneStyleScope(scope || (source && source.scope) || {}),
1303
+ source: safeSource,
1304
+ reason: reason || 'cssom-style-source-stale'
1305
+ });
1306
+ logger.warn('[DOM Stream] cssom style source queued', {
1307
+ action: action || 'replace',
1308
+ sourceId: sourceId,
1309
+ reason: reason || 'cssom-style-source-stale'
1310
+ });
1311
+ if (!flushingMutations) scheduleMutationFlush();
1312
+ }
1313
+
1314
+ function drainPendingStyleSourceDiffs() {
1315
+ var diffs = [];
1316
+ pendingStyleSourceChanges.forEach(function(entry) {
1317
+ var diff = {
1318
+ op: DIFF_OP.STYLE_SOURCE,
1319
+ action: entry.action,
1320
+ sourceId: entry.sourceId,
1321
+ scope: cloneStyleScope(entry.scope)
1322
+ };
1323
+ if (entry.action !== 'remove' && entry.source) diff.source = entry.source;
1324
+ diffs.push(diff);
1325
+ });
1326
+ pendingStyleSourceChanges.clear();
1327
+ return diffs;
1328
+ }
1329
+
1330
+ function queueStyleScopeReplacement(scope, root, reason) {
1331
+ if (styleMode !== 'cssom') return;
1332
+ var scopeKey = styleScopeKey(scope);
1333
+ var info = styleScopeRoots.get(scopeKey) || {};
1334
+ var docForScope = info.doc || (root && root.ownerDocument) || document;
1335
+ var rootForScope = root || info.root || docForScope;
1336
+ var before = {};
1337
+ styleSourceRegistry.forEach(function(entry, key) {
1338
+ if (styleScopeKey(entry.scope) === scopeKey) before[key] = true;
1339
+ });
1340
+ var collected = collectCssomStyleSourcesForScope(docForScope, scope, { root: rootForScope });
1341
+ for (var i = 0; i < collected.sources.length; i++) {
1342
+ var source = collected.sources[i];
1343
+ delete before[source.sourceId];
1344
+ queueStyleSourceChange('replace', source, source.scope, reason || 'cssom-style-source-stale');
1345
+ }
1346
+ Object.keys(before).forEach(function(sourceId) {
1347
+ var entry = styleSourceRegistry.get(sourceId);
1348
+ styleSourceRegistry.delete(sourceId);
1349
+ queueStyleSourceChange('remove', {
1350
+ sourceId: sourceId,
1351
+ scope: entry ? entry.scope : cloneStyleScope(scope)
1352
+ }, entry ? entry.scope : scope, reason || 'cssom-style-source-stale');
1353
+ });
1354
+ }
1355
+
1356
+ function markStyleOwnerDirty(owner, reason) {
1357
+ if (styleMode !== 'cssom') return;
1358
+ var key = owner && styleOwnerToSourceKey ? styleOwnerToSourceKey.get(owner) : '';
1359
+ var entry = key ? styleSourceRegistry.get(key) : null;
1360
+ if (!entry) {
1361
+ sendCssomFreshSnapshot('cssom-style-source-stale');
1362
+ return;
1363
+ }
1364
+ queueStyleScopeReplacement(entry.scope, entry.root, reason || 'cssom-style-source-stale');
1365
+ }
1366
+
1367
+ function patchCssStyleSheetMethods() {
1368
+ if (styleMode !== 'cssom' || nativeCssStyleSheetMethods) return;
1369
+ var proto = window && window.CSSStyleSheet && window.CSSStyleSheet.prototype;
1370
+ if (!proto) return;
1371
+ nativeCssStyleSheetMethods = {};
1372
+ ['insertRule', 'deleteRule', 'replace', 'replaceSync'].forEach(function(name) {
1373
+ if (typeof proto[name] !== 'function') return;
1374
+ nativeCssStyleSheetMethods[name] = proto[name];
1375
+ try {
1376
+ proto[name] = function patchedCssStyleSheetMethod() {
1377
+ var result = nativeCssStyleSheetMethods[name].apply(this, arguments);
1378
+ var sheet = this;
1379
+ if (name === 'replace' && result && typeof result.then === 'function') {
1380
+ result.then(function() {
1381
+ markStyleOwnerDirty(sheet, 'cssom-rule-mutated');
1382
+ }, function() {
1383
+ logger.warn('[DOM Stream] cssom hook unavailable', { reason: 'cssom-hook-unavailable' });
1384
+ sendCssomFreshSnapshot('cssom-hook-unavailable');
1385
+ });
1386
+ } else {
1387
+ markStyleOwnerDirty(sheet, 'cssom-rule-mutated');
1388
+ }
1389
+ return result;
1390
+ };
1391
+ } catch (err) {
1392
+ logger.warn('[DOM Stream] cssom hook unavailable', { reason: 'cssom-hook-unavailable' });
1393
+ sendCssomFreshSnapshot('cssom-hook-unavailable');
1394
+ }
1395
+ });
1396
+ }
1397
+
1398
+ function restoreCssStyleSheetMethods() {
1399
+ if (!nativeCssStyleSheetMethods) return;
1400
+ var proto = window && window.CSSStyleSheet && window.CSSStyleSheet.prototype;
1401
+ if (proto) {
1402
+ Object.keys(nativeCssStyleSheetMethods).forEach(function(name) {
1403
+ try {
1404
+ proto[name] = nativeCssStyleSheetMethods[name];
1405
+ } catch (err) { /* best-effort restore */ }
1406
+ });
1407
+ }
1408
+ nativeCssStyleSheetMethods = null;
1409
+ }
1410
+
1411
+ function reconcileAdoptedStyleSheetsForScope(root, scope) {
1412
+ if (styleMode !== 'cssom') return;
1413
+ try {
1414
+ if (root && root.adoptedStyleSheets) {
1415
+ queueStyleScopeReplacement(scope, root, 'adoptedStyleSheets');
1416
+ }
1417
+ } catch (err) {
1418
+ logger.warn('[DOM Stream] cssom hook unavailable', { reason: 'cssom-hook-unavailable' });
1419
+ }
1420
+ }
1421
+
1422
+ function reconcileAllKnownStyleScopes() {
1423
+ if (styleMode !== 'cssom') return;
1424
+ styleScopeRoots.forEach(function(info) {
1425
+ if (!info || !info.root || !info.scope) return;
1426
+ reconcileAdoptedStyleSheetsForScope(info.root, info.scope);
1427
+ });
1428
+ }
1429
+
1430
+ function sendCssomFreshSnapshot(reason) {
1431
+ if (styleMode !== 'cssom' || !streaming) return;
1432
+ logger.warn('[DOM Stream] cssom resnapshot', {
1433
+ reason: reason || 'cssom-style-source-stale'
1434
+ });
1435
+ safeSend(STREAM.SNAPSHOT, serializeDOM());
1436
+ }
1437
+
1438
+ function prepareFrameDocumentClone(frameDoc, bodyClone, cloneToNid) {
1439
+ var liveDescendants = frameDoc.body && frameDoc.body.querySelectorAll
1440
+ ? frameDoc.body.querySelectorAll('*')
1441
+ : [];
1442
+ var cloneDescendants = bodyClone.querySelectorAll('*');
1443
+ var toRemove = [];
1444
+ var blockedPairs = [];
1445
+
1446
+ for (var i = 0; i < liveDescendants.length; i++) {
1447
+ var live = liveDescendants[i];
1448
+ var clone = cloneDescendants[i];
1449
+ if (!clone) continue;
1450
+ var tag = clone.tagName ? String(clone.tagName).toLowerCase() : '';
1451
+
1452
+ if (wireDroppedWithAncestors(live.parentElement)) {
1453
+ reserveNodeId();
1454
+ toRemove.push(clone);
1455
+ continue;
1456
+ }
1457
+
1458
+ var elemDecision = sanitizeForWire('element', { orig: live, clone: clone });
1459
+ if (elemDecision && elemDecision.drop) {
1460
+ toRemove.push(clone);
1461
+ continue;
1462
+ }
1463
+ if (safeSkipElement(clone) || skipElementWithAncestors(clone)) {
1464
+ toRemove.push(clone);
1465
+ continue;
1466
+ }
1467
+ if (blockedWithAncestors(live.parentElement)) continue;
1468
+ if (blockMatches(live)) {
1469
+ assignNodeId(live, clone, cloneToNid);
1470
+ blockedPairs.push({ orig: live, clone: clone });
1471
+ continue;
1472
+ }
1473
+
1474
+ assignNodeId(live, clone, cloneToNid);
1475
+
1476
+ if (tag === 'iframe') {
1477
+ prepareIframeWireShell(live, clone);
1478
+ continue;
1479
+ }
1480
+
1481
+ for (var a = 0; a < URL_ATTRS.length; a++) {
1482
+ var attrVal = clone.getAttribute(URL_ATTRS[a]);
1483
+ if (attrVal) clone.setAttribute(URL_ATTRS[a], absolutifyUrl(attrVal, frameDoc));
1484
+ }
1485
+ var srcsetVal = clone.getAttribute('srcset');
1486
+ if (srcsetVal) clone.setAttribute('srcset', absolutifySrcset(srcsetVal, frameDoc));
1487
+ if (styleMode !== 'cssom') captureComputedStyles(live, clone);
1488
+ sanitizeForWire('element', { orig: live, clone: clone });
1489
+ }
1490
+
1491
+ for (var r = 0; r < toRemove.length; r++) {
1492
+ if (toRemove[r].parentNode) toRemove[r].parentNode.removeChild(toRemove[r]);
1493
+ }
1494
+ for (var b = 0; b < blockedPairs.length; b++) {
1495
+ replaceWithBlockPlaceholder(
1496
+ blockedPairs[b].orig,
1497
+ blockedPairs[b].clone,
1498
+ readBlockRect(blockedPairs[b].orig),
1499
+ cloneToNid
1500
+ );
1501
+ }
1502
+ }
1503
+
1504
+ function serializeFrameDocument(iframe, frameNid, frameDoc) {
1505
+ if (!iframe || !frameNid || !frameDoc || !frameDoc.documentElement || !frameDoc.body) {
1506
+ return null;
1507
+ }
1508
+ var bodyClone = frameDoc.body.cloneNode(true);
1509
+ var cloneToNid = new Map();
1510
+ var htmlNid = ensureNodeId(frameDoc.documentElement);
1511
+ var bodyNid = ensureNodeId(frameDoc.body);
1512
+
1513
+ prepareFrameDocumentClone(frameDoc, bodyClone, cloneToNid);
1514
+ var subtreeResult = sanitizeForWire('subtree', {
1515
+ root: bodyClone,
1516
+ liveRoot: frameDoc.body,
1517
+ cloneToNid: cloneToNid
1518
+ });
1519
+ if (subtreeResult && subtreeResult.drop) return null;
1520
+
1521
+ var nodeIds = buildNodeIdSidecar(bodyClone, cloneToNid, false);
1522
+ var frameShadowRoots = collectShadowRootPayloads(frameDoc.body, nodeIds);
1523
+ var nestedFrames = collectFramePayloads(frameDoc.body, cloneToNid);
1524
+ var framePayload = {
1525
+ frameNid: String(frameNid),
1526
+ kind: 'same-origin',
1527
+ html: bodyClone.innerHTML || '',
1528
+ nodeIds: nodeIds,
1529
+ shadowRoots: frameShadowRoots,
1530
+ htmlNid: htmlNid ? String(htmlNid) : '',
1531
+ bodyNid: bodyNid ? String(bodyNid) : '',
1532
+ frames: nestedFrames,
1533
+ stylesheets: collectStylesheetsFrom(frameDoc),
1534
+ inlineStyles: collectInlineStylesFrom(frameDoc),
1535
+ htmlAttrs: serializeShellAttributes(frameDoc.documentElement),
1536
+ bodyAttrs: serializeShellAttributes(frameDoc.body),
1537
+ htmlStyle: collectComputedStyleText(frameDoc.documentElement, SHELL_PROPS),
1538
+ bodyStyle: collectComputedStyleText(frameDoc.body, SHELL_PROPS),
1539
+ scrollX: frameDoc.defaultView ? frameDoc.defaultView.scrollX : 0,
1540
+ scrollY: frameDoc.defaultView ? frameDoc.defaultView.scrollY : 0,
1541
+ viewportWidth: frameDoc.defaultView ? frameDoc.defaultView.innerWidth : 0,
1542
+ viewportHeight: frameDoc.defaultView ? frameDoc.defaultView.innerHeight : 0,
1543
+ pageWidth: frameDoc.documentElement.scrollWidth,
1544
+ pageHeight: frameDoc.documentElement.scrollHeight,
1545
+ url: frameDoc.location ? String(frameDoc.location.href || '') : '',
1546
+ title: frameDoc.title || ''
1547
+ };
1548
+ if (styleMode === 'cssom') {
1549
+ var frameCssom = collectCssomStyleSourcesForScope(
1550
+ frameDoc,
1551
+ { kind: 'frame', frameNid: String(frameNid) },
1552
+ { root: frameDoc }
1553
+ );
1554
+ framePayload.styleSources = frameCssom.sources;
1555
+ framePayload.styleStrategy = frameCssom.strategy;
1556
+ }
1557
+ return framePayload;
1558
+ }
1559
+
1560
+ function collectFramePayloads(root, cloneToNid, excludedFrameNodeIds) {
1561
+ var payloads = [];
1562
+ if (!root) return payloads;
1563
+ var allowed = null;
1564
+ if (cloneToNid && typeof cloneToNid.forEach === 'function') {
1565
+ allowed = new Set();
1566
+ cloneToNid.forEach(function(nid) {
1567
+ if (nid !== undefined && nid !== null) allowed.add(String(nid));
1568
+ });
1569
+ }
1570
+
1571
+ var elements = elementsUnderRoot(root);
1572
+ for (var i = 0; i < elements.length; i++) {
1573
+ var iframe = elements[i];
1574
+ var tag = iframe && iframe.tagName ? String(iframe.tagName).toLowerCase() : '';
1575
+ if (tag !== 'iframe') continue;
1576
+ if (skipElementWithAncestors(iframe) || blockedWithAncestors(iframe) || wireDroppedWithAncestors(iframe)) {
1577
+ continue;
1578
+ }
1579
+ var frameNid = getTrackedNodeId(iframe) || ensureNodeId(iframe);
1580
+ if (!frameNid) continue;
1581
+ if (allowed && !allowed.has(String(frameNid))) continue;
1582
+ if (excludedFrameNodeIds && excludedFrameNodeIds.has(String(frameNid))) continue;
1583
+ var classification = classifyFrame(iframe);
1584
+ if (classification.kind === 'same-origin') {
1585
+ var sameOriginPayload = serializeFrameDocument(
1586
+ iframe,
1587
+ frameNid,
1588
+ classification.document
1589
+ );
1590
+ if (sameOriginPayload) payloads.push(sameOriginPayload);
1591
+ continue;
1592
+ }
1593
+ payloads.push(Object.assign({ frameNid: String(frameNid) }, classification));
1594
+ }
1595
+ return payloads;
1596
+ }
1597
+
1598
+ function registerFrameLoadListener(iframe, frameNid) {
1599
+ if (!iframe || !frameNid || typeof iframe.addEventListener !== 'function') return;
1600
+ var key = String(frameNid);
1601
+ var existing = frameLoadListeners.get(key);
1602
+ if (existing && existing.iframe === iframe) return;
1603
+ if (existing && existing.iframe && typeof existing.iframe.removeEventListener === 'function') {
1604
+ existing.iframe.removeEventListener('load', existing.handler);
1605
+ }
1606
+ var handler = function() {
1607
+ var classification = classifyFrame(iframe);
1608
+ if (classification.kind === 'same-origin') {
1609
+ registerFrameDocument(iframe, key, classification.document, true);
1610
+ } else {
1611
+ observedFrameDocuments.delete(key);
1612
+ }
1613
+ };
1614
+ iframe.addEventListener('load', handler);
1615
+ frameLoadListeners.set(key, { iframe: iframe, handler: handler });
1616
+ }
1617
+
1618
+ function registerFrameDocument(iframe, frameNid, frameDoc, emitRefresh) {
1619
+ if (!mutationObserver || !iframe || !frameNid || !frameDoc || !frameDoc.body) return null;
1620
+ var key = String(frameNid);
1621
+ var record = {
1622
+ iframe: iframe,
1623
+ document: frameDoc,
1624
+ root: frameDoc,
1625
+ frameNid: key
1626
+ };
1627
+ observedFrameDocuments.set(key, record);
1628
+ frameDocumentToNid.set(frameDoc, key);
1629
+ addValueListenerRoot(frameDoc);
1630
+ registerFrameLoadListener(iframe, key);
1631
+ var framePayload = serializeFrameDocument(iframe, key, frameDoc);
1632
+ try {
1633
+ mutationObserver.observe(frameDoc, mutationObserverOptions());
1634
+ } catch (err) {
1635
+ logger.warn('[DOM Stream] frame document observe failed', {
1636
+ reason: 'observe-failed'
1637
+ });
1638
+ return record;
1639
+ }
1640
+ observeOpenShadowRoots(frameDoc.body);
1641
+ observeSameOriginFrameDocuments(frameDoc.body);
1642
+ if (emitRefresh && framePayload) {
1643
+ sendMutationDiffs([{
1644
+ op: DIFF_OP.FRAME,
1645
+ frameNid: key,
1646
+ frame: framePayload
1647
+ }], { includeStaleFlushCount: false });
1648
+ }
1649
+ return record;
1650
+ }
1651
+
1652
+ function observeSameOriginFrameDocuments(root) {
1653
+ var elements = elementsUnderRoot(root);
1654
+ for (var i = 0; i < elements.length; i++) {
1655
+ var iframe = elements[i];
1656
+ var tag = iframe && iframe.tagName ? String(iframe.tagName).toLowerCase() : '';
1657
+ if (tag !== 'iframe') continue;
1658
+ if (skipElementWithAncestors(iframe) || blockedWithAncestors(iframe) || wireDroppedWithAncestors(iframe)) {
1659
+ continue;
1660
+ }
1661
+ var frameNid = getTrackedNodeId(iframe) || ensureNodeId(iframe);
1662
+ if (!frameNid) continue;
1663
+ var classification = classifyFrame(iframe);
1664
+ if (classification.kind === 'same-origin') {
1665
+ registerFrameDocument(iframe, frameNid, classification.document, false);
1666
+ } else {
1667
+ registerFrameLoadListener(iframe, frameNid);
1668
+ }
1669
+ }
1670
+ }
1671
+
1672
+ function getMutationFrameRecord(target) {
1673
+ if (!target) return null;
1674
+ var ownerDoc = target.nodeType === Node.DOCUMENT_NODE ? target : target.ownerDocument;
1675
+ if (!ownerDoc) return null;
1676
+ var frameNid = frameDocumentToNid.get(ownerDoc);
1677
+ if (!frameNid) return null;
1678
+ var record = observedFrameDocuments.get(String(frameNid));
1679
+ if (!record || record.document !== ownerDoc) return null;
1680
+ return record;
1681
+ }
1682
+
1683
+ function isInactiveFrameDocumentMutation(target) {
1684
+ if (!target) return false;
1685
+ var ownerDoc = target.nodeType === Node.DOCUMENT_NODE ? target : target.ownerDocument;
1686
+ if (!ownerDoc) return false;
1687
+ var frameNid = frameDocumentToNid.get(ownerDoc);
1688
+ if (!frameNid) return false;
1689
+ var record = observedFrameDocuments.get(String(frameNid));
1690
+ return !record || record.document !== ownerDoc;
1691
+ }
1692
+
1693
+ function scopeFrameDiff(diff, frameRecord) {
1694
+ if (diff && frameRecord && frameRecord.frameNid) {
1695
+ diff.frameNid = String(frameRecord.frameNid);
1696
+ }
1697
+ return diff;
1698
+ }
1699
+
1700
+ function isValueControl(el) {
1701
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
1702
+ var tag = el.tagName ? String(el.tagName).toLowerCase() : '';
1703
+ return tag === 'input' || tag === 'textarea' || tag === 'select';
1704
+ }
1705
+
1706
+ function selectedOptionValues(select) {
1707
+ var values = [];
1708
+ var options = select && select.options ? select.options : [];
1709
+ for (var i = 0; i < options.length; i++) {
1710
+ if (options[i].selected) values.push(String(options[i].value));
1711
+ }
1712
+ return values;
1713
+ }
1714
+
1715
+ function sanitizeInputValue(value, owner) {
1716
+ return sanitizeForWire('input', {
1717
+ value: value == null ? '' : String(value),
1718
+ owner: owner
1719
+ }).value;
1720
+ }
1721
+
1722
+ function buildValueDiff(control) {
1723
+ if (!isValueControl(control)) return null;
1724
+ if (skipElementWithAncestors(control) || blockedWithAncestors(control) || wireDroppedWithAncestors(control)) {
1725
+ return null;
1726
+ }
1727
+ var shadowHost = getMutationShadowHost(control);
1728
+ if (shadowHost && (
1729
+ skipElementWithAncestors(shadowHost)
1730
+ || blockedWithAncestors(shadowHost)
1731
+ || wireDroppedWithAncestors(shadowHost)
1732
+ )) {
1733
+ return null;
1734
+ }
1735
+ var nid = getTrackedNodeId(control);
1736
+ if (!nid) return null;
1737
+
1738
+ var tag = control.tagName ? String(control.tagName).toLowerCase() : '';
1739
+ var diff = {
1740
+ op: DIFF_OP.VALUE,
1741
+ nid: nid
1742
+ };
1743
+
1744
+ if (tag === 'select') {
1745
+ diff.value = sanitizeInputValue(control.value, control);
1746
+ var selected = selectedOptionValues(control);
1747
+ diff.selectedValues = [];
1748
+ for (var s = 0; s < selected.length; s++) {
1749
+ diff.selectedValues.push(sanitizeInputValue(selected[s], control));
1750
+ }
1751
+ return diff;
1752
+ }
1753
+
1754
+ if (tag === 'textarea') {
1755
+ diff.value = sanitizeInputValue(control.value, control);
1756
+ return diff;
1757
+ }
1758
+
1759
+ var inputType = '';
1760
+ try {
1761
+ inputType = String(control.type || control.getAttribute('type') || '').toLowerCase();
1762
+ } catch (err) {
1763
+ inputType = String(control.getAttribute && control.getAttribute('type') || '').toLowerCase();
1764
+ }
1765
+
1766
+ if (inputType === 'checkbox' || inputType === 'radio') {
1767
+ diff.checked = !!control.checked;
1768
+ diff.value = sanitizeInputValue(control.value, control);
1769
+ return diff;
1770
+ }
1771
+
1772
+ diff.value = sanitizeInputValue(control.value, control);
1773
+ return diff;
1774
+ }
1775
+
1776
+ function handleValueEvent(event) {
1777
+ if (!streaming || !event || !event.target) return;
1778
+ var diff = buildValueDiff(event.target);
1779
+ if (!diff) return;
1780
+ sendMutationDiffs(
1781
+ [scopeFrameDiff(diff, getMutationFrameRecord(event.target))],
1782
+ { includeStaleFlushCount: false }
1783
+ );
1784
+ }
1785
+
1786
+ function addValueListenerRoot(root) {
1787
+ if (!valueCaptureActive || !root || typeof root.addEventListener !== 'function') return;
1788
+ if (valueListenerRoots.has(root)) return;
1789
+ root.addEventListener('input', handleValueEvent, true);
1790
+ root.addEventListener('change', handleValueEvent, true);
1791
+ valueListenerRoots.add(root);
1792
+ valueListenerRecords.push(root);
1793
+ }
1794
+
1795
+ function addValueListenerRootsUnder(root) {
1796
+ if (root && (root.nodeType === Node.DOCUMENT_NODE || isOpenShadowRoot(root))) {
1797
+ addValueListenerRoot(root);
1798
+ }
1799
+ var elements = elementsUnderRoot(root);
1800
+ for (var i = 0; i < elements.length; i++) {
1801
+ if (elements[i].shadowRoot && isOpenShadowRoot(elements[i].shadowRoot)) {
1802
+ addValueListenerRootsUnder(elements[i].shadowRoot);
1803
+ }
1804
+ }
1805
+ }
1806
+
1807
+ function startValueCapture() {
1808
+ stopValueCapture();
1809
+ valueCaptureActive = true;
1810
+ addValueListenerRoot(document);
1811
+ addValueListenerRootsUnder(document.body);
1812
+ observedFrameDocuments.forEach(function(record) {
1813
+ if (!record || !record.document) return;
1814
+ addValueListenerRoot(record.document);
1815
+ addValueListenerRootsUnder(record.document.body);
1816
+ });
1817
+ }
1818
+
1819
+ function stopValueCapture() {
1820
+ for (var i = 0; i < valueListenerRecords.length; i++) {
1821
+ var root = valueListenerRecords[i];
1822
+ try {
1823
+ if (root && typeof root.removeEventListener === 'function') {
1824
+ root.removeEventListener('input', handleValueEvent, true);
1825
+ root.removeEventListener('change', handleValueEvent, true);
1826
+ }
1827
+ } catch (err) {
1828
+ logger.warn('[DOM Stream] value listener cleanup failed', {
1829
+ reason: 'cleanup-failed'
1830
+ });
1831
+ }
1832
+ }
1833
+ valueListenerRecords = [];
1834
+ valueListenerRoots = new WeakSet();
1835
+ valueCaptureActive = false;
1836
+ }
1837
+
1838
+ function clearObservedFrameDocuments() {
1839
+ frameLoadListeners.forEach(function(record) {
1840
+ try {
1841
+ if (record && record.iframe && typeof record.iframe.removeEventListener === 'function') {
1842
+ record.iframe.removeEventListener('load', record.handler);
1843
+ }
1844
+ } catch (err) {
1845
+ logger.warn('[DOM Stream] frame load listener cleanup failed', {
1846
+ reason: 'cleanup-failed'
1847
+ });
1848
+ }
1849
+ });
1850
+ frameLoadListeners.clear();
1851
+ observedFrameDocuments.clear();
1852
+ frameDocumentToNid = new WeakMap();
1853
+ }
1854
+
1855
+ function wrapAttachShadow() {
1856
+ if (nativeAttachShadow) return;
1857
+ var proto = window && window.Element && window.Element.prototype;
1858
+ if (!proto || typeof proto.attachShadow !== 'function') return;
1859
+ attachShadowProto = proto;
1860
+ nativeAttachShadow = proto.attachShadow;
1861
+ proto.attachShadow = function() {
1862
+ var root = nativeAttachShadow.apply(this, arguments);
1863
+ try {
1864
+ if (isOpenShadowRoot(root)) {
1865
+ observeOpenShadowRoot(root);
1866
+ if (streaming) {
1867
+ var hostNid = ensureNodeId(this);
1868
+ var payload = serializeOpenShadowRoot(this, hostNid);
1869
+ if (payload) {
1870
+ safeSend(STREAM.MUTATIONS, {
1871
+ mutations: [Object.assign({ op: DIFF_OP.SHADOW_ROOT }, payload)],
1872
+ streamSessionId: streamSessionId || '',
1873
+ snapshotId: currentSnapshotId || 0,
1874
+ staleFlushCount: staleFlushCount
1875
+ });
1876
+ }
1877
+ }
1878
+ }
1879
+ } catch (err) {
1880
+ logger.error('[DOM Stream] attachShadow wrapper failed', err);
1881
+ }
1882
+ return root;
1883
+ };
1884
+ }
1885
+
1886
+ function restoreAttachShadow() {
1887
+ if (!nativeAttachShadow || !attachShadowProto) return;
1888
+ try {
1889
+ attachShadowProto.attachShadow = nativeAttachShadow;
1890
+ } catch (err) {
1891
+ logger.error('[DOM Stream] attachShadow restore failed', err);
1892
+ }
1893
+ nativeAttachShadow = null;
1894
+ attachShadowProto = null;
1895
+ }
1896
+
1897
+ // =========================================================================
1898
+ // 0. Dialog Interception (D-01/D-03)
1899
+ // =========================================================================
1900
+
1901
+ /**
1902
+ * Inject a page-level script that monkey-patches window.alert,
1903
+ * window.confirm, and window.prompt to fire CustomEvents the capture
1904
+ * context can listen for. Per D-01/D-03: intercept native dialogs and
1905
+ * relay to the viewer. The 'fsb-dialog' / 'fsb-dialog-dismiss' event names
1906
+ * and the 'fsb-dialog-interceptor' element id are wire-adjacent and kept
1907
+ * byte-identical to the reference.
1908
+ */
1909
+ function injectDialogInterceptor() {
1910
+ // Only inject once
1911
+ if (window.__phantomStreamDisableDialogInterceptor) return;
1912
+ if (document.getElementById('fsb-dialog-interceptor')) return;
1913
+
1914
+ var script = document.createElement('script');
1915
+ script.id = 'fsb-dialog-interceptor';
1916
+ script.textContent = '(' + function() {
1917
+ var origAlert = window.alert;
1918
+ var origConfirm = window.confirm;
1919
+ var origPrompt = window.prompt;
1920
+
1921
+ window.alert = function(message) {
1922
+ document.dispatchEvent(new CustomEvent('fsb-dialog', {
1923
+ detail: { type: 'alert', message: String(message || '') }
1924
+ }));
1925
+ var result = origAlert.call(window, message);
1926
+ document.dispatchEvent(new CustomEvent('fsb-dialog-dismiss', {
1927
+ detail: { type: 'alert' }
1928
+ }));
1929
+ return result;
1930
+ };
1931
+
1932
+ window.confirm = function(message) {
1933
+ document.dispatchEvent(new CustomEvent('fsb-dialog', {
1934
+ detail: { type: 'confirm', message: String(message || '') }
1935
+ }));
1936
+ var result = origConfirm.call(window, message);
1937
+ document.dispatchEvent(new CustomEvent('fsb-dialog-dismiss', {
1938
+ detail: { type: 'confirm', result: result }
1939
+ }));
1940
+ return result;
1941
+ };
1942
+
1943
+ window.prompt = function(message, defaultValue) {
1944
+ document.dispatchEvent(new CustomEvent('fsb-dialog', {
1945
+ detail: { type: 'prompt', message: String(message || ''), defaultValue: defaultValue || '' }
1946
+ }));
1947
+ var result = origPrompt.call(window, message, defaultValue);
1948
+ document.dispatchEvent(new CustomEvent('fsb-dialog-dismiss', {
1949
+ detail: { type: 'prompt', result: result }
1950
+ }));
1951
+ return result;
1952
+ };
1953
+ } + ')();';
1954
+
1955
+ (document.head || document.documentElement).appendChild(script);
1956
+ }
1957
+
1958
+ /**
1959
+ * Listen for dialog events from the page-level interceptor and relay them
1960
+ * through the transport.
1961
+ *
1962
+ * SEC-03 side-channel masking disposition (threat T-03-26, accepted --
1963
+ * the CONTEXT masking decision's "and side channels" clause, discharged
1964
+ * explicitly here, never silently): dialog detail.message and
1965
+ * detail.defaultValue (and the overlay payload text relayed by
1966
+ * broadcastOverlayState) are NOT routed through the masking helpers.
1967
+ * They are string-only payloads with no owner element, so blockSelector /
1968
+ * maskTextSelector matching has nothing to match against; a page script
1969
+ * that echoes masked content into an alert/prompt is outside capture-side
1970
+ * masking's reach (the rrweb-parity boundary). The viewer renders these
1971
+ * via textContent only (overlays.js, threat T-02-04), so the residual is
1972
+ * privacy-scoped, not markup injection. docs/SECURITY.md lists this
1973
+ * residual (plan 03-05).
1974
+ */
1975
+ function setupDialogRelay() {
1976
+ if (dialogRelayActive) return;
1977
+ dialogRelayActive = true;
1978
+
1979
+ document.addEventListener('fsb-dialog', function(e) {
1980
+ var detail = e.detail || {};
1981
+ safeSend(STREAM.DIALOG, {
1982
+ dialog: attachStreamMetadata({
1983
+ type: detail.type,
1984
+ message: detail.message,
1985
+ defaultValue: detail.defaultValue,
1986
+ state: 'open'
1987
+ })
1988
+ });
1989
+ });
1990
+
1991
+ document.addEventListener('fsb-dialog-dismiss', function(e) {
1992
+ var detail = e.detail || {};
1993
+ safeSend(STREAM.DIALOG, {
1994
+ dialog: attachStreamMetadata({
1995
+ type: detail.type,
1996
+ result: detail.result,
1997
+ state: 'closed'
1998
+ })
1999
+ });
2000
+ });
2001
+ }
2002
+
2003
+ // =========================================================================
2004
+ // 0.4 SEC-03 Privacy-masking helpers (plan 03-03)
2005
+ // =========================================================================
2006
+
2007
+ /**
2008
+ * Validate a host-provided mask selector at factory time. Returns the
2009
+ * selector string, or null when the option was not provided. Any provided
2010
+ * value that is not a non-empty string, or that the ambient document's
2011
+ * selector engine rejects, THROWS Error('invalid-mask-selector'):
2012
+ * factory-time validation is the one allowed throwing site (D-07
2013
+ * transport-send-required precedent, 03-PATTERNS Shared Patterns), and a
2014
+ * silently dropped mask selector would be a privacy leak -- fail closed
2015
+ * and loud. Runtime matcher errors on exotic elements are contained
2016
+ * per-element by the predicates below instead (Pitfall 6).
2017
+ * @param {*} raw - cfg.blockSelector / cfg.maskTextSelector as provided
2018
+ * @returns {string|null}
2019
+ */
2020
+ function compileMaskSelector(raw) {
2021
+ if (raw === undefined || raw === null) return null;
2022
+ if (typeof raw !== 'string' || raw === '') {
2023
+ throw new Error('invalid-mask-selector');
2024
+ }
2025
+ try {
2026
+ document.querySelector(raw);
2027
+ } catch (err) {
2028
+ throw new Error('invalid-mask-selector');
2029
+ }
2030
+ return raw;
2031
+ }
2032
+
2033
+ /**
2034
+ * Ancestor-inclusive maskTextSelector predicate (closest()-shaped, the
2035
+ * skipElementWithAncestors analog -- 03-RESEARCH Pattern 6). True when el
2036
+ * or any ancestor (within el's tree: full live ancestry for live
2037
+ * elements, clone-local ancestry for detached clones) matches
2038
+ * maskTextSelector. A runtime matches/closest error on an exotic element
2039
+ * is contained in the safeSkipElement shape: routed to the logger,
2040
+ * treated as not-matched -- the capture never wedges (Pitfall 6).
2041
+ * @param {Element} el
2042
+ * @returns {boolean}
2043
+ */
2044
+ function maskTextMatches(el) {
2045
+ if (!maskTextSelector) return false;
2046
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
2047
+ try {
2048
+ return !!(el.closest && el.closest(maskTextSelector));
2049
+ } catch (err) {
2050
+ logger.error('[DOM Stream] maskTextSelector match failed', err);
2051
+ return false;
2052
+ }
2053
+ }
2054
+
2055
+ /**
2056
+ * True when the element itself matches blockSelector. Runtime selector
2057
+ * errors are contained like maskTextSelector errors: logged and treated as
2058
+ * not-blocked so capture never wedges after factory-time validation.
2059
+ * @param {Element} el
2060
+ * @returns {boolean}
2061
+ */
2062
+ function blockMatches(el) {
2063
+ if (!blockSelector) return false;
2064
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
2065
+ try {
2066
+ return !!(el.matches && el.matches(blockSelector));
2067
+ } catch (err) {
2068
+ logger.error('[DOM Stream] blockSelector match failed', err);
2069
+ return false;
2070
+ }
2071
+ }
2072
+
2073
+ /**
2074
+ * Ancestor-inclusive blockSelector predicate. Used by the differ skip
2075
+ * guards so mutations ON or INSIDE a blocked subtree emit nothing.
2076
+ * @param {Element} el
2077
+ * @returns {boolean}
2078
+ */
2079
+ function blockedWithAncestors(el) {
2080
+ if (!blockSelector) return false;
2081
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
2082
+ try {
2083
+ return !!(el.closest && el.closest(blockSelector));
2084
+ } catch (err) {
2085
+ logger.error('[DOM Stream] blockSelector match failed', err);
2086
+ return false;
2087
+ }
2088
+ }
2089
+
2090
+ /**
2091
+ * Elements intentionally absent from the wire must also be absent from the
2092
+ * live tracking graph. Otherwise descendants can receive nids before the
2093
+ * clone subtree is removed, then later leak mutations for content the
2094
+ * snapshot never mirrored.
2095
+ * @param {Element} el
2096
+ * @returns {boolean}
2097
+ */
2098
+ function isWireDroppedElement(el) {
2099
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
2100
+ var tag = el.tagName ? String(el.tagName).toLowerCase() : '';
2101
+ return tag === 'script' || tag === 'noscript' || tag === 'object' || tag === 'embed';
2102
+ }
2103
+
2104
+ /**
2105
+ * Ancestor-inclusive dropped-subtree predicate, matching the blockSelector
2106
+ * mutation guards for built-in forbidden wire roots.
2107
+ * @param {Element} el
2108
+ * @returns {boolean}
2109
+ */
2110
+ function wireDroppedWithAncestors(el) {
2111
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
2112
+ var node = el;
2113
+ while (node && node.nodeType === Node.ELEMENT_NODE) {
2114
+ if (isWireDroppedElement(node)) return true;
2115
+ node = node.parentElement;
2116
+ }
2117
+ return false;
2118
+ }
2119
+
2120
+ /**
2121
+ * Apply the text mask: maskTextFn when provided, with fail-CLOSED
2122
+ * containment -- a throwing custom fn falls back to the DEFAULT asterisk
2123
+ * mask (raw text NEVER leaks, threat T-03-16) and routes to the logger.
2124
+ * @param {string} text
2125
+ * @param {Element} el - element owning the text (rrweb fn signature)
2126
+ * @returns {string}
2127
+ */
2128
+ function safeMaskText(text, el) {
2129
+ if (maskTextFn) {
2130
+ try {
2131
+ return String(maskTextFn(String(text), el));
2132
+ } catch (err) {
2133
+ logger.error('[DOM Stream] maskTextFn failed; default mask applied', err);
2134
+ return defaultMaskText(text);
2135
+ }
2136
+ }
2137
+ return defaultMaskText(text);
2138
+ }
2139
+
2140
+ /**
2141
+ * Apply the input-value mask: maskInputFn when provided, with the same
2142
+ * fail-CLOSED containment as safeMaskText.
2143
+ * @param {string} text
2144
+ * @param {Element} el
2145
+ * @returns {string}
2146
+ */
2147
+ function safeMaskInput(text, el) {
2148
+ if (maskInputFn) {
2149
+ try {
2150
+ return String(maskInputFn(String(text), el));
2151
+ } catch (err) {
2152
+ logger.error('[DOM Stream] maskInputFn failed; default mask applied', err);
2153
+ return defaultMaskText(text);
2154
+ }
2155
+ }
2156
+ return defaultMaskText(text);
2157
+ }
2158
+
2159
+ /**
2160
+ * True when an element's value/text value must be masked. Password inputs
2161
+ * are always masked; maskInputs extends masking to input/textarea/select.
2162
+ * Select option display text is intentionally not masked here (T-03-18,
2163
+ * accepted residual); a future Phase 8 input-event capture path must route
2164
+ * typed values through safeMaskInput as well.
2165
+ * @param {Element} el
2166
+ * @returns {boolean}
2167
+ */
2168
+ function shouldMaskInput(el) {
2169
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
2170
+ var tag = el.tagName ? String(el.tagName).toLowerCase() : '';
2171
+ if (tag === 'input') {
2172
+ var inputType = '';
2173
+ try {
2174
+ inputType = String(el.type || el.getAttribute('type') || '').toLowerCase();
2175
+ } catch (e) {
2176
+ inputType = String(el.getAttribute && el.getAttribute('type') || '').toLowerCase();
2177
+ }
2178
+ if (inputType === 'password') return true;
2179
+ return maskInputs;
2180
+ }
2181
+ if (tag === 'textarea' || tag === 'select') return maskInputs;
2182
+ return false;
2183
+ }
2184
+
2185
+ /**
2186
+ * Option value attributes are the value surface of a masked select. Option
2187
+ * display labels remain the documented residual; value attrs do not.
2188
+ * @param {Element} el
2189
+ * @returns {boolean}
2190
+ */
2191
+ function isOptionUnderMaskedSelect(el) {
2192
+ if (!maskInputs || !el || el.nodeType !== Node.ELEMENT_NODE) return false;
2193
+ var tag = el.tagName ? String(el.tagName).toLowerCase() : '';
2194
+ if (tag !== 'option') return false;
2195
+ try {
2196
+ return !!(el.closest && el.closest('select'));
2197
+ } catch (e) {
2198
+ return false;
2199
+ }
2200
+ }
2201
+
2202
+ function maskOptionValue(optionClone, owner) {
2203
+ if (!optionClone || !optionClone.hasAttribute || !optionClone.hasAttribute('value')) return;
2204
+ if (optionClone._psOptionValueMasked) return;
2205
+ optionClone._psOptionValueMasked = true;
2206
+ var value = optionClone.getAttribute('value');
2207
+ var maskedValue = safeMaskInput(value == null ? '' : value, owner);
2208
+ if (maskedValue !== value) {
2209
+ optionClone.setAttribute('value', maskedValue);
2210
+ sanitizeCounters.maskedInputs++;
2211
+ }
2212
+ }
2213
+
2214
+ /**
2215
+ * Mask a clone's input/textarea/select wire value in place.
2216
+ * @param {Element} clone
2217
+ * @param {Element} owner
2218
+ */
2219
+ function maskInputCloneValue(clone, owner) {
2220
+ if (isOptionUnderMaskedSelect(owner)) {
2221
+ maskOptionValue(clone, owner);
2222
+ return;
2223
+ }
2224
+ if (!shouldMaskInput(owner)) return;
2225
+ var tag = clone.tagName ? String(clone.tagName).toLowerCase() : '';
2226
+ if (tag === 'textarea') {
2227
+ maskDirectChildText(clone, owner, safeMaskInput, 'maskedInputs');
2228
+ return;
2229
+ }
2230
+ if (tag === 'select') {
2231
+ var cloneOptions = clone.querySelectorAll ? clone.querySelectorAll('option') : [];
2232
+ var ownerOptions = owner && owner.querySelectorAll ? owner.querySelectorAll('option') : [];
2233
+ for (var o = 0; o < cloneOptions.length; o++) {
2234
+ maskOptionValue(cloneOptions[o], ownerOptions[o] || owner);
2235
+ }
2236
+ return;
2237
+ }
2238
+ if (clone.hasAttribute && clone.hasAttribute('value')) {
2239
+ var value = clone.getAttribute('value');
2240
+ var maskedValue = safeMaskInput(value == null ? '' : value, owner);
2241
+ if (maskedValue !== value) {
2242
+ clone.setAttribute('value', maskedValue);
2243
+ sanitizeCounters.maskedInputs++;
2244
+ }
2245
+ }
2246
+ }
2247
+
2248
+ /**
2249
+ * Mask every DIRECT child text node of a detached clone element in place.
2250
+ * Descendant elements are deliberately NOT recursed into: each
2251
+ * serialization walk visits every element, so descendant text is covered
2252
+ * by the descendant's own visit. Counters move only when a value actually
2253
+ * changes (SEC-01 idempotence discipline).
2254
+ * @param {Element} el - detached clone whose direct text children to mask
2255
+ * @param {Element} owner - element handed to the custom mask fn
2256
+ * @param {(text: string, el: Element) => string} maskFn - safeMaskText
2257
+ * (or safeMaskInput for textarea values)
2258
+ * @param {string} counterKey - sanitizeCounters key to increment
2259
+ */
2260
+ function maskDirectChildText(el, owner, maskFn, counterKey) {
2261
+ var child = el.firstChild;
2262
+ while (child) {
2263
+ if (child.nodeType === Node.TEXT_NODE && child.nodeValue) {
2264
+ var maskedValue = maskFn(child.nodeValue, owner);
2265
+ if (maskedValue !== child.nodeValue) {
2266
+ child.nodeValue = maskedValue;
2267
+ sanitizeCounters[counterKey]++;
2268
+ }
2269
+ }
2270
+ child = child.nextSibling;
2271
+ }
2272
+ }
2273
+
2274
+ /**
2275
+ * Read the live dimensions used by rrweb-compatible block placeholders.
2276
+ * @param {Element} el
2277
+ * @returns {{width: number, height: number}}
2278
+ */
2279
+ function readBlockRect(el) {
2280
+ try {
2281
+ var rect = el.getBoundingClientRect();
2282
+ return {
2283
+ width: rect && typeof rect.width === 'number' ? rect.width : 0,
2284
+ height: rect && typeof rect.height === 'number' ? rect.height : 0
2285
+ };
2286
+ } catch (e) {
2287
+ return { width: 0, height: 0 };
2288
+ }
2289
+ }
2290
+
2291
+ /**
2292
+ * Build the placeholder for a blocked element. It carries only dimensions:
2293
+ * no original attributes, no children, no text. Its identity travels in
2294
+ * the nodeIds sidecar.
2295
+ * @param {Document} doc
2296
+ * @param {{width: number, height: number}} rect
2297
+ * @returns {Element}
2298
+ */
2299
+ function createBlockPlaceholder(doc, rect) {
2300
+ var placeholder = doc.createElement('div');
2301
+ placeholder.setAttribute('rr_width', String(rect.width || 0) + 'px');
2302
+ placeholder.setAttribute('rr_height', String(rect.height || 0) + 'px');
2303
+ return placeholder;
2304
+ }
2305
+
2306
+ /**
2307
+ * Replace a detached clone element with its blocked placeholder.
2308
+ * @param {Element} liveEl
2309
+ * @param {Element} cloneEl
2310
+ * @param {{width: number, height: number}} rect
2311
+ * @param {Map<Element, string>} [cloneToNid]
2312
+ * @returns {Element|null}
2313
+ */
2314
+ function replaceWithBlockPlaceholder(liveEl, cloneEl, rect, cloneToNid) {
2315
+ if (!cloneEl || !cloneEl.parentNode) return null;
2316
+ var nid = cloneToNid && cloneToNid.get(cloneEl);
2317
+ if (!nid) nid = getTrackedNodeId(liveEl) || '';
2318
+ var placeholder = createBlockPlaceholder(cloneEl.ownerDocument, rect);
2319
+ cloneEl.parentNode.replaceChild(placeholder, cloneEl);
2320
+ if (cloneToNid) {
2321
+ cloneToNid.delete(cloneEl);
2322
+ if (nid) cloneToNid.set(placeholder, nid);
2323
+ }
2324
+ sanitizeCounters.blockedSubtrees++;
2325
+ return placeholder;
2326
+ }
2327
+
2328
+ function createTruncatedPlaceholder(doc) {
2329
+ var placeholder = doc.createElement('div');
2330
+ placeholder.setAttribute('data-phantomstream-truncated', 'true');
2331
+ return placeholder;
2332
+ }
2333
+
2334
+ function deleteCloneSubtreeMappings(cloneEl, cloneToNid) {
2335
+ if (!cloneEl || !cloneToNid) return;
2336
+ cloneToNid.delete(cloneEl);
2337
+ if (!cloneEl.querySelectorAll) return;
2338
+ var descendants = cloneEl.querySelectorAll('*');
2339
+ for (var i = 0; i < descendants.length; i++) {
2340
+ cloneToNid.delete(descendants[i]);
2341
+ }
2342
+ }
2343
+
2344
+ function replaceWithTruncatedPlaceholder(cloneEl, cloneToNid) {
2345
+ if (!cloneEl || !cloneEl.parentNode) return null;
2346
+ var nid = cloneToNid && cloneToNid.get(cloneEl);
2347
+ if (!nid) return null;
2348
+ var placeholder = createTruncatedPlaceholder(cloneEl.ownerDocument);
2349
+ cloneEl.parentNode.replaceChild(placeholder, cloneEl);
2350
+ deleteCloneSubtreeMappings(cloneEl, cloneToNid);
2351
+ cloneToNid.set(placeholder, nid);
2352
+ return placeholder;
2353
+ }
2354
+
2355
+ function utf8ByteLength(text) {
2356
+ var str = String(text || '');
2357
+ var bytes = 0;
2358
+ for (var i = 0; i < str.length; i++) {
2359
+ var code = str.charCodeAt(i);
2360
+ if (code < 0x80) {
2361
+ bytes += 1;
2362
+ } else if (code < 0x800) {
2363
+ bytes += 2;
2364
+ } else if (code >= 0xD800 && code <= 0xDBFF && i + 1 < str.length) {
2365
+ var next = str.charCodeAt(i + 1);
2366
+ if (next >= 0xDC00 && next <= 0xDFFF) {
2367
+ bytes += 4;
2368
+ i++;
2369
+ } else {
2370
+ bytes += 3;
2371
+ }
2372
+ } else {
2373
+ bytes += 3;
2374
+ }
2375
+ }
2376
+ return bytes;
2377
+ }
2378
+
2379
+ function wireByteLength(value) {
2380
+ try {
2381
+ var json = JSON.stringify(value);
2382
+ if (json === undefined) return 0;
2383
+ if (typeof TextEncoder !== 'undefined') {
2384
+ return new TextEncoder().encode(json).byteLength;
2385
+ }
2386
+ if (typeof Buffer !== 'undefined') {
2387
+ return Buffer.byteLength(json, 'utf8');
2388
+ }
2389
+ return utf8ByteLength(json);
2390
+ } catch (err) {
2391
+ return Infinity;
2392
+ }
2393
+ }
2394
+
2395
+ function sidecarWireLength(value) {
2396
+ return wireByteLength(value);
2397
+ }
2398
+
2399
+ function findCloneElementByNid(root, cloneToNid, nid) {
2400
+ if (!root || !cloneToNid || nid === undefined || nid === null) return null;
2401
+ var key = String(nid);
2402
+ var elements = elementsUnderRoot(root);
2403
+ for (var i = 0; i < elements.length; i++) {
2404
+ if (String(cloneToNid.get(elements[i]) || '') === key) return elements[i];
2405
+ }
2406
+ return null;
2407
+ }
2408
+
2409
+ function markCloneNidTruncated(root, cloneToNid, nid, truncatedNodeIds) {
2410
+ var cloneEl = findCloneElementByNid(root, cloneToNid, nid);
2411
+ if (!cloneEl) return false;
2412
+ var placeholder = replaceWithTruncatedPlaceholder(cloneEl, cloneToNid);
2413
+ if (!placeholder) return false;
2414
+ var placeholderNid = cloneToNid.get(placeholder) || nid;
2415
+ if (placeholderNid && truncatedNodeIds && typeof truncatedNodeIds.add === 'function') {
2416
+ truncatedNodeIds.add(String(placeholderNid));
2417
+ }
2418
+ return true;
2419
+ }
2420
+
2421
+ function truncatedPayloadForNid(doc, nid) {
2422
+ var placeholder = createTruncatedPlaceholder(doc || document);
2423
+ return {
2424
+ html: placeholder.outerHTML || '',
2425
+ nodeIds: nid ? [String(nid)] : [],
2426
+ shadowRoots: [],
2427
+ frames: [],
2428
+ truncated: true,
2429
+ missingDescendants: 1
2430
+ };
2431
+ }
2432
+
2433
+ function pruneSnapshotSidecarsForBudget(basePayload, shadowRoots, frames, clone, cloneToNid, truncatedNodeIds) {
2434
+ var base = Object.assign({}, basePayload || {});
2435
+ var keptShadowRoots = Array.isArray(shadowRoots) ? shadowRoots.slice() : [];
2436
+ var keptFrames = Array.isArray(frames) ? frames.slice() : [];
2437
+ var removed = 0;
2438
+
2439
+ function currentWireLength() {
2440
+ return wireByteLength(Object.assign({}, base, {
2441
+ shadowRoots: keptShadowRoots,
2442
+ frames: keptFrames
2443
+ }));
2444
+ }
2445
+
2446
+ while (currentWireLength() > SNAPSHOT_BUDGET_BYTES && (keptShadowRoots.length || keptFrames.length)) {
2447
+ var largestKind = '';
2448
+ var largestIndex = -1;
2449
+ var largestLength = -1;
2450
+
2451
+ for (var s = 0; s < keptShadowRoots.length; s++) {
2452
+ var shadowLength = sidecarWireLength(keptShadowRoots[s]);
2453
+ if (shadowLength > largestLength) {
2454
+ largestLength = shadowLength;
2455
+ largestKind = 'shadow';
2456
+ largestIndex = s;
2457
+ }
2458
+ }
2459
+ for (var f = 0; f < keptFrames.length; f++) {
2460
+ var frameLength = sidecarWireLength(keptFrames[f]);
2461
+ if (frameLength > largestLength) {
2462
+ largestLength = frameLength;
2463
+ largestKind = 'frame';
2464
+ largestIndex = f;
2465
+ }
2466
+ }
2467
+
2468
+ var ownerNid = '';
2469
+ if (largestKind === 'shadow') {
2470
+ var removedShadow = keptShadowRoots.splice(largestIndex, 1)[0];
2471
+ ownerNid = removedShadow && removedShadow.hostNid;
2472
+ } else if (largestKind === 'frame') {
2473
+ var removedFrame = keptFrames.splice(largestIndex, 1)[0];
2474
+ ownerNid = removedFrame && removedFrame.frameNid;
2475
+ } else {
2476
+ break;
2477
+ }
2478
+ markCloneNidTruncated(clone, cloneToNid, ownerNid, truncatedNodeIds);
2479
+ removed++;
2480
+ base.truncated = true;
2481
+ base.missingDescendants = (base.missingDescendants || 0) + 1;
2482
+ base.html = clone && clone.innerHTML ? clone.innerHTML : base.html;
2483
+ base.nodeIds = buildNodeIdSidecar(clone, cloneToNid, false);
2484
+ }
2485
+
2486
+ return {
2487
+ html: base.html,
2488
+ nodeIds: base.nodeIds || [],
2489
+ shadowRoots: keptShadowRoots,
2490
+ frames: keptFrames,
2491
+ truncated: !!base.truncated,
2492
+ missingDescendants: base.missingDescendants || 0,
2493
+ removed: removed
2494
+ };
2495
+ }
2496
+
2497
+ function markSnapshotPayloadTruncated(payload) {
2498
+ payload.truncated = true;
2499
+ return payload;
2500
+ }
2501
+
2502
+ function fitSnapshotPayloadForBudget(payload, clone, cloneToNid, truncatedNodeIds) {
2503
+ var next = Object.assign({}, payload || {}, {
2504
+ nodeIds: Array.isArray(payload && payload.nodeIds) ? payload.nodeIds.slice() : [],
2505
+ shadowRoots: Array.isArray(payload && payload.shadowRoots) ? payload.shadowRoots.slice() : [],
2506
+ frames: Array.isArray(payload && payload.frames) ? payload.frames.slice() : [],
2507
+ stylesheets: Array.isArray(payload && payload.stylesheets) ? payload.stylesheets.slice() : [],
2508
+ inlineStyles: Array.isArray(payload && payload.inlineStyles) ? payload.inlineStyles.slice() : [],
2509
+ htmlAttrs: Object.assign({}, payload && payload.htmlAttrs ? payload.htmlAttrs : {}),
2510
+ bodyAttrs: Object.assign({}, payload && payload.bodyAttrs ? payload.bodyAttrs : {})
2511
+ });
2512
+
2513
+ while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.inlineStyles.length) {
2514
+ next.inlineStyles.pop();
2515
+ markSnapshotPayloadTruncated(next);
2516
+ }
2517
+ while (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.stylesheets.length) {
2518
+ next.stylesheets.pop();
2519
+ markSnapshotPayloadTruncated(next);
2520
+ }
2521
+
2522
+ if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.htmlStyle) {
2523
+ next.htmlStyle = '';
2524
+ markSnapshotPayloadTruncated(next);
2525
+ }
2526
+ if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.bodyStyle) {
2527
+ next.bodyStyle = '';
2528
+ markSnapshotPayloadTruncated(next);
2529
+ }
2530
+ if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Object.keys(next.htmlAttrs).length) {
2531
+ next.htmlAttrs = {};
2532
+ markSnapshotPayloadTruncated(next);
2533
+ }
2534
+ if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && Object.keys(next.bodyAttrs).length) {
2535
+ next.bodyAttrs = {};
2536
+ markSnapshotPayloadTruncated(next);
2537
+ }
2538
+ if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.title) {
2539
+ next.title = '';
2540
+ markSnapshotPayloadTruncated(next);
2541
+ }
2542
+ if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && next.url) {
2543
+ next.url = '';
2544
+ markSnapshotPayloadTruncated(next);
2545
+ }
2546
+
2547
+ if (wireByteLength(next) > SNAPSHOT_BUDGET_BYTES && clone && cloneToNid) {
2548
+ var cloneEls = cloneElementsWithNodeIds(clone, cloneToNid);
2549
+ for (var i = cloneEls.length - 1; i >= 0 && wireByteLength(next) > SNAPSHOT_BUDGET_BYTES; i--) {
2550
+ var nid = cloneToNid.get(cloneEls[i]);
2551
+ if (markCloneNidTruncated(clone, cloneToNid, nid, truncatedNodeIds)) {
2552
+ next.html = clone.innerHTML || '';
2553
+ next.nodeIds = buildNodeIdSidecar(clone, cloneToNid, false);
2554
+ next.shadowRoots = collectShadowRootPayloads(document.body, next.nodeIds, truncatedNodeIds);
2555
+ next.frames = collectFramePayloads(document.body, cloneToNid, truncatedNodeIds);
2556
+ next.missingDescendants = (next.missingDescendants || 0) + 1;
2557
+ markSnapshotPayloadTruncated(next);
2558
+ }
2559
+ }
2560
+ }
2561
+
2562
+ if (wireByteLength(next) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
2563
+ next.html = '';
2564
+ next.nodeIds = [];
2565
+ next.shadowRoots = [];
2566
+ next.frames = [];
2567
+ next.inlineStyles = [];
2568
+ next.stylesheets = [];
2569
+ next.htmlAttrs = {};
2570
+ next.bodyAttrs = {};
2571
+ next.htmlStyle = '';
2572
+ next.bodyStyle = '';
2573
+ next.title = '';
2574
+ next.url = '';
2575
+ next.missingDescendants = (next.missingDescendants || 0) + 1;
2576
+ markSnapshotPayloadTruncated(next);
2577
+ }
2578
+
2579
+ return next;
2580
+ }
2581
+
2582
+ // =========================================================================
2583
+ // 0.5 SEC-01 Sanitization chokepoint
2584
+ // =========================================================================
2585
+
2586
+ /**
2587
+ * Snapshot the sanitization counters (plain copy, for the aggregate strip
2588
+ * warn's before/after comparison and as the warn payload).
2589
+ * @returns {Object} counter snapshot
2590
+ */
2591
+ function sanitizeCountersSnapshot() {
2592
+ return {
2593
+ strippedHandlers: sanitizeCounters.strippedHandlers,
2594
+ blockedUrlSchemes: sanitizeCounters.blockedUrlSchemes,
2595
+ blockedSubtrees: sanitizeCounters.blockedSubtrees,
2596
+ cssScrubs: sanitizeCounters.cssScrubs,
2597
+ maskedTextNodes: sanitizeCounters.maskedTextNodes,
2598
+ maskedInputs: sanitizeCounters.maskedInputs
2599
+ };
2600
+ }
2601
+
2602
+ /**
2603
+ * Emit ONE aggregate strip warn per serialization pass when any
2604
+ * sanitization counter moved during that pass (counted + logged, never
2605
+ * silent -- CONTEXT observability decision; aggregate, not per-strip
2606
+ * spam). Called once per serializeDOM pass and once per mutation flush.
2607
+ * @param {Object} before - counter snapshot taken before the pass
2608
+ */
2609
+ function warnIfSanitizeStrips(before) {
2610
+ var after = sanitizeCountersSnapshot();
2611
+ var moved = false;
2612
+ for (var key in after) {
2613
+ if (Object.prototype.hasOwnProperty.call(after, key) && after[key] !== before[key]) {
2614
+ moved = true;
2615
+ break;
2616
+ }
2617
+ }
2618
+ if (moved) {
2619
+ logger.warn('[DOM Stream] sanitization strips', after);
2620
+ }
2621
+ }
2622
+
2623
+ // Serialization-path inventory (keep ACCURATE -- this list is the ground
2624
+ // truth the plan 03-05 chokepoint purity scan audits, Pitfall 1; mirrors
2625
+ // the WR-03 wire-value insertion-point inventory in
2626
+ // src/renderer/snapshot.js):
2627
+ // 1. serializeDOM clone walk -- 'element' dispatch (drop
2628
+ // decision at the old script/noscript site, before nid assignment,
2629
+ // plus a post-absolutification re-scrub per pair and an
2630
+ // iframe-branch scrub)
2631
+ // 2. processAddedNode add-op subtrees -- 'subtree' dispatch on the
2632
+ // detached wire clone (the live node is NEVER scrubbed)
2633
+ // 3. attr-op branch -- 'attr' dispatch, after
2634
+ // absolutifyUrl/absolutifySrcset so the scheme check runs on final
2635
+ // wire values
2636
+ // 4. characterData text branch -- 'text' dispatch (SEC-03
2637
+ // masking seam, plan 03-03)
2638
+ // 5. E2 text-childlist branch -- 'text' dispatch (same seam)
2639
+ // 6. input/change value branch -- 'input' dispatch (CAPT-05
2640
+ // masking seam for event-driven form state)
2641
+ // Head inline <style> text additionally routes through the 'css' dispatch
2642
+ // at the serializeDOM collection site (a value scrub, not a markup walk).
2643
+ // Side channels that BYPASS the markup scrub AND the masking helpers BY
2644
+ // DESIGN: the dialog relay (setupDialogRelay -- see the T-03-26
2645
+ // disposition comment there) and the overlay broadcast
2646
+ // (broadcastOverlayState) carry text/metadata only and are rendered via
2647
+ // textContent in the viewer (overlays.js, threat T-02-04) -- no HTML
2648
+ // parse path exists for them.
2649
+
2650
+ /**
2651
+ * The capture-side sanitization chokepoint (SEC-01): the single named
2652
+ * function through which every serialization path emits. Blocklist
2653
+ * policy, fidelity-first (CONTEXT locked decision: allowlist rejected) --
2654
+ * benign content passes through byte-identical. Strips apply ONLY to
2655
+ * detached clones / wire values, never to the live observed page (threat
2656
+ * T-03-06). Dispatch shapes (kind, payload -> result):
2657
+ *
2658
+ * 'element', { orig, clone } -> { drop?: true }
2659
+ * Scrubs one detached clone element in place; { drop: true } for
2660
+ * script/noscript (reference-parity strip, uncounted) and
2661
+ * object/embed (SEC-01 blocklist, counted).
2662
+ * 'subtree', { root, liveRoot } -> { drop?: true }
2663
+ * Walks a detached wire clone (root + descendants), element-scrubbing
2664
+ * each and removing forbidden descendants; { drop: true } when the
2665
+ * root itself is forbidden.
2666
+ * 'attr', { name, value, target } -> { drop?: true, value?: string }
2667
+ * Attr-op gate: on* and srcdoc ops are DROPPED, dangerous URL schemes
2668
+ * neutralize to '', style values are CSS-scrubbed; everything else
2669
+ * passes through unchanged.
2670
+ * 'text', { text, owner } -> { text }
2671
+ * SEC-03 masking seam (plan 03-03): maskTextSelector / maskTextFn
2672
+ * applied against the LIVE owner element's ancestry (incrementing
2673
+ * maskedTextNodes); Phase 8 CAPT-05 typed-text capture plugs into the
2674
+ * same seam.
2675
+ * 'input', { value, owner } -> { value }
2676
+ * CAPT-05 masking seam for event-driven form values. Password inputs
2677
+ * and maskInputs/maskInputFn are applied before transport.
2678
+ * 'css', { css } -> { css }
2679
+ * Targeted CSS value scrub (scrubCssText) for head inline styles.
2680
+ *
2681
+ * @param {string} kind - dispatch tag
2682
+ * @param {Object} payload - shape per dispatch tag (above)
2683
+ * @returns {Object} per-dispatch result object
2684
+ */
2685
+ function sanitizeForWire(kind, payload) {
2686
+ if (kind === 'element') {
2687
+ var clone = payload.clone;
2688
+ if (!clone || clone.nodeType !== Node.ELEMENT_NODE) return {};
2689
+ var tag = clone.tagName ? String(clone.tagName).toLowerCase() : '';
2690
+ // script/noscript: reference-parity strip -- NOT counted (the
2691
+ // reference already dropped these from snapshots; counting them
2692
+ // would fire the strip warn on every benign page with a <script>).
2693
+ if (tag === 'script' || tag === 'noscript') {
2694
+ return { drop: true };
2695
+ }
2696
+ // object/embed: SEC-01 blocklist drop (CONTEXT decision: drop the
2697
+ // whole subtree, no placeholder -- threat T-03-04).
2698
+ if (tag === 'object' || tag === 'embed') {
2699
+ sanitizeCounters.blockedSubtrees++;
2700
+ return { drop: true };
2701
+ }
2702
+ // Collect attribute names FIRST: clone.attributes is a LIVE
2703
+ // NamedNodeMap, so removing while iterating skips entries.
2704
+ var attrNames = [];
2705
+ var attrList = clone.attributes;
2706
+ if (attrList) {
2707
+ for (var i = 0; i < attrList.length; i++) {
2708
+ if (attrList[i] && attrList[i].name) attrNames.push(attrList[i].name);
2709
+ }
2710
+ }
2711
+ for (var n = 0; n < attrNames.length; n++) {
2712
+ var rawName = attrNames[n];
2713
+ var lowName = String(rawName).toLowerCase();
2714
+ // on* handler attrs: stripped on EVERY element regardless of
2715
+ // namespace (serializeShellAttributes precedent generalized to all
2716
+ // paths -- threats T-03-01/T-03-03, Pitfall 4).
2717
+ if (lowName.indexOf('on') === 0) {
2718
+ clone.removeAttribute(rawName);
2719
+ sanitizeCounters.strippedHandlers++;
2720
+ continue;
2721
+ }
2722
+ // srcdoc: a whole nested attacker document in one attribute --
2723
+ // dropped outright, counted as a blocked subtree (T-03-04).
2724
+ if (lowName === 'srcdoc') {
2725
+ clone.removeAttribute(rawName);
2726
+ sanitizeCounters.blockedSubtrees++;
2727
+ }
2728
+ }
2729
+ // URL-carrying attributes: dangerous schemes are removed, not
2730
+ // rewritten to href="". Empty hrefs navigate to the iframe's own URL
2731
+ // on click, so removal is the inert mirror behavior required by the
2732
+ // Phase 3 browser checkpoint.
2733
+ for (var u = 0; u < URL_ATTRS.length; u++) {
2734
+ var urlVal = clone.getAttribute(URL_ATTRS[u]);
2735
+ if (urlVal && hasDangerousScheme(urlVal)) {
2736
+ clone.removeAttribute(URL_ATTRS[u]);
2737
+ sanitizeCounters.blockedUrlSchemes++;
2738
+ }
2739
+ }
2740
+ var formactionVal = clone.getAttribute('formaction');
2741
+ if (formactionVal && hasDangerousScheme(formactionVal)) {
2742
+ clone.removeAttribute('formaction');
2743
+ sanitizeCounters.blockedUrlSchemes++;
2744
+ }
2745
+ // SVG xlink:href (getAttributeNS per the serializeDOM precedent).
2746
+ try {
2747
+ var xlinkVal = clone.getAttributeNS('http://www.w3.org/1999/xlink', 'href');
2748
+ if (xlinkVal && hasDangerousScheme(xlinkVal)) {
2749
+ clone.removeAttributeNS('http://www.w3.org/1999/xlink', 'href');
2750
+ sanitizeCounters.blockedUrlSchemes++;
2751
+ }
2752
+ } catch (e) { /* not an SVG element or no xlink support */ }
2753
+ // srcset: per-candidate scheme check (benign values byte-identical).
2754
+ var srcsetVal = clone.getAttribute('srcset');
2755
+ if (srcsetVal) {
2756
+ var scrubbedSrcset = scrubSrcset(srcsetVal);
2757
+ if (scrubbedSrcset !== srcsetVal) {
2758
+ clone.setAttribute('srcset', scrubbedSrcset);
2759
+ sanitizeCounters.blockedUrlSchemes++;
2760
+ }
2761
+ }
2762
+ // style attribute: targeted CSS value scrub.
2763
+ var styleVal = clone.getAttribute('style');
2764
+ if (styleVal) {
2765
+ var scrubbedStyle = scrubCssText(styleVal);
2766
+ if (scrubbedStyle !== styleVal) {
2767
+ clone.setAttribute('style', scrubbedStyle);
2768
+ sanitizeCounters.cssScrubs++;
2769
+ }
2770
+ }
2771
+ // <style> ELEMENT text: same CSS value scrub as head styles. This is
2772
+ // the namespace-confusion mXSS surface (threat T-03-03): a confused
2773
+ // parse can leave hostile markup as the style element's RAW TEXT,
2774
+ // invisible to attribute enumeration -- scrubCssText pass 5 removes
2775
+ // it. Detached clone only; the live element's text is untouched.
2776
+ if (tag === 'style') {
2777
+ var styleElText = clone.textContent;
2778
+ if (styleElText) {
2779
+ var scrubbedElText = scrubCssText(styleElText);
2780
+ if (scrubbedElText !== styleElText) {
2781
+ clone.textContent = scrubbedElText;
2782
+ sanitizeCounters.cssScrubs++;
2783
+ }
2784
+ }
2785
+ }
2786
+ // SEC-03 masking pass (plan 03-03), applied ONCE per clone: the pairs
2787
+ // walk routes each pair through this dispatch twice (drop decision +
2788
+ // final-wire-value re-scrub), and a second application would corrupt
2789
+ // custom mask fn output -- so the pass marks the clone with a JS-only
2790
+ // property that never serializes (clone-only; live nodes are never
2791
+ // touched, threat T-03-06).
2792
+ if (!clone._psMasked) {
2793
+ clone._psMasked = true;
2794
+ if (payload.orig) {
2795
+ maskInputCloneValue(clone, payload.orig);
2796
+ }
2797
+ // maskTextSelector: the LIVE element's ancestry decides (orig is
2798
+ // null for detached subtree descendants -- those are masked by the
2799
+ // 'subtree' dispatch, which knows the inherited root state).
2800
+ if (payload.orig && maskTextMatches(payload.orig)) {
2801
+ maskDirectChildText(clone, payload.orig, safeMaskText, 'maskedTextNodes');
2802
+ }
2803
+ }
2804
+ return {};
2805
+ }
2806
+
2807
+ if (kind === 'subtree') {
2808
+ var root = payload.root;
2809
+ if (!root || root.nodeType !== Node.ELEMENT_NODE) return {};
2810
+ // Root itself forbidden (script/noscript/object/embed): signal the
2811
+ // caller to emit nothing rather than an empty-html op.
2812
+ var rootResult = sanitizeForWire('element', { orig: payload.liveRoot, clone: root });
2813
+ if (rootResult && rootResult.drop) {
2814
+ return { drop: true };
2815
+ }
2816
+ // SEC-03: every descendant uses its LIVE counterpart when available,
2817
+ // so maskTextSelector sees full live ancestry (detached clones cannot)
2818
+ // and maskInputs/password rules consult the real form control type.
2819
+ var liveDescendants = (payload.liveRoot && payload.liveRoot.querySelectorAll)
2820
+ ? payload.liveRoot.querySelectorAll('*')
2821
+ : [];
2822
+ var descendants = root.querySelectorAll('*');
2823
+ for (var d = 0; d < descendants.length; d++) {
2824
+ var desc = descendants[d];
2825
+ var liveDesc = liveDescendants[d] || null;
2826
+ // Skip nodes already detached with a removed forbidden ancestor
2827
+ // (querySelectorAll is static; removal does not re-enumerate).
2828
+ if (!root.contains(desc)) continue;
2829
+ if (liveDesc && wireDroppedWithAncestors(liveDesc.parentElement)) continue;
2830
+ if (liveDesc && blockedWithAncestors(liveDesc.parentElement)) continue;
2831
+ if (liveDesc && blockMatches(liveDesc)) {
2832
+ replaceWithBlockPlaceholder(liveDesc, desc, readBlockRect(liveDesc), payload.cloneToNid);
2833
+ continue;
2834
+ }
2835
+ var descResult = sanitizeForWire('element', { orig: liveDesc, clone: desc });
2836
+ if (descResult && descResult.drop && desc.parentNode) {
2837
+ desc.parentNode.removeChild(desc);
2838
+ }
2839
+ }
2840
+ return {};
2841
+ }
2842
+
2843
+ if (kind === 'attr') {
2844
+ var attrName = String(payload.name || '').toLowerCase();
2845
+ // on* handler attr mutations: the op is DROPPED entirely, never
2846
+ // value-neutralized -- the mirror must not even learn the attribute
2847
+ // name (Pitfall 5: this branch bypassed the snapshot sanitizer).
2848
+ if (attrName.indexOf('on') === 0) {
2849
+ sanitizeCounters.strippedHandlers++;
2850
+ return { drop: true };
2851
+ }
2852
+ // srcdoc: dropped, matching the element-path attribute strip.
2853
+ if (attrName === 'srcdoc') {
2854
+ sanitizeCounters.blockedSubtrees++;
2855
+ return { drop: true };
2856
+ }
2857
+ // style: targeted CSS value scrub (A2: style attr mutations flow
2858
+ // through this branch as full inline-style serializations).
2859
+ if (attrName === 'style') {
2860
+ var scrubbedAttrCss = scrubCssText(payload.value);
2861
+ if (scrubbedAttrCss !== payload.value) {
2862
+ sanitizeCounters.cssScrubs++;
2863
+ }
2864
+ return { value: scrubbedAttrCss };
2865
+ }
2866
+ // srcset: per-candidate scheme neutralization.
2867
+ if (attrName === 'srcset' && payload.value) {
2868
+ var scrubbedAttrSrcset = scrubSrcset(payload.value);
2869
+ if (scrubbedAttrSrcset !== payload.value) {
2870
+ sanitizeCounters.blockedUrlSchemes++;
2871
+ }
2872
+ return { value: scrubbedAttrSrcset };
2873
+ }
2874
+ // URL-carrying attrs: dangerous schemes remove the attr on the mirror.
2875
+ // Preserving href with an empty value is still navigable in real
2876
+ // browsers, so null is the inert ATTR-op shape (diff.js removeAttribute).
2877
+ if ((URL_ATTRS.indexOf(attrName) !== -1 || attrName === 'formaction' || attrName === 'xlink:href')
2878
+ && payload.value && hasDangerousScheme(payload.value)) {
2879
+ sanitizeCounters.blockedUrlSchemes++;
2880
+ return { value: null };
2881
+ }
2882
+ if (attrName === 'value' && (shouldMaskInput(payload.target) || isOptionUnderMaskedSelect(payload.target))) {
2883
+ var maskedAttrValue = safeMaskInput(payload.value == null ? '' : payload.value, payload.target);
2884
+ if (maskedAttrValue !== payload.value) {
2885
+ sanitizeCounters.maskedInputs++;
2886
+ }
2887
+ return { value: maskedAttrValue };
2888
+ }
2889
+ return { value: payload.value };
2890
+ }
2891
+
2892
+ if (kind === 'text') {
2893
+ // SEC-03 masking (plan 03-03): BOTH text-op branches (characterData
2894
+ // and the E2 text-childlist branch) route through this one hook. The
2895
+ // owner element is LIVE, so closest() sees the full ancestry. Phase 8
2896
+ // CAPT-05 typed-text capture plugs into the same seam. Unmasked text
2897
+ // passes through unchanged (default-off: zero wire change without
2898
+ // masking config).
2899
+ if (shouldMaskInput(payload.owner)) {
2900
+ var maskedInputText = safeMaskInput(payload.text == null ? '' : payload.text, payload.owner);
2901
+ if (maskedInputText !== payload.text) {
2902
+ sanitizeCounters.maskedInputs++;
2903
+ }
2904
+ return { text: maskedInputText };
2905
+ }
2906
+ if (maskTextMatches(payload.owner)) {
2907
+ var maskedOpText = safeMaskText(payload.text, payload.owner);
2908
+ if (maskedOpText !== payload.text) {
2909
+ sanitizeCounters.maskedTextNodes++;
2910
+ }
2911
+ return { text: maskedOpText };
2912
+ }
2913
+ return { text: payload.text };
2914
+ }
2915
+
2916
+ if (kind === 'input') {
2917
+ var inputValue = payload.value == null ? '' : String(payload.value);
2918
+ if (shouldMaskInput(payload.owner)) {
2919
+ var maskedValue = safeMaskInput(inputValue, payload.owner);
2920
+ if (maskedValue !== inputValue) {
2921
+ sanitizeCounters.maskedInputs++;
2922
+ }
2923
+ return { value: maskedValue };
2924
+ }
2925
+ return { value: inputValue };
2926
+ }
2927
+
2928
+ if (kind === 'css') {
2929
+ var scrubbedCss = scrubCssText(payload.css);
2930
+ if (scrubbedCss !== payload.css) {
2931
+ sanitizeCounters.cssScrubs++;
2932
+ }
2933
+ return { css: scrubbedCss };
2934
+ }
2935
+
2936
+ return {};
2937
+ }
2938
+
2939
+ // =========================================================================
2940
+ // 1. DOM Serializer
2941
+ // =========================================================================
2942
+
2943
+ /**
2944
+ * Absolutify a URL attribute value relative to the current document.
2945
+ * Note: javascript: URLs pass through unchanged HERE (reference parity --
2946
+ * this helper stays a pure URL resolver); the SEC-01 chokepoint
2947
+ * (sanitizeForWire) neutralizes dangerous schemes AFTER absolutification,
2948
+ * so the scheme check always runs on final wire values.
2949
+ * @param {string} val - The attribute value
2950
+ * @returns {string} Absolute URL or original value if invalid
2951
+ */
2952
+ function absolutifyUrl(val, baseDoc) {
2953
+ if (!val || val.startsWith('data:') || val.startsWith('blob:') || val.startsWith('javascript:')) {
2954
+ return val;
2955
+ }
2956
+ try {
2957
+ var base = baseDoc && baseDoc.baseURI ? baseDoc.baseURI : document.baseURI;
2958
+ return new URL(val, base).href;
2959
+ } catch (e) {
2960
+ return val;
2961
+ }
2962
+ }
2963
+
2964
+ /**
2965
+ * Absolutify srcset attribute (comma-separated URL descriptors).
2966
+ * @param {string} srcset
2967
+ * @returns {string}
2968
+ */
2969
+ function absolutifySrcset(srcset, baseDoc) {
2970
+ if (!srcset) return srcset;
2971
+ var candidates = parseSrcsetCandidates(srcset);
2972
+ if (!candidates.length) return srcset;
2973
+ return candidates.map(function(candidate) {
2974
+ return formatSrcsetCandidate({
2975
+ url: absolutifyUrl(candidate.url, baseDoc),
2976
+ descriptor: candidate.descriptor
2977
+ });
2978
+ }).join(', ');
2979
+ }
2980
+
2981
+ /**
2982
+ * Collect computed styles for an element as inline style text.
2983
+ * Iterates CURATED_PROPS (~85 visual-fidelity properties) instead of all
2984
+ * 300+ computed properties. Skips common defaults to reduce payload size
2985
+ * (D-04, D-07, D-08).
2986
+ * @param {Element} original - The original DOM element (for getComputedStyle)
2987
+ * @param {string[]} [props] - Property list; defaults to CURATED_PROPS
2988
+ * @returns {string} 'prop:value;...' style text
2989
+ */
2990
+ function collectComputedStyleText(original, props) {
2991
+ try {
2992
+ var view = original && original.ownerDocument && original.ownerDocument.defaultView
2993
+ ? original.ownerDocument.defaultView
2994
+ : window;
2995
+ var computed = view.getComputedStyle(original);
2996
+ var styles = [];
2997
+ var styleProps = props || CURATED_PROPS;
2998
+
2999
+ for (var i = 0; i < styleProps.length; i++) {
3000
+ var prop = styleProps[i];
3001
+ var val = computed.getPropertyValue(prop);
3002
+ if (!val || val === '') continue;
3003
+ // Skip common defaults to reduce payload (per D-08)
3004
+ if (STYLE_DEFAULTS[prop] === val) continue;
3005
+ // Skip values that are just browser defaults for most elements
3006
+ if (val === '0px' || val === 'normal' || val === 'none' || val === 'auto' || val === '0s' || val === '0px 0px') {
3007
+ if (!STYLE_DEFAULTS[prop]) continue;
3008
+ }
3009
+ styles.push(prop + ':' + val);
3010
+ }
3011
+
3012
+ return styles.join(';');
3013
+ } catch (e) {
3014
+ // getComputedStyle can fail for detached elements
3015
+ return '';
3016
+ }
3017
+ }
3018
+
3019
+ /**
3020
+ * Capture curated computed styles from the original element onto the clone
3021
+ * as an inline style attribute.
3022
+ * @param {Element} original
3023
+ * @param {Element} clone
3024
+ */
3025
+ function captureComputedStyles(original, clone) {
3026
+ var styleText = collectComputedStyleText(original, CURATED_PROPS);
3027
+ if (styleText) {
3028
+ clone.setAttribute('style', styleText);
3029
+ }
3030
+ }
3031
+
3032
+ function collectSubtreeComputedStyles(root) {
3033
+ var styles = new WeakMap();
3034
+ if (!root || root.nodeType !== Node.ELEMENT_NODE) return styles;
3035
+ var liveElements = [root];
3036
+ if (root.querySelectorAll) {
3037
+ var descendants = root.querySelectorAll('*');
3038
+ for (var i = 0; i < descendants.length; i++) liveElements.push(descendants[i]);
3039
+ }
3040
+ for (var e = 0; e < liveElements.length; e++) {
3041
+ var styleText = collectComputedStyleText(liveElements[e], CURATED_PROPS);
3042
+ if (styleText) styles.set(liveElements[e], styleText);
3043
+ }
3044
+ return styles;
3045
+ }
3046
+
3047
+ /**
3048
+ * Serialize the attributes of a shell element (html/body), dropping style
3049
+ * and on* handler attributes. This was the reference's ONLY on*-strip
3050
+ * site; Phase 3 SEC-01 generalized the same name test to every
3051
+ * serialization path via the sanitizeForWire chokepoint (threat T-03-01).
3052
+ * @param {Element} el
3053
+ * @returns {Object} name -> value attribute map
3054
+ */
3055
+ function serializeShellAttributes(el) {
3056
+ var attrs = {};
3057
+ if (!el || !el.attributes) return attrs;
3058
+ for (var i = 0; i < el.attributes.length; i++) {
3059
+ var attr = el.attributes[i];
3060
+ if (!attr || !attr.name) continue;
3061
+ var name = String(attr.name).toLowerCase();
3062
+ if (name === 'style' || name.indexOf('on') === 0) continue;
3063
+ attrs[name] = String(attr.value || '');
3064
+ }
3065
+ return attrs;
3066
+ }
3067
+
3068
+ /**
3069
+ * Serialize the full DOM body into a clean HTML string.
3070
+ * Strips scripts, absolutifies URLs, assigns stable node identity through
3071
+ * the internal mirror, renders iframes live with absolutified src, and
3072
+ * captures curated computed styles.
3073
+ *
3074
+ * @returns {Object} { html, stylesheets, scrollX, scrollY, viewportWidth, viewportHeight,
3075
+ * pageWidth, pageHeight, url, title }
3076
+ */
3077
+ function serializeDOM() {
3078
+ // SEC-01: counter snapshot for the ONE aggregate strip warn per pass.
3079
+ var sanBefore = sanitizeCountersSnapshot();
3080
+
3081
+ // Clone the body for transformation
3082
+ var clone = document.body.cloneNode(true);
3083
+ var cloneToNid = new Map();
3084
+
3085
+ // Build a map from original elements to cloned elements for computed style capture.
3086
+ // Walk original body and clone in parallel using TreeWalker.
3087
+ var origWalker = document.createTreeWalker(
3088
+ document.body,
3089
+ NodeFilter.SHOW_ELEMENT,
3090
+ null
3091
+ );
3092
+ var cloneWalker = document.createTreeWalker(
3093
+ clone,
3094
+ NodeFilter.SHOW_ELEMENT,
3095
+ null
3096
+ );
3097
+
3098
+ // Collect elements to process (TreeWalker is live, so modifying during walk is risky)
3099
+ var pairs = [];
3100
+ var origEl = origWalker.nextNode();
3101
+ var cloneEl = cloneWalker.nextNode();
3102
+ while (origEl && cloneEl) {
3103
+ pairs.push({ orig: origEl, clone: cloneEl });
3104
+ origEl = origWalker.nextNode();
3105
+ cloneEl = cloneWalker.nextNode();
3106
+ }
3107
+
3108
+ // Elements to remove from clone (scripts, noscript, host-flagged elements)
3109
+ var toRemove = [];
3110
+ var blockedPairs = [];
3111
+
3112
+ for (var i = 0; i < pairs.length; i++) {
3113
+ var orig = pairs[i].orig;
3114
+ var cl = pairs[i].clone;
3115
+ var tag = cl.tagName ? cl.tagName.toLowerCase() : '';
3116
+
3117
+ if (wireDroppedWithAncestors(orig.parentElement)) {
3118
+ reserveNodeId();
3119
+ continue;
3120
+ }
3121
+
3122
+ // SEC-01 drop decision routed through the chokepoint: script/noscript
3123
+ // (reference parity) plus object/embed (blocklist) -- the decision
3124
+ // logic lives INSIDE sanitizeForWire; this loop only routes. The same
3125
+ // call scrubs the surviving clone's RAW attribute values (the
3126
+ // post-absolutification re-scrub below covers final wire values).
3127
+ // Dropped elements exit BEFORE node-id assignment, exactly like the
3128
+ // reference's script/noscript handling.
3129
+ var elemDecision = sanitizeForWire('element', { orig: orig, clone: cl });
3130
+ if (elemDecision && elemDecision.drop) {
3131
+ toRemove.push(cl);
3132
+ continue;
3133
+ }
3134
+
3135
+ // skipElement seam: elements the host flags (its own UI) are dropped
3136
+ // from the clone before any node-id assignment. The default predicate
3137
+ // returns false, which matches the reference running on a page with no
3138
+ // host overlay present. Exception-contained: a throwing host predicate
3139
+ // is logged and treated as not-skipped (never escapes start()).
3140
+ if (safeSkipElement(cl)) {
3141
+ toRemove.push(cl);
3142
+ continue;
3143
+ }
3144
+ // Reference parity (dom-stream.js 420-424): descendants of a
3145
+ // host-skipped element are skipped too, with NO node-id assignment --
3146
+ // removing the skipped root above already drops the whole subtree
3147
+ // from the clone.
3148
+ if (skipElementWithAncestors(cl)) {
3149
+ continue;
3150
+ }
3151
+
3152
+ // blockSelector: descendants of a blocked root get no nid assignment
3153
+ // (the root swap discards the whole cloned subtree). The blocked root
3154
+ // itself is still tracked, then replaced after this walk by a
3155
+ // dimension-preserving placeholder whose identity travels in nodeIds.
3156
+ if (blockedWithAncestors(orig.parentElement)) {
3157
+ continue;
3158
+ }
3159
+ if (blockMatches(orig)) {
3160
+ assignNodeId(orig, cl, cloneToNid);
3161
+ blockedPairs.push({ orig: orig, clone: cl });
3162
+ continue;
3163
+ }
3164
+
3165
+ // Frame documents travel only through frames[] sidecars; the shell
3166
+ // iframe remains inert and content-free in the main html.
3167
+ if (tag === 'iframe') {
3168
+ assignNodeId(orig, cl, cloneToNid);
3169
+ prepareIframeWireShell(orig, cl);
3170
+ continue;
3171
+ }
3172
+
3173
+ // Assign stable node identity in the internal mirror and sidecar map.
3174
+ var nid = assignNodeId(orig, cl, cloneToNid);
3175
+
3176
+ // Canvas-to-img conversion: capture canvas content before it's lost in the clone
3177
+ if (tag === 'canvas') {
3178
+ try {
3179
+ var dataUrl = orig.toDataURL('image/png');
3180
+ var img = clone.ownerDocument.createElement('img');
3181
+ img.src = dataUrl;
3182
+ img.setAttribute('style', 'width:' + (orig.width || 300) + 'px;height:' + (orig.height || 150) + 'px;');
3183
+ if (cl.parentNode) {
3184
+ cl.parentNode.replaceChild(img, cl);
3185
+ cloneToNid.delete(cl);
3186
+ if (nid) cloneToNid.set(img, nid);
3187
+ }
3188
+ } catch (e) {
3189
+ // Tainted canvas or security error -- leave as empty canvas
3190
+ }
3191
+ continue;
3192
+ }
3193
+
3194
+ // Absolutify URL attributes
3195
+ for (var a = 0; a < URL_ATTRS.length; a++) {
3196
+ var attrVal = cl.getAttribute(URL_ATTRS[a]);
3197
+ if (attrVal) {
3198
+ cl.setAttribute(URL_ATTRS[a], absolutifyUrl(attrVal));
3199
+ }
3200
+ }
3201
+
3202
+ // SVG xlink:href absolutification
3203
+ try {
3204
+ var xlinkHref = cl.getAttributeNS('http://www.w3.org/1999/xlink', 'href');
3205
+ if (xlinkHref) {
3206
+ cl.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', absolutifyUrl(xlinkHref));
3207
+ }
3208
+ } catch (e) { /* not an SVG element or no xlink support */ }
3209
+
3210
+ // Absolutify srcset
3211
+ var srcsetVal = cl.getAttribute('srcset');
3212
+ if (srcsetVal) {
3213
+ cl.setAttribute('srcset', absolutifySrcset(srcsetVal));
3214
+ }
3215
+
3216
+ // Capture generated computed styles only in the default compatibility mode.
3217
+ if (styleMode !== 'cssom') captureComputedStyles(orig, cl);
3218
+
3219
+ // SEC-01 re-scrub on FINAL wire values: absolutifyUrl normalizes
3220
+ // whitespace-obfuscated schemes (the URL parser strips tab/LF/CR), and
3221
+ // captureComputedStyles rewrites the style attribute -- so the scheme
3222
+ // check and CSS scrub must run again after both. Idempotent: counters
3223
+ // only move when an attribute value actually changes.
3224
+ sanitizeForWire('element', { orig: orig, clone: cl });
3225
+ }
3226
+
3227
+ // Read all blocked live rects together after the pair walk and before
3228
+ // clone writes. This preserves the single-pass layout-read discipline:
3229
+ // dimensions come from the original elements, never detached clones.
3230
+ var blockedRects = [];
3231
+ for (var bp = 0; bp < blockedPairs.length; bp++) {
3232
+ blockedRects.push(readBlockRect(blockedPairs[bp].orig));
3233
+ }
3234
+
3235
+ // Remove marked elements
3236
+ for (var r = 0; r < toRemove.length; r++) {
3237
+ if (toRemove[r].parentNode) {
3238
+ toRemove[r].parentNode.removeChild(toRemove[r]);
3239
+ }
3240
+ }
3241
+
3242
+ for (var br = 0; br < blockedPairs.length; br++) {
3243
+ replaceWithBlockPlaceholder(blockedPairs[br].orig, blockedPairs[br].clone, blockedRects[br], cloneToNid);
3244
+ }
3245
+
3246
+ // Collect stylesheet URLs from document.head
3247
+ var stylesheets = collectStylesheetsFrom(document);
3248
+
3249
+ // Collect inline <style> tags from document.head, value-scrubbed
3250
+ // through the chokepoint's 'css' dispatch (SEC-01: dangerous url()
3251
+ // schemes, expression(), -moz-binding, non-http(s) @import, </style
3252
+ // breakout). Benign CSS passes byte-identical.
3253
+ var inlineStyles = collectInlineStylesFrom(document);
3254
+
3255
+ var documentCssom = styleMode === 'cssom'
3256
+ ? collectCssomStyleSourcesForScope(document, { kind: 'document' }, { root: document })
3257
+ : null;
3258
+ var html = clone.innerHTML;
3259
+ var truncated = false;
3260
+ var missingDescendants = 0;
3261
+ var truncatedNodeIds = new Set();
3262
+
3263
+ // Phase 211-02 (STREAM-03 + STREAM-04): single TreeWalker pre-pass on the
3264
+ // LIVE document reads getBoundingClientRect().top per tracked element into
3265
+ // a Map BEFORE any clone mutation. This collapses N forced layout flushes
3266
+ // into 1 (web-perf folklore: read-then-write batching). The Map is the
3267
+ // authoritative position source because the clone is not in the document
3268
+ // tree and getBoundingClientRect() on it returns zeros.
3269
+ var topByNid = new Map();
3270
+ try {
3271
+ var walker = document.createTreeWalker(
3272
+ document.body,
3273
+ NodeFilter.SHOW_ELEMENT,
3274
+ {
3275
+ acceptNode: function(el) {
3276
+ return getTrackedNodeId(el) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
3277
+ }
3278
+ }
3279
+ );
3280
+ var liveEl;
3281
+ while ((liveEl = walker.nextNode())) {
3282
+ var liveNid = getTrackedNodeId(liveEl);
3283
+ if (liveNid) {
3284
+ // Single getBoundingClientRect call per annotated element.
3285
+ // All reads happen before any clone mutation -> 1 layout flush.
3286
+ topByNid.set(liveNid, liveEl.getBoundingClientRect().top);
3287
+ }
3288
+ }
3289
+ } catch (e) { /* TreeWalker unavailable in this realm; truncation falls back to no-op */ }
3290
+
3291
+ // SNAPSHOT_BUDGET_BYTES is the imported 80%-of-relay-cap budget. Compare
3292
+ // UTF-8 wire bytes, not UTF-16 code units, so non-ASCII snapshots respect
3293
+ // the relay's byte cap.
3294
+ if (wireByteLength(html) > SNAPSHOT_BUDGET_BYTES) {
3295
+ truncated = true;
3296
+ var viewportCutoff = window.innerHeight * TRUNCATION_VIEWPORT_MULTIPLIER;
3297
+
3298
+ // Pass 1: drop complete subtrees whose cached top is below the
3299
+ // viewport-multiple cutoff. Iterate the clone's annotated elements;
3300
+ // consult the Map for live top. Removing a parent later in the loop
3301
+ // also removes its children, so we walk last-to-first to keep indices
3302
+ // stable as we mutate.
3303
+ var cloneEls1 = cloneElementsWithNodeIds(clone, cloneToNid);
3304
+ for (var t = cloneEls1.length - 1; t >= 0; t--) {
3305
+ var nidVal1 = cloneToNid.get(cloneEls1[t]);
3306
+ var top1 = topByNid.get(nidVal1);
3307
+ if (typeof top1 === 'number' && top1 > viewportCutoff) {
3308
+ var placeholder1 = replaceWithTruncatedPlaceholder(cloneEls1[t], cloneToNid);
3309
+ if (placeholder1) {
3310
+ var placeholderNid1 = cloneToNid.get(placeholder1);
3311
+ if (placeholderNid1) truncatedNodeIds.add(String(placeholderNid1));
3312
+ missingDescendants++;
3313
+ }
3314
+ }
3315
+ }
3316
+
3317
+ // Re-measure; if still over cap, pass 2 walks remaining annotated
3318
+ // elements in document order and drops complete subtrees until under
3319
+ // cap. Only complete subtrees are removed -- never a mid-element cut.
3320
+ html = clone.innerHTML;
3321
+ if (wireByteLength(html) > SNAPSHOT_BUDGET_BYTES) {
3322
+ var cloneEls2 = cloneElementsWithNodeIds(clone, cloneToNid);
3323
+ for (var u = cloneEls2.length - 1; u >= 0 && wireByteLength(clone.innerHTML) > SNAPSHOT_BUDGET_BYTES; u--) {
3324
+ var placeholder2 = replaceWithTruncatedPlaceholder(cloneEls2[u], cloneToNid);
3325
+ if (placeholder2) {
3326
+ var placeholderNid2 = cloneToNid.get(placeholder2);
3327
+ if (placeholderNid2) truncatedNodeIds.add(String(placeholderNid2));
3328
+ missingDescendants++;
3329
+ }
3330
+ }
3331
+ html = clone.innerHTML;
3332
+ }
3333
+ }
3334
+
3335
+ html = clone.innerHTML;
3336
+
3337
+ // SEC-01: one aggregate strip warn per serialization pass (never silent).
3338
+ warnIfSanitizeStrips(sanBefore);
3339
+
3340
+ var nodeIds = buildNodeIdSidecar(clone, cloneToNid, false);
3341
+ var shadowRoots = collectShadowRootPayloads(document.body, nodeIds, truncatedNodeIds);
3342
+ var frames = collectFramePayloads(document.body, cloneToNid, truncatedNodeIds);
3343
+ var budgetInput = {
3344
+ html: html,
3345
+ nodeIds: nodeIds,
3346
+ truncated: truncated,
3347
+ missingDescendants: missingDescendants,
3348
+ stylesheets: stylesheets,
3349
+ inlineStyles: inlineStyles,
3350
+ htmlAttrs: serializeShellAttributes(document.documentElement),
3351
+ bodyAttrs: serializeShellAttributes(document.body),
3352
+ htmlStyle: collectComputedStyleText(document.documentElement, SHELL_PROPS),
3353
+ bodyStyle: collectComputedStyleText(document.body, SHELL_PROPS),
3354
+ scrollX: window.scrollX,
3355
+ scrollY: window.scrollY,
3356
+ viewportWidth: window.innerWidth,
3357
+ viewportHeight: window.innerHeight,
3358
+ pageWidth: document.documentElement.scrollWidth,
3359
+ pageHeight: document.documentElement.scrollHeight,
3360
+ url: location.href,
3361
+ title: document.title,
3362
+ streamSessionId: streamSessionId || '',
3363
+ snapshotId: currentSnapshotId || 0
3364
+ };
3365
+ if (documentCssom) {
3366
+ budgetInput.styleSources = documentCssom.sources;
3367
+ budgetInput.styleStrategy = documentCssom.strategy;
3368
+ }
3369
+ var budgetedSidecars = pruneSnapshotSidecarsForBudget(
3370
+ budgetInput,
3371
+ shadowRoots,
3372
+ frames,
3373
+ clone,
3374
+ cloneToNid,
3375
+ truncatedNodeIds
3376
+ );
3377
+ html = budgetedSidecars.html;
3378
+ nodeIds = budgetedSidecars.nodeIds;
3379
+ shadowRoots = budgetedSidecars.shadowRoots;
3380
+ frames = budgetedSidecars.frames;
3381
+ truncated = budgetedSidecars.truncated;
3382
+ missingDescendants = budgetedSidecars.missingDescendants;
3383
+
3384
+ var snapshotPayload = {
3385
+ html: html,
3386
+ nodeIds: nodeIds,
3387
+ shadowRoots: shadowRoots,
3388
+ frames: frames,
3389
+ truncated: truncated,
3390
+ missingDescendants: missingDescendants,
3391
+ stylesheets: stylesheets,
3392
+ inlineStyles: inlineStyles,
3393
+ htmlAttrs: serializeShellAttributes(document.documentElement),
3394
+ bodyAttrs: serializeShellAttributes(document.body),
3395
+ htmlStyle: collectComputedStyleText(document.documentElement, SHELL_PROPS),
3396
+ bodyStyle: collectComputedStyleText(document.body, SHELL_PROPS),
3397
+ scrollX: window.scrollX,
3398
+ scrollY: window.scrollY,
3399
+ viewportWidth: window.innerWidth,
3400
+ viewportHeight: window.innerHeight,
3401
+ pageWidth: document.documentElement.scrollWidth,
3402
+ pageHeight: document.documentElement.scrollHeight,
3403
+ url: location.href,
3404
+ title: document.title,
3405
+ streamSessionId: streamSessionId || '',
3406
+ snapshotId: currentSnapshotId || 0
3407
+ };
3408
+ if (documentCssom) {
3409
+ snapshotPayload.styleSources = documentCssom.sources;
3410
+ snapshotPayload.styleStrategy = documentCssom.strategy;
3411
+ }
3412
+ return fitSnapshotPayloadForBudget(snapshotPayload, clone, cloneToNid, truncatedNodeIds);
3413
+ }
3414
+
3415
+ // =========================================================================
3416
+ // 2. MutationObserver Streaming
3417
+ // =========================================================================
3418
+
3419
+ /**
3420
+ * Mirror node ids for an added node and its descendants, absolutify URLs,
3421
+ * then serialize a SCRUBBED detached clone of it (for add ops).
3422
+ *
3423
+ * SEC-01: the live node keeps URL absolutification exactly as before
3424
+ * (reference parity -- the observed page must keep its event handlers;
3425
+ * stripping the live node would change page behavior). PhantomStream
3426
+ * identity stays in the internal mirror, not live attributes.
3427
+ * The wire HTML is then built from a detached cloneNode(true) routed
3428
+ * through sanitizeForWire('subtree') -- the serialized output never comes
3429
+ * from the live node directly (threat T-03-06).
3430
+ *
3431
+ * @param {Element} el - Added element to process
3432
+ * @returns {{html: string, nodeIds: string[]}|null} Scrubbed wire HTML and
3433
+ * sidecar ids, or null when the root itself is forbidden.
3434
+ */
3435
+ function processAddedNode(el) {
3436
+ if (el.nodeType !== Node.ELEMENT_NODE) return null;
3437
+ if (wireDroppedWithAncestors(el)) {
3438
+ reserveNodeId();
3439
+ if (isWireDroppedElement(el)) sanitizeCounters.blockedSubtrees++;
3440
+ return null;
3441
+ }
3442
+
3443
+ // Live-node identity mirror + absolutification (reference parity for URL
3444
+ // mutation, but no framework identity attributes on the observed page).
3445
+ var rootNid = ensureNodeId(el);
3446
+ if (blockMatches(el)) {
3447
+ var blockedRootPlaceholder = createBlockPlaceholder(
3448
+ document,
3449
+ readBlockRect(el)
3450
+ );
3451
+ sanitizeCounters.blockedSubtrees++;
3452
+ return {
3453
+ html: blockedRootPlaceholder.outerHTML || '',
3454
+ nodeIds: rootNid ? [rootNid] : []
3455
+ };
3456
+ }
3457
+ var computedStyles = styleMode === 'cssom' ? new WeakMap() : collectSubtreeComputedStyles(el);
3458
+ var rootTag = el.tagName ? String(el.tagName).toLowerCase() : '';
3459
+ var baseDoc = el.ownerDocument || document;
3460
+ for (var a = 0; a < URL_ATTRS.length; a++) {
3461
+ if (rootTag === 'iframe' && URL_ATTRS[a] === 'src') continue;
3462
+ var val = el.getAttribute(URL_ATTRS[a]);
3463
+ if (val) el.setAttribute(URL_ATTRS[a], absolutifyUrl(val, baseDoc));
3464
+ }
3465
+ var srcset = el.getAttribute('srcset');
3466
+ if (srcset) el.setAttribute('srcset', absolutifySrcset(srcset, baseDoc));
3467
+
3468
+ // Process descendant elements
3469
+ var descendants = el.querySelectorAll('*');
3470
+ for (var d = 0; d < descendants.length; d++) {
3471
+ var desc = descendants[d];
3472
+ if (wireDroppedWithAncestors(desc)) {
3473
+ reserveNodeId();
3474
+ continue;
3475
+ }
3476
+ if (blockedWithAncestors(desc.parentElement)) continue;
3477
+ ensureNodeId(desc);
3478
+ if (blockMatches(desc)) continue;
3479
+ var descTag = desc.tagName ? String(desc.tagName).toLowerCase() : '';
3480
+ var descDoc = desc.ownerDocument || baseDoc;
3481
+ for (var b = 0; b < URL_ATTRS.length; b++) {
3482
+ if (descTag === 'iframe' && URL_ATTRS[b] === 'src') continue;
3483
+ var dv = desc.getAttribute(URL_ATTRS[b]);
3484
+ if (dv) desc.setAttribute(URL_ATTRS[b], absolutifyUrl(dv, descDoc));
3485
+ }
3486
+ var ds = desc.getAttribute('srcset');
3487
+ if (ds) desc.setAttribute('srcset', absolutifySrcset(ds, descDoc));
3488
+ }
3489
+
3490
+ // SEC-01: scrub a detached wire clone through the chokepoint and
3491
+ // serialize THAT -- never the live node's own markup.
3492
+ var wireClone = el.cloneNode(true);
3493
+ var cloneToNid = new Map();
3494
+ if (rootNid) cloneToNid.set(wireClone, rootNid);
3495
+ var rootStyleText = computedStyles.get(el);
3496
+ if (rootStyleText) appendStyleDeclaration(wireClone, rootStyleText);
3497
+ var liveDescendants = el.querySelectorAll('*');
3498
+ var cloneDescendants = wireClone.querySelectorAll('*');
3499
+ for (var c = 0; c < liveDescendants.length; c++) {
3500
+ var liveNid = getTrackedNodeId(liveDescendants[c]);
3501
+ if (liveNid && cloneDescendants[c]) cloneToNid.set(cloneDescendants[c], liveNid);
3502
+ var descStyleText = computedStyles.get(liveDescendants[c]);
3503
+ if (descStyleText && cloneDescendants[c]) {
3504
+ appendStyleDeclaration(cloneDescendants[c], descStyleText);
3505
+ }
3506
+ }
3507
+ prepareIframeWireShellsForClone(el, wireClone);
3508
+ var subtreeResult = sanitizeForWire('subtree', {
3509
+ root: wireClone,
3510
+ liveRoot: el,
3511
+ cloneToNid: cloneToNid
3512
+ });
3513
+ if (subtreeResult && subtreeResult.drop) return null;
3514
+ var nodeIds = buildNodeIdSidecar(wireClone, cloneToNid, true);
3515
+ var shadowRoots = collectShadowRootPayloads(el, nodeIds);
3516
+ var frames = collectFramePayloads(el, cloneToNid);
3517
+ var addedResult = {
3518
+ html: wireClone.outerHTML || '',
3519
+ nodeIds: nodeIds,
3520
+ shadowRoots: shadowRoots,
3521
+ frames: frames
3522
+ };
3523
+ if (styleMode === 'cssom') {
3524
+ addedResult.styleSources = [];
3525
+ addedResult.styleStrategy = buildStyleStrategy('cssom', []);
3526
+ }
3527
+ return addedResult;
3528
+ }
3529
+
3530
+ function contentFreeSubtreeStatus(status) {
3531
+ return {
3532
+ status: status,
3533
+ nodeIds: [],
3534
+ shadowRoots: [],
3535
+ frames: []
3536
+ };
3537
+ }
3538
+
3539
+ function serializeRequestedSubtree(nid) {
3540
+ var key = String(nid || '');
3541
+ if (!key) return contentFreeSubtreeStatus('untracked');
3542
+ var el = nidToElement.get(key);
3543
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) {
3544
+ return contentFreeSubtreeStatus('untracked');
3545
+ }
3546
+ if (el.isConnected === false) {
3547
+ return contentFreeSubtreeStatus('gone');
3548
+ }
3549
+ if (getTrackedNodeId(el) !== key) {
3550
+ return contentFreeSubtreeStatus('untracked');
3551
+ }
3552
+ if (skipElementWithAncestors(el)) {
3553
+ return contentFreeSubtreeStatus('skipped');
3554
+ }
3555
+ if (blockedWithAncestors(el)) {
3556
+ return contentFreeSubtreeStatus('blocked');
3557
+ }
3558
+ if (wireDroppedWithAncestors(el)) {
3559
+ return contentFreeSubtreeStatus('blocked');
3560
+ }
3561
+
3562
+ var sanBefore = sanitizeCountersSnapshot();
3563
+ var payload = processAddedNode(el);
3564
+ warnIfSanitizeStrips(sanBefore);
3565
+ if (!payload) {
3566
+ return contentFreeSubtreeStatus('blocked');
3567
+ }
3568
+ return {
3569
+ status: 'ok',
3570
+ html: payload.html || '',
3571
+ nodeIds: payload.nodeIds || [],
3572
+ shadowRoots: payload.shadowRoots || [],
3573
+ frames: payload.frames || []
3574
+ };
3575
+ }
3576
+
3577
+ function isCurrentControlPayload(payload) {
3578
+ if (!payload) return false;
3579
+ if (!streamSessionId || !currentSnapshotId) return false;
3580
+ if (String(payload.streamSessionId || '') !== String(streamSessionId)) return false;
3581
+ if (String(payload.snapshotId || '') !== String(currentSnapshotId)) return false;
3582
+ return true;
3583
+ }
3584
+
3585
+ function sendSubtreeResponse(request, result) {
3586
+ var response = Object.assign({
3587
+ requestId: request && request.requestId != null ? String(request.requestId) : '',
3588
+ nid: request && request.nid != null ? String(request.nid) : '',
3589
+ status: result.status || 'untracked',
3590
+ streamSessionId: streamSessionId || '',
3591
+ snapshotId: currentSnapshotId || 0
3592
+ }, result);
3593
+ if (response.status === 'ok' && wireByteLength(response) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
3594
+ response = Object.assign({
3595
+ requestId: request && request.requestId != null ? String(request.requestId) : '',
3596
+ nid: request && request.nid != null ? String(request.nid) : '',
3597
+ streamSessionId: streamSessionId || '',
3598
+ snapshotId: currentSnapshotId || 0
3599
+ }, contentFreeSubtreeStatus('too-large'));
3600
+ }
3601
+ safeSend(STREAM.SUBTREE_RESPONSE, response);
3602
+ }
3603
+
3604
+ function handleControl(type, payload) {
3605
+ if (type !== CONTROL.SUBTREE_REQUEST) return;
3606
+ var request = payload || {};
3607
+ if (!isCurrentControlPayload(request)) {
3608
+ sendSubtreeResponse(request, contentFreeSubtreeStatus('stale'));
3609
+ return;
3610
+ }
3611
+ sendSubtreeResponse(request, serializeRequestedSubtree(request.nid));
3612
+ }
3613
+
3614
+ /**
3615
+ * Process a batch of accumulated mutations into diff objects.
3616
+ * @param {MutationRecord[]} mutations
3617
+ * @returns {Array} Array of diff objects
3618
+ */
3619
+ function processMutationBatch(mutations) {
3620
+ var diffs = [];
3621
+ var removedRoots = [];
3622
+ var shadowHosts = new Map();
3623
+ // Dedup registry for childList-derived text ops (fidelity fix, ledger
3624
+ // D6): multiple childList records in one batch targeting the same
3625
+ // element (e.g. two textContent= writes between flushes) collapse to a
3626
+ // single op. The op text is read LIVE from the target at process time,
3627
+ // so every record for the same element yields the same final value --
3628
+ // dedup loses nothing.
3629
+ var textOpNids = {};
3630
+
3631
+ for (var i = 0; i < mutations.length; i++) {
3632
+ var m = mutations[i];
3633
+ var frameRecord = getMutationFrameRecord(m.target);
3634
+ if (!frameRecord && isInactiveFrameDocumentMutation(m.target)) continue;
3635
+
3636
+ // Skip mutations on host-flagged elements (skipElement seam).
3637
+ // Ancestor-inclusive, matching the reference's isFsbOverlay closest()
3638
+ // semantics: mutations anywhere inside a skipped subtree are dropped.
3639
+ if (m.target && m.target.nodeType === Node.ELEMENT_NODE &&
3640
+ (skipElementWithAncestors(m.target) || blockedWithAncestors(m.target) || wireDroppedWithAncestors(m.target))) {
3641
+ continue;
3642
+ }
3643
+ if (m.target && m.target.nodeType === Node.TEXT_NODE &&
3644
+ m.target.parentElement &&
3645
+ (skipElementWithAncestors(m.target.parentElement)
3646
+ || blockedWithAncestors(m.target.parentElement)
3647
+ || wireDroppedWithAncestors(m.target.parentElement))) {
3648
+ continue;
3649
+ }
3650
+
3651
+ var shadowHost = getMutationShadowHost(m.target);
3652
+ if (shadowHost) {
3653
+ if (skipElementWithAncestors(shadowHost) || blockedWithAncestors(shadowHost) || wireDroppedWithAncestors(shadowHost)) {
3654
+ continue;
3655
+ }
3656
+ var shadowHostNid = getTrackedNodeId(shadowHost) || ensureNodeId(shadowHost);
3657
+ if (shadowHostNid) {
3658
+ shadowHosts.set(String(shadowHostNid), {
3659
+ host: shadowHost,
3660
+ frameRecord: frameRecord
3661
+ });
3662
+ }
3663
+ continue;
3664
+ }
3665
+
3666
+ if (m.type === 'childList') {
3667
+ if (styleMode === 'cssom' && m.target && m.target.nodeType === Node.ELEMENT_NODE) {
3668
+ var childListTag = m.target.tagName ? String(m.target.tagName).toLowerCase() : '';
3669
+ if (childListTag === 'style') markStyleOwnerDirty(m.target, 'style-text-mutated');
3670
+ }
3671
+ // Bare text-node add/remove detection (fidelity fix, differential
3672
+ // ledger D6): el.textContent = '...' REPLACES the text child, which
3673
+ // the observer reports as a childList record with a TEXT-node
3674
+ // removal+addition. The reference's element-only loops drop it --
3675
+ // silent mirror drift with no stale-miss and no self-heal (Phase 2
3676
+ // real-browser checkpoint finding). When any added/removed node is
3677
+ // a TEXT or CDATA node, a text op for the mutation TARGET (the
3678
+ // parent element) is emitted below, mirroring the characterData
3679
+ // branch's shape -- unless the mixed-content guard at the emission
3680
+ // site suppresses it. Comment nodes stay excluded: they never
3681
+ // render.
3682
+ var sawBareTextNode = false;
3683
+
3684
+ // Added nodes
3685
+ for (var a = 0; a < m.addedNodes.length; a++) {
3686
+ var added = m.addedNodes[a];
3687
+ if (added.nodeType === Node.ELEMENT_NODE) {
3688
+ if (skipElementWithAncestors(added)) continue;
3689
+ if (wireDroppedWithAncestors(added.parentElement)) continue;
3690
+ if (blockedWithAncestors(added.parentElement)) continue;
3691
+
3692
+ var parentNid = getTrackedNodeId(m.target);
3693
+ if (!parentNid) continue; // Parent not tracked
3694
+
3695
+ var addedPayload = processAddedNode(added);
3696
+ // SEC-01: a forbidden root (script/noscript/object/embed)
3697
+ // scrubs to nothing -- emit no add op rather than an empty op.
3698
+ if (!addedPayload || !addedPayload.html) continue;
3699
+ observeOpenShadowRoots(added);
3700
+ observeSameOriginFrameDocuments(added);
3701
+ var nextSib = added.nextElementSibling;
3702
+ var beforeNid = getTrackedNodeId(nextSib);
3703
+
3704
+ var addDiff = scopeFrameDiff({
3705
+ op: 'add',
3706
+ parentNid: parentNid,
3707
+ html: addedPayload.html,
3708
+ beforeNid: beforeNid,
3709
+ nodeIds: addedPayload.nodeIds,
3710
+ shadowRoots: addedPayload.shadowRoots || [],
3711
+ frames: addedPayload.frames || []
3712
+ }, frameRecord);
3713
+ diffs.push(boundMutationDiffForBudget(addDiff));
3714
+ } else if (added.nodeType === Node.TEXT_NODE || added.nodeType === Node.CDATA_SECTION_NODE) {
3715
+ sawBareTextNode = true;
3716
+ }
3717
+ }
3718
+
3719
+ // Removed nodes
3720
+ for (var r = 0; r < m.removedNodes.length; r++) {
3721
+ var removed = m.removedNodes[r];
3722
+ if (removed.nodeType === Node.ELEMENT_NODE) {
3723
+ if (wireDroppedWithAncestors(removed)) continue;
3724
+ var nid = getTrackedNodeId(removed);
3725
+ if (!nid) continue; // Not tracked
3726
+ diffs.push(scopeFrameDiff({ op: 'rm', nid: nid }, frameRecord));
3727
+ removedRoots.push(removed);
3728
+ } else if (removed.nodeType === Node.TEXT_NODE || removed.nodeType === Node.CDATA_SECTION_NODE) {
3729
+ sawBareTextNode = true;
3730
+ }
3731
+ }
3732
+
3733
+ // Emit AFTER both loops so a textContent= that also removed element
3734
+ // children orders its rm ops before the text op -- the renderer then
3735
+ // removes the elements and sets the final flat text, matching the
3736
+ // live DOM end state.
3737
+ //
3738
+ // MIXED-CONTENT GUARD (review CR-01): the renderer applies this op
3739
+ // as textContent = text, which REPLACES every child of the mirrored
3740
+ // target. Emitting it while the live target still has element
3741
+ // children (a text-node append into a mixed container, innerHTML
3742
+ // with mixed content) would destroy mirrored element subtrees that
3743
+ // still exist in the live DOM -- structural corruption with no
3744
+ // stale-miss signal. Gating on firstElementChild keeps the
3745
+ // textContent= shape working (its element children were just
3746
+ // removed, so the live read is null) and reverts mixed-content text
3747
+ // changes to the reference's drop behavior: text drift, structure
3748
+ // intact. Residual gap documented in the E2 README entry and the D6
3749
+ // ledger rationale.
3750
+ if (sawBareTextNode && !m.target.firstElementChild) {
3751
+ var textTargetNid = getTrackedNodeId(m.target);
3752
+ if (textTargetNid && !textOpNids[textTargetNid]) {
3753
+ textOpNids[textTargetNid] = true;
3754
+ // SEC-03 masking seam (plan 03-03): maskTextSelector /
3755
+ // maskTextFn applied inside the chokepoint; owner is the
3756
+ // mutation target itself for E2.
3757
+ var e2TextResult = sanitizeForWire('text', {
3758
+ text: m.target.textContent,
3759
+ owner: m.target
3760
+ });
3761
+ // Same wire shape as the characterData branch: the renderer's
3762
+ // DIFF_OP.TEXT applier sets textContent on the nid target.
3763
+ diffs.push(scopeFrameDiff({
3764
+ op: 'text',
3765
+ nid: textTargetNid,
3766
+ text: e2TextResult.text
3767
+ }, frameRecord));
3768
+ }
3769
+ }
3770
+ } else if (m.type === 'attributes') {
3771
+ var attrName = String(m.attributeName || '');
3772
+ var attrNameLower = attrName.toLowerCase();
3773
+ var attrTargetTag = m.target && m.target.tagName ? String(m.target.tagName).toLowerCase() : '';
3774
+ if (styleMode === 'cssom'
3775
+ && attrTargetTag === 'link'
3776
+ && (attrNameLower === 'href' || attrNameLower === 'media' || attrNameLower === 'disabled')) {
3777
+ markStyleOwnerDirty(m.target, 'link-attr-mutated');
3778
+ }
3779
+ var targetNid = getTrackedNodeId(m.target);
3780
+ if (!targetNid) continue;
3781
+
3782
+ if (attrTargetTag === 'iframe' && attrNameLower === 'src') {
3783
+ registerFrameLoadListener(m.target, targetNid);
3784
+ continue;
3785
+ }
3786
+
3787
+ var attrVal = m.target.getAttribute(m.attributeName);
3788
+ // Absolutify URL attributes in mutations
3789
+ if (URL_ATTRS.indexOf(m.attributeName) !== -1 && attrVal) {
3790
+ attrVal = absolutifyUrl(attrVal, m.target.ownerDocument);
3791
+ }
3792
+ if (m.attributeName === 'srcset' && attrVal) {
3793
+ attrVal = absolutifySrcset(attrVal, m.target.ownerDocument);
3794
+ }
3795
+
3796
+ // SEC-01: route through the chokepoint AFTER absolutification so
3797
+ // the scheme check runs on final wire values (Pitfall 5: this
3798
+ // branch was the snapshot sanitizer's bypass).
3799
+ var attrResult = sanitizeForWire('attr', {
3800
+ name: m.attributeName,
3801
+ value: attrVal,
3802
+ target: m.target
3803
+ });
3804
+ if (attrResult.drop) continue;
3805
+
3806
+ diffs.push(scopeFrameDiff({
3807
+ op: 'attr',
3808
+ nid: targetNid,
3809
+ attr: m.attributeName,
3810
+ val: attrResult.value
3811
+ }, frameRecord));
3812
+ } else if (m.type === 'characterData') {
3813
+ var parentEl = m.target.parentElement;
3814
+ if (styleMode === 'cssom'
3815
+ && parentEl
3816
+ && parentEl.tagName
3817
+ && String(parentEl.tagName).toLowerCase() === 'style') {
3818
+ markStyleOwnerDirty(parentEl, 'style-text-mutated');
3819
+ }
3820
+ var textNid = getTrackedNodeId(parentEl);
3821
+ if (!textNid) continue;
3822
+
3823
+ // SEC-03 masking seam (plan 03-03): maskTextSelector / maskTextFn
3824
+ // applied inside the chokepoint; owner is the LIVE parent element.
3825
+ var textResult = sanitizeForWire('text', {
3826
+ text: m.target.textContent,
3827
+ owner: parentEl
3828
+ });
3829
+
3830
+ diffs.push(scopeFrameDiff({
3831
+ op: 'text',
3832
+ nid: textNid,
3833
+ text: textResult.text
3834
+ }, frameRecord));
3835
+ }
3836
+ }
3837
+
3838
+ shadowHosts.forEach(function(entry, hostNid) {
3839
+ var host = entry && entry.host ? entry.host : entry;
3840
+ var payload = serializeOpenShadowRoot(host, hostNid);
3841
+ if (!payload) return;
3842
+ diffs.push(scopeFrameDiff(
3843
+ Object.assign({ op: DIFF_OP.SHADOW_ROOT }, payload),
3844
+ entry && entry.frameRecord ? entry.frameRecord : null
3845
+ ));
3846
+ });
3847
+
3848
+ for (var rr = 0; rr < removedRoots.length; rr++) {
3849
+ if (!removedRoots[rr].isConnected) {
3850
+ forgetSubtreeIdentity(removedRoots[rr]);
3851
+ }
3852
+ }
3853
+
3854
+ return diffs;
3855
+ }
3856
+
3857
+ function mutationPayloadForBudget(diffs, options) {
3858
+ var opts = options || {};
3859
+ var payload = {
3860
+ mutations: diffs || [],
3861
+ streamSessionId: streamSessionId || '',
3862
+ snapshotId: currentSnapshotId || 0
3863
+ };
3864
+ if (opts.includeStaleFlushCount !== false) {
3865
+ payload.staleFlushCount = staleFlushCount;
3866
+ }
3867
+ return payload;
3868
+ }
3869
+
3870
+ function firstPayloadNodeId(nodeIds) {
3871
+ if (!Array.isArray(nodeIds)) return '';
3872
+ for (var i = 0; i < nodeIds.length; i++) {
3873
+ if (nodeIds[i] !== undefined && nodeIds[i] !== null && String(nodeIds[i]) !== '') {
3874
+ return String(nodeIds[i]);
3875
+ }
3876
+ }
3877
+ return '';
3878
+ }
3879
+
3880
+ function boundedAddPlaceholder(diff) {
3881
+ var rootNid = Array.isArray(diff.nodeIds) && diff.nodeIds.length ? diff.nodeIds[0] : '';
3882
+ if (!rootNid) return null;
3883
+ var bounded = Object.assign({
3884
+ op: DIFF_OP.ADD,
3885
+ parentNid: diff.parentNid || '',
3886
+ beforeNid: diff.beforeNid || ''
3887
+ }, truncatedPayloadForNid(document, rootNid));
3888
+ if (diff.frameNid) bounded.frameNid = diff.frameNid;
3889
+ return bounded;
3890
+ }
3891
+
3892
+ function boundedFramePlaceholder(diff) {
3893
+ var frame = diff && diff.frame ? diff.frame : {};
3894
+ var frameNid = String((diff && diff.frameNid) || frame.frameNid || '');
3895
+ if (!frameNid) return null;
3896
+ var rootNid = firstPayloadNodeId(frame.nodeIds) || String(frame.bodyNid || frame.htmlNid || '');
3897
+ if (!rootNid) return null;
3898
+ var placeholder = truncatedPayloadForNid(document, rootNid);
3899
+ var boundedFrame = {
3900
+ frameNid: frameNid,
3901
+ kind: 'same-origin',
3902
+ html: placeholder.html || '',
3903
+ nodeIds: placeholder.nodeIds || [],
3904
+ shadowRoots: [],
3905
+ htmlNid: frame.htmlNid ? String(frame.htmlNid) : '',
3906
+ bodyNid: frame.bodyNid ? String(frame.bodyNid) : '',
3907
+ frames: [],
3908
+ stylesheets: [],
3909
+ inlineStyles: [],
3910
+ htmlAttrs: {},
3911
+ bodyAttrs: {},
3912
+ htmlStyle: '',
3913
+ bodyStyle: '',
3914
+ scrollX: frame.scrollX || 0,
3915
+ scrollY: frame.scrollY || 0,
3916
+ viewportWidth: frame.viewportWidth || 0,
3917
+ viewportHeight: frame.viewportHeight || 0,
3918
+ pageWidth: frame.pageWidth || 0,
3919
+ pageHeight: frame.pageHeight || 0,
3920
+ url: '',
3921
+ title: '',
3922
+ truncated: true,
3923
+ missingDescendants: (frame.missingDescendants || 0) + 1
3924
+ };
3925
+ return { op: DIFF_OP.FRAME, frameNid: frameNid, frame: boundedFrame };
3926
+ }
3927
+
3928
+ function boundedShadowRootPlaceholder(diff) {
3929
+ var hostNid = String((diff && diff.hostNid) || '');
3930
+ var rootNid = firstPayloadNodeId(diff && diff.nodeIds);
3931
+ if (!hostNid || !rootNid) return null;
3932
+ var placeholder = truncatedPayloadForNid(document, rootNid);
3933
+ var bounded = {
3934
+ op: DIFF_OP.SHADOW_ROOT,
3935
+ hostNid: hostNid,
3936
+ mode: diff.mode || 'open',
3937
+ html: placeholder.html || '',
3938
+ nodeIds: placeholder.nodeIds || [],
3939
+ slotAssignment: diff.slotAssignment || 'none',
3940
+ truncated: true,
3941
+ missingDescendants: (diff.missingDescendants || 0) + 1
3942
+ };
3943
+ if (diff.frameNid) bounded.frameNid = diff.frameNid;
3944
+ return bounded;
3945
+ }
3946
+
3947
+ function boundMutationDiffForBudget(diff, options) {
3948
+ if (!diff) return null;
3949
+ if (wireByteLength(mutationPayloadForBudget([diff], options)) <= RELAY_PER_MESSAGE_LIMIT_BYTES) return diff;
3950
+ var bounded = null;
3951
+ if (diff.op === DIFF_OP.ADD) bounded = boundedAddPlaceholder(diff);
3952
+ if (diff.op === DIFF_OP.FRAME) bounded = boundedFramePlaceholder(diff);
3953
+ if (diff.op === DIFF_OP.SHADOW_ROOT) bounded = boundedShadowRootPlaceholder(diff);
3954
+ if (!bounded) return null;
3955
+ return wireByteLength(mutationPayloadForBudget([bounded], options)) <= RELAY_PER_MESSAGE_LIMIT_BYTES
3956
+ ? bounded
3957
+ : null;
3958
+ }
3959
+
3960
+ function sendMutationDiffs(diffs, options) {
3961
+ var chunk = [];
3962
+ for (var i = 0; i < diffs.length; i++) {
3963
+ var originalDiff = diffs[i];
3964
+ var diff = boundMutationDiffForBudget(originalDiff, options);
3965
+ if (!diff) {
3966
+ if (originalDiff) {
3967
+ logger.warn('[DOM Stream] mutation diff dropped over budget', {
3968
+ op: originalDiff && originalDiff.op ? originalDiff.op : ''
3969
+ });
3970
+ }
3971
+ continue;
3972
+ }
3973
+ var singlePayload = mutationPayloadForBudget([diff], options);
3974
+ if (wireByteLength(singlePayload) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
3975
+ logger.warn('[DOM Stream] mutation diff dropped over budget', {
3976
+ op: diff && diff.op ? diff.op : ''
3977
+ });
3978
+ continue;
3979
+ }
3980
+ var nextChunk = chunk.concat([diff]);
3981
+ if (chunk.length && wireByteLength(mutationPayloadForBudget(nextChunk, options)) > RELAY_PER_MESSAGE_LIMIT_BYTES) {
3982
+ safeSend(STREAM.MUTATIONS, mutationPayloadForBudget(chunk, options));
3983
+ chunk = [diff];
3984
+ } else {
3985
+ chunk = nextChunk;
3986
+ }
3987
+ }
3988
+ if (chunk.length) {
3989
+ safeSend(STREAM.MUTATIONS, mutationPayloadForBudget(chunk, options));
3990
+ }
3991
+ }
3992
+
3993
+ /**
3994
+ * Flush pending mutations: process into diffs and send via the transport.
3995
+ */
3996
+ function flushMutations() {
3997
+ batchTimer = null;
3998
+ if (pendingMutations.length === 0 && pendingStyleSourceChanges.size === 0) return;
3999
+
4000
+ var batch = pendingMutations;
4001
+ pendingMutations = [];
4002
+
4003
+ // SEC-01: the aggregate strip warn fires even when every diff in the
4004
+ // batch was dropped by the chokepoint (counted + logged, never silent),
4005
+ // so the snapshot/compare wraps the empty-diffs early return.
4006
+ var sanBefore = sanitizeCountersSnapshot();
4007
+ var diffs = [];
4008
+ flushingMutations = true;
4009
+ try {
4010
+ diffs = processMutationBatch(batch);
4011
+ reconcileAllKnownStyleScopes();
4012
+ diffs = diffs.concat(drainPendingStyleSourceDiffs());
4013
+ } finally {
4014
+ flushingMutations = false;
4015
+ }
4016
+ warnIfSanitizeStrips(sanBefore);
4017
+ if (diffs.length === 0) return;
4018
+
4019
+ sendMutationDiffs(diffs);
4020
+
4021
+ // Phase 211-02 STREAM-02: stale counter resets on successful drain.
4022
+ // Reset is flush-based (not ack-based) per D-14 / STREAM-FUTURE-01 deferral.
4023
+ // The peak count is captured in the payload above BEFORE this reset, so
4024
+ // the host sees the watchdog-rescue count at drain time.
4025
+ lastDrainTs = Date.now();
4026
+ staleFlushCount = 0;
4027
+ }
4028
+
4029
+ /**
4030
+ * Start the MutationObserver stream on document.body.
4031
+ * Batches mutations via requestAnimationFrame for display-matched delivery (D-06).
4032
+ */
4033
+ function startMutationStream() {
4034
+ if (mutationObserver) {
4035
+ mutationObserver.disconnect();
4036
+ }
4037
+
4038
+ pendingMutations = [];
4039
+ observedShadowRoots = new WeakSet();
4040
+ clearObservedFrameDocuments();
4041
+
4042
+ mutationObserver = new MutationObserver(function(mutations) {
4043
+ // Accumulate mutations
4044
+ for (var i = 0; i < mutations.length; i++) {
4045
+ pendingMutations.push(mutations[i]);
4046
+ }
4047
+
4048
+ // Batch flush synced to browser paint cycle via rAF (FIDELITY-03).
4049
+ scheduleMutationFlush();
4050
+ });
4051
+
4052
+ mutationObserver.observe(document.body, mutationObserverOptions());
4053
+ if (styleMode === 'cssom' && document.head) {
4054
+ try {
4055
+ mutationObserver.observe(document.head, mutationObserverOptions());
4056
+ } catch (err) {
4057
+ logger.warn('[DOM Stream] cssom hook unavailable', { reason: 'cssom-hook-unavailable' });
4058
+ }
4059
+ }
4060
+ observeOpenShadowRoots(document.body);
4061
+ observeSameOriginFrameDocuments(document.body);
4062
+ wrapAttachShadow();
4063
+ patchCssStyleSheetMethods();
4064
+
4065
+ // Phase 211-02 STREAM-01: 5s capture-side self-watchdog (trip wire).
4066
+ // Detects stuck mutation queues without involving the host. Uses a
4067
+ // self-re-arming setTimeout chain (never a fixed-interval timer) so
4068
+ // cadence resets on every tick and on every successful drain. Host-side
4069
+ // safety nets (e.g. the MV3 service-worker alarm in the reference
4070
+ // deployment) cover the case where this context itself is wedged.
4071
+ lastDrainTs = Date.now();
4072
+ if (watchdogTimer) clearTimeout(watchdogTimer);
4073
+ var watchdogTick = function() {
4074
+ try {
4075
+ if (pendingMutations.length > 0 && (Date.now() - lastDrainTs) > MUTATION_STALE_THRESHOLD_MS) {
4076
+ // Increment BEFORE forced flush so the new value is observable
4077
+ // post-flush (per D-04). flushMutations resets staleFlushCount
4078
+ // back to 0, so this counter only grows when the watchdog is
4079
+ // actively rescuing a stuck queue.
4080
+ staleFlushCount++;
4081
+ if (batchTimer) {
4082
+ cancelAnimationFrame(batchTimer);
4083
+ batchTimer = null;
4084
+ }
4085
+ flushMutations();
4086
+ }
4087
+ } catch (e) { /* watchdog must not crash the capture context */ }
4088
+ watchdogTimer = setTimeout(watchdogTick, WATCHDOG_TICK_MS);
4089
+ };
4090
+ watchdogTimer = setTimeout(watchdogTick, WATCHDOG_TICK_MS);
4091
+
4092
+ logger.info('[DOM Stream] MutationObserver started');
4093
+ }
4094
+
4095
+ /**
4096
+ * Stop the MutationObserver stream and flush any pending mutations.
4097
+ */
4098
+ function stopMutationStream() {
4099
+ stopValueCapture();
4100
+
4101
+ if (batchTimer) {
4102
+ cancelAnimationFrame(batchTimer);
4103
+ batchTimer = null;
4104
+ }
4105
+
4106
+ if (watchdogTimer) {
4107
+ clearTimeout(watchdogTimer);
4108
+ watchdogTimer = null;
4109
+ }
4110
+
4111
+ if (mutationObserver) {
4112
+ mutationObserver.disconnect();
4113
+ mutationObserver = null;
4114
+ }
4115
+ observedShadowRoots = new WeakSet();
4116
+ restoreAttachShadow();
4117
+ restoreCssStyleSheetMethods();
4118
+
4119
+ // Flush any remaining mutations.
4120
+ // PARITY: the stop-path payload intentionally omits staleFlushCount,
4121
+ // matching the reference's asymmetry between the normal flush and the
4122
+ // final stop-path flush.
4123
+ if (pendingMutations.length > 0) {
4124
+ var batch = pendingMutations;
4125
+ pendingMutations = [];
4126
+ // SEC-01: same aggregate strip-warn discipline as flushMutations.
4127
+ var sanBefore = sanitizeCountersSnapshot();
4128
+ flushingMutations = true;
4129
+ var diffs = [];
4130
+ try {
4131
+ diffs = processMutationBatch(batch);
4132
+ reconcileAllKnownStyleScopes();
4133
+ diffs = diffs.concat(drainPendingStyleSourceDiffs());
4134
+ } finally {
4135
+ flushingMutations = false;
4136
+ }
4137
+ warnIfSanitizeStrips(sanBefore);
4138
+ if (diffs.length > 0) {
4139
+ sendMutationDiffs(diffs, { includeStaleFlushCount: false });
4140
+ }
4141
+ }
4142
+
4143
+ clearObservedFrameDocuments();
4144
+ logger.info('[DOM Stream] MutationObserver stopped');
4145
+ }
4146
+
4147
+ // =========================================================================
4148
+ // 3. Scroll Tracker
4149
+ // =========================================================================
4150
+
4151
+ /**
4152
+ * Start tracking scroll position changes.
4153
+ * Throttled to max 1 event per SCROLL_THROTTLE_MS using timestamp check.
4154
+ */
4155
+ function startScrollTracker() {
4156
+ if (scrollHandler) {
4157
+ window.removeEventListener('scroll', scrollHandler);
4158
+ }
4159
+
4160
+ lastScrollSend = 0;
4161
+
4162
+ scrollHandler = function() {
4163
+ var now = Date.now();
4164
+ if (now - lastScrollSend < SCROLL_THROTTLE_MS) return;
4165
+ lastScrollSend = now;
4166
+
4167
+ safeSend(STREAM.SCROLL, {
4168
+ scrollX: window.scrollX,
4169
+ scrollY: window.scrollY,
4170
+ streamSessionId: streamSessionId || '',
4171
+ snapshotId: currentSnapshotId || 0
4172
+ });
4173
+ };
4174
+
4175
+ window.addEventListener('scroll', scrollHandler, { passive: true });
4176
+ logger.info('[DOM Stream] Scroll tracker started');
4177
+ }
4178
+
4179
+ /**
4180
+ * Stop tracking scroll position changes.
4181
+ */
4182
+ function stopScrollTracker() {
4183
+ if (scrollHandler) {
4184
+ window.removeEventListener('scroll', scrollHandler);
4185
+ scrollHandler = null;
4186
+ }
4187
+ logger.info('[DOM Stream] Scroll tracker stopped');
4188
+ }
4189
+
4190
+ // =========================================================================
4191
+ // 4. Overlay Event Broadcaster
4192
+ // =========================================================================
4193
+
4194
+ /**
4195
+ * Read current host overlay state through the overlayProvider seam and
4196
+ * broadcast it. Pass-through contract (Phase 2 VIEW-04 extension, README
4197
+ * entry E1): EVERY own enumerable key of the provider's returned state is
4198
+ * forwarded on the wire as an overlay kind, so custom DOM-anchored
4199
+ * overlays reach the viewer end-to-end. The built-ins `glow` and
4200
+ * `progress` still default to null when the provider omits them, and the
4201
+ * identity keys (streamSessionId / snapshotId) are reserved: they are
4202
+ * assigned LAST, after the provider copy, so a provider can never
4203
+ * overwrite stream identity (threat T-02-06).
4204
+ *
4205
+ * With no provider configured -- or a throwing provider -- the message
4206
+ * carries exactly { glow: null, progress: null, streamSessionId,
4207
+ * snapshotId }, byte-compatible with the reference's wire shape
4208
+ * (differential-oracle protection: no fixture configures a provider).
4209
+ * @param {boolean} [force] - Bypass the throttle (lifecycle broadcasts)
4210
+ */
4211
+ function broadcastOverlayState(force) {
4212
+ // Throttle to max 1 broadcast per OVERLAY_THROTTLE_MS (per D-05)
4213
+ var now = Date.now();
4214
+ if (!force && (now - lastOverlayBroadcast < OVERLAY_THROTTLE_MS)) return;
4215
+ lastOverlayBroadcast = now;
4216
+
4217
+ var payload = {};
4218
+
4219
+ // overlayProvider seam: replaces the reference's host-namespace overlay
4220
+ // reads. Provider errors are swallowed exactly like the reference's
4221
+ // try/catch around its overlay reads; on error the payload resets to
4222
+ // the defaults-only shape.
4223
+ try {
4224
+ if (overlayProvider) {
4225
+ var state = overlayProvider();
4226
+ if (state) {
4227
+ for (var key in state) {
4228
+ if (Object.prototype.hasOwnProperty.call(state, key)) {
4229
+ payload[key] = state[key];
4230
+ }
4231
+ }
4232
+ }
4233
+ }
4234
+ } catch (e) { payload = {}; /* swallowed like the reference */ }
4235
+
4236
+ // Built-in kinds default null even when the provider omits them
4237
+ // (reference wire shape; the viewer's null-hides contract relies on
4238
+ // these keys always being present).
4239
+ payload.glow = payload.glow || null;
4240
+ payload.progress = payload.progress || null;
4241
+
4242
+ // Identity keys assigned LAST: provider keys can never overwrite the
4243
+ // stream identity (T-02-06).
4244
+ payload.streamSessionId = streamSessionId || '';
4245
+ payload.snapshotId = currentSnapshotId || 0;
4246
+
4247
+ safeSend(STREAM.OVERLAY, payload);
4248
+ }
4249
+
4250
+ // =========================================================================
4251
+ // 5. Lifecycle API (replaces the reference's control-message listener)
4252
+ // =========================================================================
4253
+
4254
+ /**
4255
+ * Begin a fresh capture session: mint new identity, serialize a full
4256
+ * snapshot, then arm the mutation observer and scroll tracker.
4257
+ * Calling start() while streaming restarts cleanly (re-injection guard).
4258
+ */
4259
+ function start() {
4260
+ logger.info('[DOM Stream] Start requested');
4261
+ injectDialogInterceptor();
4262
+ setupDialogRelay();
4263
+ // Re-injection guard: stop existing stream before restarting
4264
+ if (streaming) {
4265
+ stopMutationStream();
4266
+ stopScrollTracker();
4267
+ }
4268
+ beginStreamSession();
4269
+ clearNodeMirror();
4270
+ nextNodeId = 1;
4271
+ var snapshot = serializeDOM();
4272
+ safeSend(STREAM.SNAPSHOT, snapshot);
4273
+ startMutationStream();
4274
+ startValueCapture();
4275
+ startScrollTracker();
4276
+ streaming = true;
4277
+ broadcastOverlayState(true);
4278
+ }
4279
+
4280
+ /**
4281
+ * Stop the capture: halt observers (final mutation flush included), then
4282
+ * give the host transport one deterministic flush() drain point.
4283
+ */
4284
+ function stop() {
4285
+ logger.info('[DOM Stream] Stop requested');
4286
+ stopMutationStream();
4287
+ stopScrollTracker();
4288
+ streaming = false;
4289
+ clearNodeMirror();
4290
+ safeFlush();
4291
+ }
4292
+
4293
+ /**
4294
+ * Pause the capture: halt observers but keep the session alive
4295
+ * (streaming stays true — paused state, not stopped).
4296
+ */
4297
+ function pause() {
4298
+ logger.info('[DOM Stream] Pause requested');
4299
+ stopMutationStream();
4300
+ stopScrollTracker();
4301
+ // Keep streaming = true (paused state, not stopped)
4302
+ }
4303
+
4304
+ /**
4305
+ * Resume the capture: re-arm the mutation observer and scroll tracker ONLY.
4306
+ *
4307
+ * D-06 USER OVERRIDE (divergence-ledger entry D1): unlike the reference,
4308
+ * resume does NOT mint a new session, does NOT re-serialize, and does NOT
4309
+ * send a snapshot — the same streamSessionId/snapshotId continue. Mutations
4310
+ * that occurred while paused are missed by design; hosts that need a fresh
4311
+ * view call stop() then start().
4312
+ */
4313
+ function resume() {
4314
+ logger.info('[DOM Stream] Resume requested');
4315
+ startMutationStream();
4316
+ startValueCapture();
4317
+ startScrollTracker();
4318
+ streaming = true;
4319
+ }
4320
+
4321
+ function getNodeId(element) {
4322
+ if (!streaming) return null;
4323
+ if (!element || element.nodeType !== Node.ELEMENT_NODE) return null;
4324
+ if (element.isConnected === false && !getMutationFrameRecord(element)) return null;
4325
+ return getTrackedNodeId(element);
4326
+ }
4327
+
4328
+ function getObservedFrameDocuments() {
4329
+ if (!streaming) return [];
4330
+ var roots = [];
4331
+ observedFrameDocuments.forEach(function(record) {
4332
+ if (!record || !record.document) return;
4333
+ roots.push({
4334
+ iframe: record.iframe,
4335
+ document: record.document,
4336
+ root: record.root || record.document,
4337
+ frameNid: record.frameNid
4338
+ });
4339
+ });
4340
+ return roots;
4341
+ }
4342
+
4343
+ // Readiness signal. The reference pinged its host once at script-load
4344
+ // time; the factory's creation moment is the closest analog for an
4345
+ // explicitly imported module (any residual timing difference is
4346
+ // divergence-ledger entry D3). The reference's host-polled readiness
4347
+ // probe is dropped entirely — hosts call these functions directly
4348
+ // (ledger entry D4).
4349
+ safeSend(STREAM.READY, {});
4350
+ logger.info('[DOM Stream] Module loaded');
4351
+
4352
+ return {
4353
+ start: start,
4354
+ stop: stop,
4355
+ pause: pause,
4356
+ resume: resume,
4357
+ handleControl: handleControl,
4358
+ getNodeId: getNodeId,
4359
+ getObservedFrameDocuments: getObservedFrameDocuments
4360
+ };
4361
+ }