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