@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,1401 @@
1
+ // PhantomStream renderer: createViewer -- the embeddable viewer component.
2
+ //
3
+ // Wires the pure renderer pieces (snapshot.js srcdoc builder, diff.js
4
+ // Document-parameterized applier, overlays.js registry + parity built-ins)
5
+ // into the auto-attaching viewer factory. Behavioral port of the FSB
6
+ // reference viewer's stream plumbing (reference/dashboard/dashboard.js,
7
+ // shipped as FSB milestone v0.9.9.1):
8
+ //
9
+ // - identity guard, generation-state reset, latched resync: 185-278
10
+ // - snapshot handler sequence (srcdoc write + onload): 2723-2829
11
+ // - scale-to-fit math: 2831-2869 (single fill-container mode)
12
+ // - resize wiring (window listener + guarded ResizeObserver): 3194-3207
13
+ // - mutation dispatch + post-batch scroll re-apply: 3209-3356
14
+ // - scroll handler (store first, gated smooth follow): 3358-3372
15
+ //
16
+ // Intentional divergences (renderer divergence ledger, plan 02-04):
17
+ // - FSB 9-state preview machine -> minimal 'waiting' | 'streaming' gate
18
+ // plus Phase 4's host-facing state/health event surface (VIEW-02).
19
+ // - tabId identity checks dropped (FSB extension concern); staleness goes
20
+ // through the protocol's isCurrentStream instead.
21
+ // - dash:request-status send dropped from the resync path -- the resync
22
+ // message is CONTROL.START alone (02-RESEARCH Pattern 2; a message named
23
+ // dash:request-snapshot does not exist anywhere in the protocol).
24
+ // - recordDashboardTransportEvent/-Error ring buffers dropped; renderer
25
+ // diagnostics go to the injected logger with the '[Renderer]' prefix.
26
+ // - Layout modes (inline/maximized/pip/fullscreen) dropped (D-03): the
27
+ // viewer always fills its container; layout belongs to the host.
28
+ // - Dialog identity-nesting quirk ported as-is (Pitfall 8): capture nests
29
+ // stream identity INSIDE payload.dialog, so the top-level isCurrentStream
30
+ // check finds no identity and always accepts dialogs. Explicit parity
31
+ // choice -- revisit when Phase 4 introduces multi-stream transports.
32
+ //
33
+ // Cross-runtime style per the capture-core precedent: var declarations,
34
+ // || inline defaulting, function expressions, named exports, explicit .js
35
+ // import extensions, factory-time validation as the ONLY throwing site.
36
+
37
+ import { buildSnapshotHtml, buildFramePlaceholderHtml } from './snapshot.js';
38
+ import { applyMutations } from './diff.js';
39
+ import { sanitizeFragment, scrubCssText } from './sanitize.js';
40
+ import { createOverlays, mapRectToHost, OVERLAY_CSS } from './overlays.js';
41
+ import { STREAM, CONTROL, isCurrentStream } from '../protocol/messages.js';
42
+
43
+ /**
44
+ * The host-injected viewer transport. Mirrors the capture Transport's
45
+ * fire-and-forget send contract and adds the receive side; Phase 4's
46
+ * WebSocket transport implements this same interface by encoding/decoding
47
+ * envelopes, so the viewer never changes.
48
+ *
49
+ * @typedef {Object} ViewerTransport
50
+ * @property {(type: string, payload: Object) => void} send
51
+ * Viewer -> capture host (CONTROL.* messages). Fire-and-forget; errors
52
+ * are contained to the injected logger, never thrown into the viewer.
53
+ * @property {(handler: (type: string, payload: Object) => void) => (() => void)} onMessage
54
+ * Subscribe to capture-host -> viewer (STREAM.*) messages. Returns an
55
+ * unsubscribe function; detach() invokes it.
56
+ * @property {(handler: (status: Object) => void) => (() => void)} [onStatus]
57
+ * Optional Phase 4 status subscription implemented by WebSocket transports.
58
+ * Status objects are telemetry only; mirrored payloads never flow here.
59
+ */
60
+
61
+ /**
62
+ * @typedef {Object} ViewerLogger
63
+ * @property {(...args: *) => void} info
64
+ * @property {(...args: *) => void} warn
65
+ * @property {(...args: *) => void} error
66
+ */
67
+
68
+ /**
69
+ * @typedef {Object} ViewerOptions
70
+ * @property {Element} container
71
+ * Required. Host element the viewer root is appended into (auto-attach,
72
+ * D-01). Factory throws Error('viewer-container-required') otherwise.
73
+ * @property {ViewerTransport} transport
74
+ * Required. Factory throws Error('viewer-transport-required') when send
75
+ * or onMessage is not a function.
76
+ * @property {ViewerLogger} [logger]
77
+ * Optional. Defaults to a console-backed logger.
78
+ * @property {number} [disconnectDelayMs]
79
+ * Optional stale-to-disconnected delay for closed transports. Defaults to a
80
+ * short demo-friendly window; tests may set a smaller value.
81
+ */
82
+
83
+ /**
84
+ * @typedef {Object} ViewerHandle
85
+ * @property {() => void} detach
86
+ * Unsubscribe from the transport, remove the resize listeners, and remove
87
+ * the viewer root from the container. Idempotent.
88
+ * @property {() => void} destroy
89
+ * detach() plus state/overlay reset. Idempotent.
90
+ * @property {() => {scale: Object, viewport: Object, container: Object}} getViewportMapping
91
+ * Return cloned scale, viewport, and container geometry for host-owned
92
+ * input overlays.
93
+ * @property {(nid: string|number) => ({nid: string, exists: boolean, rect: Object, streamSessionId: string, snapshotId: number}|null)} resolveNode
94
+ * Resolve an opaque PhantomStream nid to host-document geometry and stream
95
+ * identity. Missing or stale nids return null.
96
+ * @property {(nid: string|number, options?: {label?: string}) => boolean} highlightNode
97
+ * Show or update a local host-document highlight for a resolved nid.
98
+ * Returns false for stale or missing nids.
99
+ * @property {() => void} clearHighlight
100
+ * Hide the local node highlight. Idempotent.
101
+ * @property {(nid: string|number, options?: {reason?: string}) => string|null} requestSubtree
102
+ * Request a bounded fresh subtree for an indexed truncated marker. Returns
103
+ * the generated requestId, or null when the nid is invalid, missing, or
104
+ * already in flight.
105
+ * @property {(kind: string, renderFn: (payload: *, anchorRect: ?Object, layer: Element) => void) => void} registerOverlay
106
+ * Register a custom overlay kind (delegates to the overlays registry --
107
+ * the host-facing extension seam from D-10).
108
+ * @property {(eventName: 'state'|'health', handler: (event: Object) => void) => (() => void)} on
109
+ * Subscribe to host-facing lifecycle and health events. Returns unsubscribe.
110
+ */
111
+
112
+ /**
113
+ * Scale-to-fit math (pure). Port of dashboard.js:2859-2868 simplified to
114
+ * the single fill-container mode per 02-UI-SPEC "Scale-to-fit": page
115
+ * dimensions default to 1920x1080 and floor at 1; the scale factor is the
116
+ * min of the two container/page ratios with a !isFinite/<=0 clamp to 1;
117
+ * letterbox offsets center the scaled page and floor at 0.
118
+ *
119
+ * @param {number} pageW Captured page width (0/undefined -> 1920)
120
+ * @param {number} pageH Captured page height (0/undefined -> 1080)
121
+ * @param {number} containerW Host container width in px
122
+ * @param {number} containerH Host container height in px
123
+ * @returns {{s: number, offsetX: number, offsetY: number, pageW: number, pageH: number}}
124
+ */
125
+ export function computeScale(pageW, pageH, containerW, containerH) {
126
+ var w = Math.max(1, pageW || 1920);
127
+ var h = Math.max(1, pageH || 1080);
128
+ var s = Math.min(containerW / w, containerH / h);
129
+ if (!isFinite(s) || s <= 0) s = 1;
130
+ return {
131
+ s: s,
132
+ offsetX: Math.max(0, (containerW - w * s) / 2),
133
+ offsetY: Math.max(0, (containerH - h * s) / 2),
134
+ pageW: w,
135
+ pageH: h
136
+ };
137
+ }
138
+
139
+ /**
140
+ * Create an embeddable viewer bound to a host container: sandboxed mirror
141
+ * iframe, host-document overlay layer, transport message dispatch, scale-
142
+ * to-fit, scroll mirroring, and the latched CONTROL.START resync path.
143
+ * Auto-attaches on creation (D-01): calling this yields a live mirror as
144
+ * soon as the first snapshot arrives.
145
+ *
146
+ * Factory-time validation is the ONLY place this module throws (capture
147
+ * precedent); after creation every error routes to the injected logger.
148
+ *
149
+ * @param {ViewerOptions} options
150
+ * @returns {ViewerHandle}
151
+ */
152
+ export function createViewer(options) {
153
+ var cfg = options || {};
154
+
155
+ var container = cfg.container;
156
+ if (!container || typeof container.appendChild !== 'function') {
157
+ throw new Error('viewer-container-required');
158
+ }
159
+ var transport = cfg.transport;
160
+ if (!transport || typeof transport.send !== 'function'
161
+ || typeof transport.onMessage !== 'function') {
162
+ throw new Error('viewer-transport-required');
163
+ }
164
+ var logger = cfg.logger || {
165
+ info: function () { console.info.apply(console, arguments); },
166
+ warn: function () { console.warn.apply(console, arguments); },
167
+ error: function () { console.error.apply(console, arguments); }
168
+ };
169
+ var disconnectDelayMs = typeof cfg.disconnectDelayMs === 'number'
170
+ ? Math.max(0, cfg.disconnectDelayMs)
171
+ : 750;
172
+
173
+ // All DOM construction happens in the container's own document so the
174
+ // viewer works in any window (host page, jsdom test, future multi-doc).
175
+ var doc = container.ownerDocument;
176
+ var win = doc.defaultView;
177
+
178
+ // --- Viewer root: fills the container, clips the scaled mirror, and
179
+ // carries the loopback recursion-guard marker (02-RESEARCH Pattern 4) so
180
+ // a same-page capture can skipElement the entire viewer subtree. ---
181
+ var root = doc.createElement('div');
182
+ root.setAttribute('data-phantomstream-ui', 'viewer');
183
+ root.style.position = 'relative';
184
+ root.style.width = '100%';
185
+ root.style.height = '100%';
186
+ root.style.overflow = 'hidden';
187
+
188
+ // Viewer chrome styles travel as ONE injected style element (zero-dep
189
+ // constraint: hosts never import a stylesheet).
190
+ var styleEl = doc.createElement('style');
191
+ styleEl.textContent = OVERLAY_CSS;
192
+ root.appendChild(styleEl);
193
+
194
+ // --- Mirror iframe. Hidden until the first snapshot load so the host's
195
+ // waiting placeholder behind it stays visible (02-RESEARCH Pattern 6). ---
196
+ var iframe = doc.createElement('iframe');
197
+ iframe.setAttribute('title', 'PhantomStream live mirror');
198
+ iframe.style.position = 'absolute';
199
+ iframe.style.zIndex = '1'; // overlay layer sits above at z 2
200
+ iframe.style.transformOrigin = 'top left';
201
+ iframe.style.display = 'none';
202
+
203
+ // SANDBOX ASSERTION (phase criterion 3, threat T-02-08): the mirror
204
+ // renders attacker-influenced HTML, so the sandbox must be EXACTLY
205
+ // allow-same-origin -- same-origin access for diff applies and rect
206
+ // reads, zero script execution. Read back and verify so a hostile or
207
+ // broken environment fails loudly at creation instead of weakening the
208
+ // sandbox silently.
209
+ iframe.setAttribute('sandbox', 'allow-same-origin');
210
+ var sandboxTokens = (iframe.getAttribute('sandbox') || '').trim().split(/\s+/);
211
+ if (sandboxTokens.length !== 1 || sandboxTokens[0] !== 'allow-same-origin') {
212
+ throw new Error('viewer-sandbox-invalid');
213
+ }
214
+
215
+ // POST-PARSE SCRUB (plan 03-02, threat T-03-09): the srcdoc string
216
+ // cannot be fragment-scrubbed before the browser parses it -- string
217
+ // scrubbing is the mXSS anti-pattern (scrub-then-reparse) -- so the
218
+ // PARSED mirror document is scrubbed on every load instead. Registered
219
+ // FIRST so the scrub runs before the streaming flip below; reads
220
+ // contentDocument fresh per call (re-snapshots replace the document).
221
+ // In jsdom this listener is inert against srcdoc content (jsdom never
222
+ // parses srcdoc; the one about:blank load sees an empty body) -- the
223
+ // loopback glue recipe + a deliberately re-fired load event exercise it
224
+ // under test, and real browsers fire it on every srcdoc load. The
225
+ // sandbox assertion below stays untouched (phase criterion 3).
226
+ iframe.addEventListener('load', function () {
227
+ try {
228
+ var scrubDoc = iframe.contentDocument;
229
+ if (scrubDoc && scrubDoc.body) {
230
+ sanitizeFragment(scrubDoc.body, sanitizeCounters, logger);
231
+ if (lastSnapshotPayload) {
232
+ resetIdentityIndex(scrubDoc, lastSnapshotPayload.nodeIds || []);
233
+ installStyleSources(scrubDoc, lastSnapshotPayload.styleSources || [], { kind: 'document' });
234
+ installShadowRoots(scrubDoc, lastSnapshotPayload.shadowRoots || []);
235
+ installFrames(scrubDoc, lastSnapshotPayload.frames || []);
236
+ }
237
+ }
238
+ } catch (e) {
239
+ logger.warn('[Renderer] post-parse scrub failed', e);
240
+ }
241
+ });
242
+
243
+ // Snapshot-load completion handler, attached ONCE at creation (before the
244
+ // iframe is ever connected) rather than re-assigned per snapshot like the
245
+ // reference's iframe.onload. Divergence forced by jsdom (verified
246
+ // empirically this session): jsdom 29 only queues the iframe's initial
247
+ // about:blank load event when a load listener already exists at insertion
248
+ // time, and never re-fires load on srcdoc writes -- a per-snapshot onload
249
+ // assignment therefore never runs under test. In real browsers this
250
+ // listener fires on every srcdoc load with identical behavior. Guarded on
251
+ // a pending snapshot so the bare about:blank load (before any snapshot)
252
+ // leaves the viewer waiting.
253
+ iframe.addEventListener('load', function () {
254
+ if (!lastSnapshotPayload) return;
255
+ updateScale();
256
+ try {
257
+ iframe.contentWindow.scrollTo(
258
+ lastSnapshotPayload.scrollX || 0,
259
+ lastSnapshotPayload.scrollY || 0
260
+ );
261
+ } catch (e) { /* ignore: scroll restore is best-effort */ }
262
+ viewerState = 'streaming';
263
+ iframe.style.display = '';
264
+ });
265
+ root.appendChild(iframe);
266
+
267
+ // --- Overlay layer (host document, above the iframe, never inside the
268
+ // mirror). createOverlays pre-registers the glow/progress/dialog parity
269
+ // built-ins through the same registry custom kinds use. ---
270
+ var overlays = createOverlays({ document: doc, logger: logger });
271
+ root.appendChild(overlays.layer);
272
+
273
+ // Auto-attach (D-01): creation yields a live, ready-to-stream mirror.
274
+ container.appendChild(root);
275
+
276
+ // --- Viewer state (reference module state -> factory closure state) ---
277
+ var viewerState = 'waiting'; // 'waiting' | 'streaming' minimal gate
278
+ var publicState = 'connecting'; // 'connecting' | 'live' | 'stale' | 'disconnected'
279
+ var publicStateEvent = {
280
+ state: publicState,
281
+ reason: 'viewer-created',
282
+ ts: Date.now()
283
+ };
284
+ var stateListeners = new Set();
285
+ var healthListeners = new Set();
286
+ var disconnectTimer = null;
287
+ var active = { streamSessionId: '', snapshotId: 0 };
288
+ var lastScroll = { x: 0, y: 0 };
289
+ var counters = { staleMisses: 0, applyFailures: 0 };
290
+ // Sanitization strip counters -- PER-SESSION lifecycle (03-RESEARCH
291
+ // Pitfall 3, deliberate divergence from the per-snapshot miss counters
292
+ // above): misses measure per-generation drift and reset in
293
+ // handleSnapshot; these measure a sustained strip rate across the whole
294
+ // viewer session, so they reset ONLY in destroy(). Mutated in place by
295
+ // sanitizeFragment (post-parse scrub) and the diff applier via
296
+ // hooks.sanitizeCounters.
297
+ var sanitizeCounters = {
298
+ strippedHandlers: 0, blockedUrls: 0, droppedSubtrees: 0, cssScrubs: 0
299
+ };
300
+ var resyncPending = false; // latch: at most one resync in flight per generation
301
+ var receivedByType = {};
302
+ var sentByType = {};
303
+ var lastFrameAt = 0;
304
+ var lastSnapshotAt = 0;
305
+ var lastMutationAt = 0;
306
+ var lastTransportStatus = {};
307
+ var lastSnapshotPayload = null;
308
+ var scaleState = computeScale(1920, 1080, container.clientWidth, container.clientHeight);
309
+ var detached = false;
310
+ var destroyed = false;
311
+ var nidToNode = new Map();
312
+ var nodeToNid = new WeakMap();
313
+ var frameLoadHandlers = new WeakMap();
314
+ var nodeHighlightEl = null;
315
+ var pendingSubtreeRequests = new Map();
316
+ var nextSubtreeRequestId = 1;
317
+
318
+ function incrementCounter(counter, type) {
319
+ var key = typeof type === 'string' && type ? type : 'unknown';
320
+ counter[key] = (counter[key] || 0) + 1;
321
+ }
322
+
323
+ function copyCounters(counter) {
324
+ var out = {};
325
+ for (var key in counter) {
326
+ if (Object.prototype.hasOwnProperty.call(counter, key)) out[key] = counter[key];
327
+ }
328
+ return out;
329
+ }
330
+
331
+ function copyErrors(errors) {
332
+ if (!Array.isArray(errors)) return [];
333
+ return errors.map(function (entry) {
334
+ var e = entry || {};
335
+ return {
336
+ code: typeof e.code === 'string' ? e.code : '',
337
+ reason: typeof e.reason === 'string' ? e.reason : '',
338
+ ts: typeof e.ts === 'number' ? e.ts : 0
339
+ };
340
+ });
341
+ }
342
+
343
+ function sanitizeTransportStatus(status) {
344
+ var s = status || {};
345
+ return {
346
+ state: typeof s.state === 'string' ? s.state : (typeof s.status === 'string' ? s.status : ''),
347
+ reason: typeof s.reason === 'string' ? s.reason : '',
348
+ readyState: typeof s.readyState === 'number' ? s.readyState : null,
349
+ bufferedAmount: typeof s.bufferedAmount === 'number' ? s.bufferedAmount : 0,
350
+ drops: typeof s.drops === 'number' ? s.drops : 0,
351
+ errors: copyErrors(s.errors),
352
+ lastCloseAt: typeof s.lastCloseAt === 'number' ? s.lastCloseAt : 0,
353
+ lastSendAt: typeof s.lastSendAt === 'number' ? s.lastSendAt : 0,
354
+ lastReceiveAt: typeof s.lastReceiveAt === 'number' ? s.lastReceiveAt : 0,
355
+ closeCode: typeof s.closeCode === 'number' ? s.closeCode : null,
356
+ closeReason: typeof s.closeReason === 'string' ? s.closeReason : '',
357
+ sentByType: copyCounters(s.sentByType || {}),
358
+ receivedByType: copyCounters(s.receivedByType || {})
359
+ };
360
+ }
361
+
362
+ function currentTransportHealth() {
363
+ var live = {};
364
+ if (transport && typeof transport.getHealth === 'function') {
365
+ try {
366
+ live = sanitizeTransportStatus(transport.getHealth());
367
+ } catch (err) {
368
+ logger.error('[Renderer] transport health failed', err);
369
+ }
370
+ }
371
+ return Object.assign(sanitizeTransportStatus(lastTransportStatus), live);
372
+ }
373
+
374
+ function cloneStateEvent(event) {
375
+ return {
376
+ state: event.state,
377
+ reason: event.reason,
378
+ ts: event.ts
379
+ };
380
+ }
381
+
382
+ function healthSnapshot() {
383
+ return {
384
+ state: publicState,
385
+ ts: Date.now(),
386
+ lastFrameAt: lastFrameAt,
387
+ lastSnapshotAt: lastSnapshotAt,
388
+ lastMutationAt: lastMutationAt,
389
+ receivedByType: copyCounters(receivedByType),
390
+ sentByType: copyCounters(sentByType),
391
+ staleMisses: counters.staleMisses,
392
+ applyFailures: counters.applyFailures,
393
+ resyncPending: resyncPending,
394
+ sanitizer: copyCounters(sanitizeCounters),
395
+ transport: currentTransportHealth()
396
+ };
397
+ }
398
+
399
+ function notifyState() {
400
+ var event = cloneStateEvent(publicStateEvent);
401
+ stateListeners.forEach(function (handler) {
402
+ try {
403
+ handler(cloneStateEvent(event));
404
+ } catch (err) {
405
+ logger.error('[Renderer] event handler failed', 'state', err);
406
+ }
407
+ });
408
+ }
409
+
410
+ function notifyHealth() {
411
+ var event = healthSnapshot();
412
+ healthListeners.forEach(function (handler) {
413
+ try {
414
+ handler(healthSnapshot());
415
+ } catch (err) {
416
+ logger.error('[Renderer] event handler failed', 'health', err);
417
+ }
418
+ });
419
+ return event;
420
+ }
421
+
422
+ function clearDisconnectTimer() {
423
+ if (!disconnectTimer) return;
424
+ clearTimeout(disconnectTimer);
425
+ disconnectTimer = null;
426
+ }
427
+
428
+ function setPublicState(state, reason) {
429
+ if (state !== 'connecting' && state !== 'live' &&
430
+ state !== 'stale' && state !== 'disconnected') {
431
+ return;
432
+ }
433
+ if (state !== 'stale') clearDisconnectTimer();
434
+ if (publicState === state) return;
435
+ publicState = state;
436
+ publicStateEvent = {
437
+ state: state,
438
+ reason: reason || '',
439
+ ts: Date.now()
440
+ };
441
+ notifyState();
442
+ notifyHealth();
443
+ }
444
+
445
+ function scheduleDisconnected(reason) {
446
+ clearDisconnectTimer();
447
+ disconnectTimer = setTimeout(function () {
448
+ disconnectTimer = null;
449
+ if (detached || destroyed || publicState !== 'stale') return;
450
+ setPublicState('disconnected', reason || 'transport-closed');
451
+ }, disconnectDelayMs);
452
+ }
453
+
454
+ function on(eventName, handler) {
455
+ if ((eventName !== 'state' && eventName !== 'health') || typeof handler !== 'function') {
456
+ throw new Error('viewer-event-unsupported');
457
+ }
458
+ var listeners = eventName === 'state' ? stateListeners : healthListeners;
459
+ listeners.add(handler);
460
+ try {
461
+ handler(eventName === 'state' ? cloneStateEvent(publicStateEvent) : healthSnapshot());
462
+ } catch (err) {
463
+ logger.error('[Renderer] event handler failed', eventName, err);
464
+ }
465
+ return function unsubscribeViewerEvent() {
466
+ listeners.delete(handler);
467
+ };
468
+ }
469
+
470
+ /**
471
+ * Deliver one CONTROL message through the injected transport. Capture-
472
+ * precedent containment: synchronous try/catch plus a rejection handler
473
+ * on any returned promise; failures route to the logger, never throw.
474
+ * @param {string} type
475
+ * @param {Object} payload
476
+ */
477
+ function safeSend(type, payload) {
478
+ incrementCounter(sentByType, type);
479
+ notifyHealth();
480
+ try {
481
+ var result = transport.send(type, payload);
482
+ if (result && typeof result.catch === 'function') {
483
+ result.catch(function (err) {
484
+ logger.error('[Renderer] transport send failed', err);
485
+ });
486
+ }
487
+ } catch (err) {
488
+ logger.error('[Renderer] transport send failed', err);
489
+ }
490
+ }
491
+
492
+ /**
493
+ * Latched resync request (D-08 via 02-RESEARCH Pattern 2): the resync
494
+ * message IS CONTROL.START -- the capture host responds by starting a
495
+ * fresh session whose snapshot resets this generation's counters AND
496
+ * releases the latch (the only release site). Reference parity:
497
+ * requestPreviewResync, dashboard.js:248-278, with the FSB status
498
+ * refresh and recovery-watchdog chrome dropped.
499
+ * @param {string} reason Lowercase-hyphen reason from the diff applier
500
+ * @param {Object} [details] Miss details (logged upstream; not sent)
501
+ */
502
+ function requestResync(reason, details) {
503
+ if (resyncPending) return;
504
+ resyncPending = true;
505
+ setPublicState('stale', reason || 'preview-resync');
506
+ safeSend(CONTROL.START, {
507
+ trigger: 'preview-resync',
508
+ reason: reason || 'unknown'
509
+ });
510
+ }
511
+
512
+ function clearSubtreeLatch(payload) {
513
+ var p = payload || {};
514
+ if (p.nid === undefined || p.nid === null || p.requestId === undefined || p.requestId === null) {
515
+ return false;
516
+ }
517
+ var key = String(p.nid);
518
+ var requestId = String(p.requestId);
519
+ var pending = pendingSubtreeRequests.get(key);
520
+ if (!pending || pending.requestId !== requestId) return false;
521
+ pendingSubtreeRequests.delete(key);
522
+ return true;
523
+ }
524
+
525
+ function requestSubtree(nid, options) {
526
+ if (nid === undefined || nid === null) return null;
527
+ var key = String(nid);
528
+ if (!key) return null;
529
+ var target = resolveIndexedNode(key);
530
+ if (!target) return null;
531
+ if (pendingSubtreeRequests.has(key)) return null;
532
+
533
+ var opts = options || {};
534
+ var reason = typeof opts === 'string'
535
+ ? opts
536
+ : (opts.reason || 'truncated-region');
537
+ var requestId = 'subtree_' + Date.now().toString(36) + '_' + nextSubtreeRequestId++;
538
+ pendingSubtreeRequests.set(key, { requestId: requestId });
539
+ safeSend(CONTROL.SUBTREE_REQUEST, {
540
+ requestId: requestId,
541
+ nid: key,
542
+ streamSessionId: active.streamSessionId || '',
543
+ snapshotId: active.snapshotId || 0,
544
+ reason: reason || 'truncated-region'
545
+ });
546
+ return requestId;
547
+ }
548
+
549
+ function markLive(reason) {
550
+ setPublicState('live', reason || 'frame');
551
+ }
552
+
553
+ function handleTransportStatus(status) {
554
+ if (detached) return;
555
+ lastTransportStatus = sanitizeTransportStatus(status);
556
+ var before = publicState;
557
+ var s = status && (status.state || status.status);
558
+ if (s === 'closed') {
559
+ setPublicState('stale', 'transport-closed');
560
+ scheduleDisconnected('transport-closed');
561
+ } else if (s === 'reconnecting' || s === 'error') {
562
+ setPublicState('stale', 'transport-' + s);
563
+ } else if (s === 'open' || s === 'connected') {
564
+ if (viewerState === 'streaming' || lastSnapshotPayload) {
565
+ markLive('transport-open');
566
+ } else {
567
+ setPublicState('connecting', 'transport-open');
568
+ }
569
+ } else if (s === 'connecting') {
570
+ if (publicState !== 'live') setPublicState('connecting', 'transport-connecting');
571
+ }
572
+ if (before === publicState) notifyHealth();
573
+ }
574
+
575
+ function handleStreamState(payload) {
576
+ var p = payload || {};
577
+ var state = p.state || p.status;
578
+ if (state !== 'connecting' && state !== 'live' &&
579
+ state !== 'stale' && state !== 'disconnected') {
580
+ return;
581
+ }
582
+ setPublicState(state, p.reason || 'stream-state');
583
+ }
584
+
585
+ /**
586
+ * Recompute scale-to-fit from the container box and the last snapshot's
587
+ * page size (viewportWidth || pageWidth || 1920 and viewportHeight ||
588
+ * 1080, per dashboard.js:2834-2835), then apply the iframe geometry:
589
+ * unscaled page-size box, letterbox offsets, top-left scale transform.
590
+ */
591
+ function updateScale() {
592
+ var p = lastSnapshotPayload || {};
593
+ scaleState = computeScale(
594
+ p.viewportWidth || p.pageWidth || 1920,
595
+ p.viewportHeight || 1080,
596
+ container.clientWidth,
597
+ container.clientHeight
598
+ );
599
+ iframe.style.width = scaleState.pageW + 'px';
600
+ iframe.style.height = scaleState.pageH + 'px';
601
+ iframe.style.left = scaleState.offsetX + 'px';
602
+ iframe.style.top = scaleState.offsetY + 'px';
603
+ iframe.style.transform = 'scale(' + scaleState.s + ')';
604
+ }
605
+
606
+ function getViewportMapping() {
607
+ return {
608
+ scale: {
609
+ s: scaleState.s,
610
+ offsetX: scaleState.offsetX,
611
+ offsetY: scaleState.offsetY,
612
+ pageW: scaleState.pageW,
613
+ pageH: scaleState.pageH
614
+ },
615
+ viewport: {
616
+ width: scaleState.pageW,
617
+ height: scaleState.pageH
618
+ },
619
+ container: {
620
+ width: container.clientWidth || 0,
621
+ height: container.clientHeight || 0
622
+ }
623
+ };
624
+ }
625
+
626
+ function clearIdentityIndex() {
627
+ nidToNode.clear();
628
+ nodeToNid = new WeakMap();
629
+ }
630
+
631
+ function elementsInSubtree(root) {
632
+ var elements = [];
633
+ if (!root) return elements;
634
+ if (root.nodeType === 1) elements.push(root);
635
+ if (root.querySelectorAll) {
636
+ var descendants = root.querySelectorAll('*');
637
+ for (var i = 0; i < descendants.length; i++) elements.push(descendants[i]);
638
+ }
639
+ return elements;
640
+ }
641
+
642
+ function pairIdentityElements(elements, nodeIds, scope) {
643
+ var ids = Array.isArray(nodeIds) ? nodeIds : [];
644
+ if (elements.length !== ids.length) {
645
+ logger.warn('[Renderer] identity sidecar mismatch', {
646
+ scope: scope || '',
647
+ elements: elements.length,
648
+ nodeIds: ids.length
649
+ });
650
+ }
651
+ for (var i = 0; i < elements.length && i < ids.length; i++) {
652
+ if (ids[i] === undefined || ids[i] === null) continue;
653
+ var nid = String(ids[i]);
654
+ nidToNode.set(nid, elements[i]);
655
+ nodeToNid.set(elements[i], nid);
656
+ }
657
+ }
658
+
659
+ function resetIdentityIndex(targetDoc, nodeIds) {
660
+ clearIdentityIndex();
661
+ if (!targetDoc || !targetDoc.body) return;
662
+ pairIdentityElements(
663
+ Array.prototype.slice.call(targetDoc.body.querySelectorAll('*')),
664
+ nodeIds,
665
+ 'snapshot'
666
+ );
667
+ }
668
+
669
+ function resolveIndexedNode(nid) {
670
+ if (nid === undefined || nid === null) return null;
671
+ return nidToNode.get(String(nid)) || null;
672
+ }
673
+
674
+ function indexSubtree(root, nodeIds) {
675
+ pairIdentityElements(elementsInSubtree(root), nodeIds, 'add');
676
+ }
677
+
678
+ function removeIndexedSubtree(root) {
679
+ var elements = elementsInSubtree(root);
680
+ for (var i = 0; i < elements.length; i++) {
681
+ var nid = nodeToNid.get(elements[i]);
682
+ if (nid) nidToNode.delete(nid);
683
+ nodeToNid.delete(elements[i]);
684
+ }
685
+ }
686
+
687
+ function cssEscapeIdent(value) {
688
+ var input = String(value || '');
689
+ if (win && win.CSS && typeof win.CSS.escape === 'function') {
690
+ return win.CSS.escape(input);
691
+ }
692
+ return input.replace(/[^a-zA-Z0-9_-]/g, function (ch) {
693
+ return '\\' + ch.charCodeAt(0).toString(16) + ' ';
694
+ });
695
+ }
696
+
697
+ function hasDangerousStylesheetUrl(value) {
698
+ if (!value || typeof value !== 'string') return false;
699
+ var compact = value.replace(/[\u0000-\u0020]+/g, '').toLowerCase();
700
+ return compact.indexOf('javascript:') === 0
701
+ || compact.indexOf('vbscript:') === 0
702
+ || compact.indexOf('data:text/html') === 0;
703
+ }
704
+
705
+ function setScopedStyleText(styleEl, cssText) {
706
+ styleEl.textContent = scrubCssText(String(cssText || ''));
707
+ }
708
+
709
+ function findStyleSourceElement(rootNode, sourceId) {
710
+ if (!rootNode || !rootNode.querySelector) return null;
711
+ try {
712
+ return rootNode.querySelector('[data-ps-style-source-id="' + cssEscapeIdent(sourceId) + '"]');
713
+ } catch (err) {
714
+ var nodes = rootNode.querySelectorAll ? rootNode.querySelectorAll('[data-ps-style-source-id]') : [];
715
+ for (var i = 0; i < nodes.length; i++) {
716
+ if (nodes[i].getAttribute('data-ps-style-source-id') === String(sourceId || '')) return nodes[i];
717
+ }
718
+ return null;
719
+ }
720
+ }
721
+
722
+ function installOneStyleSource(targetDoc, rootNode, source) {
723
+ var s = source || {};
724
+ if (!targetDoc || !rootNode || !s.sourceId) return false;
725
+ var existing = findStyleSourceElement(rootNode, s.sourceId);
726
+ if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
727
+ var el = null;
728
+ if (s.href && !hasDangerousStylesheetUrl(s.href)) {
729
+ el = targetDoc.createElement('link');
730
+ el.setAttribute('rel', 'stylesheet');
731
+ el.setAttribute('href', String(s.href || ''));
732
+ } else {
733
+ el = targetDoc.createElement('style');
734
+ setScopedStyleText(el, s.cssText || '');
735
+ }
736
+ el.setAttribute('data-ps-style-source-id', String(s.sourceId));
737
+ if (s.media) el.setAttribute('media', String(s.media));
738
+ if (s.disabled) el.setAttribute('data-ps-style-disabled', 'true');
739
+ rootNode.appendChild(el);
740
+ return true;
741
+ }
742
+
743
+ function installStyleSources(targetDoc, styleSources, scopeContext) {
744
+ var sources = Array.isArray(styleSources) ? styleSources.slice() : [];
745
+ if (!targetDoc) return false;
746
+ var scope = scopeContext || { kind: 'document' };
747
+ var rootNode = null;
748
+ if (scope.kind === 'document') {
749
+ rootNode = targetDoc.head || targetDoc.documentElement;
750
+ } else if (scope.kind === 'shadow') {
751
+ var host = resolveIndexedNode(scope.hostNid);
752
+ rootNode = host && host.shadowRoot ? host.shadowRoot : null;
753
+ } else if (scope.kind === 'frame') {
754
+ rootNode = targetDoc.head || targetDoc.documentElement;
755
+ }
756
+ if (!rootNode) {
757
+ logger.warn('[Renderer] style source scope missing', {
758
+ scopeKind: scope.kind || '',
759
+ reason: 'stale-style-scope'
760
+ });
761
+ return false;
762
+ }
763
+ sources.sort(function (a, b) {
764
+ return (a && typeof a.order === 'number' ? a.order : 0)
765
+ - (b && typeof b.order === 'number' ? b.order : 0);
766
+ });
767
+ for (var i = 0; i < sources.length; i++) {
768
+ var source = sources[i] || {};
769
+ var sourceScope = source.scope || {};
770
+ if (sourceScope.kind !== scope.kind) continue;
771
+ if (scope.kind === 'shadow' && String(sourceScope.hostNid || '') !== String(scope.hostNid || '')) continue;
772
+ if (scope.kind === 'frame' && String(sourceScope.frameNid || '') !== String(scope.frameNid || '')) continue;
773
+ installOneStyleSource(targetDoc, rootNode, source);
774
+ }
775
+ return true;
776
+ }
777
+
778
+ function rootForStyleScope(targetDoc, scope) {
779
+ var s = scope || {};
780
+ if (!targetDoc) return null;
781
+ if (s.kind === 'document') return { doc: targetDoc, root: targetDoc.head || targetDoc.documentElement };
782
+ if (s.kind === 'shadow') {
783
+ var host = resolveIndexedNode(s.hostNid);
784
+ if (!host || !host.shadowRoot) return null;
785
+ return { doc: targetDoc, root: host.shadowRoot };
786
+ }
787
+ if (s.kind === 'frame') {
788
+ var frameEl = resolveIndexedNode(s.frameNid);
789
+ var frameDoc = null;
790
+ try {
791
+ frameDoc = frameEl && frameEl.contentDocument;
792
+ } catch (err) {
793
+ frameDoc = null;
794
+ }
795
+ if (!frameDoc || !frameDoc.head) return null;
796
+ return { doc: frameDoc, root: frameDoc.head };
797
+ }
798
+ return null;
799
+ }
800
+
801
+ function applyStyleSource(action, sourceId, scope, source) {
802
+ var targetDoc = iframe.contentDocument;
803
+ var resolved = rootForStyleScope(targetDoc, scope);
804
+ if (!resolved || !resolved.root) {
805
+ logger.warn('[Renderer] style source scope missing', {
806
+ sourceId: sourceId || '',
807
+ scopeKind: scope && scope.kind ? scope.kind : '',
808
+ reason: 'stale-style-scope'
809
+ });
810
+ return false;
811
+ }
812
+ var existing = findStyleSourceElement(resolved.root, sourceId);
813
+ if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
814
+ return installOneStyleSource(resolved.doc, resolved.root, source || {});
815
+ }
816
+
817
+ function removeStyleSource(sourceId, scope) {
818
+ var targetDoc = iframe.contentDocument;
819
+ var resolved = rootForStyleScope(targetDoc, scope);
820
+ if (!resolved || !resolved.root) {
821
+ logger.warn('[Renderer] style source scope missing', {
822
+ sourceId: sourceId || '',
823
+ scopeKind: scope && scope.kind ? scope.kind : '',
824
+ reason: 'stale-style-scope'
825
+ });
826
+ return false;
827
+ }
828
+ var existing = findStyleSourceElement(resolved.root, sourceId);
829
+ if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
830
+ return true;
831
+ }
832
+
833
+ function installOneShadowRoot(targetDoc, payload) {
834
+ var p = payload || {};
835
+ if (!targetDoc || !p.hostNid) return false;
836
+ if (p.mode && p.mode !== 'open') return false;
837
+ var host = resolveIndexedNode(p.hostNid);
838
+ if (!host) {
839
+ logger.warn('[Renderer] shadow root host missing', { hostNid: p.hostNid || '' });
840
+ return false;
841
+ }
842
+ var shadowRoot = host.shadowRoot || null;
843
+ if (!shadowRoot) {
844
+ if (typeof host.attachShadow !== 'function') {
845
+ logger.warn('[Renderer] shadow root unsupported', { hostNid: p.hostNid || '' });
846
+ return false;
847
+ }
848
+ try {
849
+ shadowRoot = host.attachShadow({ mode: 'open' });
850
+ } catch (err) {
851
+ logger.warn('[Renderer] shadow root attach failed', {
852
+ hostNid: p.hostNid || '',
853
+ error: err && err.message ? err.message : String(err)
854
+ });
855
+ return false;
856
+ }
857
+ }
858
+
859
+ removeIndexedSubtree(shadowRoot);
860
+ while (shadowRoot.firstChild) shadowRoot.removeChild(shadowRoot.firstChild);
861
+
862
+ var tpl = targetDoc.createElement('template');
863
+ tpl.innerHTML = p.html || '';
864
+ sanitizeFragment(tpl.content, sanitizeCounters, logger);
865
+ shadowRoot.appendChild(targetDoc.importNode(tpl.content, true));
866
+ installStyleSources(targetDoc, p.styleSources || [], { kind: 'shadow', hostNid: p.hostNid });
867
+ pairIdentityElements(
868
+ Array.prototype.slice.call(shadowRoot.querySelectorAll('*')),
869
+ p.nodeIds || [],
870
+ 'shadow'
871
+ );
872
+ return true;
873
+ }
874
+
875
+ function installShadowRoots(targetDoc, shadowRoots) {
876
+ if (!Array.isArray(shadowRoots)) return;
877
+ for (var i = 0; i < shadowRoots.length; i++) {
878
+ installOneShadowRoot(targetDoc, shadowRoots[i]);
879
+ }
880
+ }
881
+
882
+ function setFrameLoadHandler(frameEl, handler) {
883
+ if (!frameEl || typeof frameEl.addEventListener !== 'function') return;
884
+ var existing = frameLoadHandlers.get(frameEl);
885
+ if (existing && typeof frameEl.removeEventListener === 'function') {
886
+ frameEl.removeEventListener('load', existing);
887
+ }
888
+ frameEl.addEventListener('load', handler);
889
+ frameLoadHandlers.set(frameEl, handler);
890
+ }
891
+
892
+ function indexFrameDocument(frameEl, framePayload) {
893
+ var p = framePayload || {};
894
+ try {
895
+ var frameDoc = frameEl && frameEl.contentDocument;
896
+ if (!frameDoc || !frameDoc.documentElement || !frameDoc.body) return false;
897
+ removeIndexedSubtree(frameDoc.documentElement);
898
+ sanitizeFragment(frameDoc.body, sanitizeCounters, logger);
899
+ if (p.htmlNid) {
900
+ nidToNode.set(String(p.htmlNid), frameDoc.documentElement);
901
+ nodeToNid.set(frameDoc.documentElement, String(p.htmlNid));
902
+ }
903
+ if (p.bodyNid) {
904
+ nidToNode.set(String(p.bodyNid), frameDoc.body);
905
+ nodeToNid.set(frameDoc.body, String(p.bodyNid));
906
+ }
907
+ installStyleSources(frameDoc, p.styleSources || [], { kind: 'frame', frameNid: p.frameNid });
908
+ pairIdentityElements(
909
+ Array.prototype.slice.call(frameDoc.body.querySelectorAll('*')),
910
+ p.nodeIds || [],
911
+ 'frame'
912
+ );
913
+ installShadowRoots(frameDoc, p.shadowRoots || []);
914
+ installFrames(frameDoc, p.frames || []);
915
+ return true;
916
+ } catch (err) {
917
+ logger.warn('[Renderer] frame document index failed', {
918
+ frameNid: p.frameNid || ''
919
+ });
920
+ return false;
921
+ }
922
+ }
923
+
924
+ function installOneFrame(targetDoc, framePayload) {
925
+ var p = framePayload || {};
926
+ if (!targetDoc || !p.frameNid) return false;
927
+ var frameEl = resolveIndexedNode(p.frameNid);
928
+ if (!frameEl) {
929
+ logger.warn('[Renderer] frame host missing', { frameNid: p.frameNid || '' });
930
+ return false;
931
+ }
932
+ if (!frameEl.tagName || String(frameEl.tagName).toLowerCase() !== 'iframe') {
933
+ logger.warn('[Renderer] frame host is not iframe', { frameNid: p.frameNid || '' });
934
+ return false;
935
+ }
936
+
937
+ frameEl.removeAttribute('src');
938
+ frameEl.setAttribute('sandbox', 'allow-same-origin');
939
+
940
+ if (p.kind === 'same-origin') {
941
+ setFrameLoadHandler(frameEl, function() {
942
+ indexFrameDocument(frameEl, p);
943
+ });
944
+ frameEl.setAttribute('srcdoc', buildSnapshotHtml(p));
945
+ indexFrameDocument(frameEl, p);
946
+ return true;
947
+ }
948
+
949
+ if (p.kind === 'cross-origin') {
950
+ setFrameLoadHandler(frameEl, function() {
951
+ try {
952
+ var placeholderDoc = frameEl.contentDocument;
953
+ if (placeholderDoc && placeholderDoc.body) {
954
+ sanitizeFragment(placeholderDoc.body, sanitizeCounters, logger);
955
+ }
956
+ } catch (err) {
957
+ logger.warn('[Renderer] frame placeholder sanitize failed', {
958
+ frameNid: p.frameNid || ''
959
+ });
960
+ }
961
+ });
962
+ frameEl.setAttribute('srcdoc', buildFramePlaceholderHtml(p));
963
+ return true;
964
+ }
965
+
966
+ logger.warn('[Renderer] frame kind unsupported', {
967
+ frameNid: p.frameNid || '',
968
+ kind: p.kind || ''
969
+ });
970
+ return false;
971
+ }
972
+
973
+ function installFrames(targetDoc, frames) {
974
+ if (!Array.isArray(frames)) return;
975
+ for (var i = 0; i < frames.length; i++) {
976
+ installOneFrame(targetDoc, frames[i]);
977
+ }
978
+ }
979
+
980
+ function hostRectForElement(el) {
981
+ var rect = el.getBoundingClientRect();
982
+ return mapRectToHost(
983
+ { x: rect.left, y: rect.top, w: rect.width, h: rect.height },
984
+ scaleState
985
+ );
986
+ }
987
+
988
+ /**
989
+ * Resolve a captured node id to a host-document overlay rect. Reads the
990
+ * mirror contentDocument FRESH per call (never cached -- re-snapshots
991
+ * replace the document). Client rects inside the iframe are already
992
+ * viewport-relative and unaffected by the host-side CSS transform
993
+ * (02-RESEARCH Pattern 5), so mapRectToHost applies scale + offsets.
994
+ * @param {number|string} nid
995
+ * @returns {?{top: number, left: number, width: number, height: number}}
996
+ */
997
+ function resolveNidRect(nid) {
998
+ try {
999
+ var el = resolveIndexedNode(nid);
1000
+ if (!el) return null;
1001
+ return hostRectForElement(el);
1002
+ } catch (err) {
1003
+ // Containment: a malformed nid (selector syntax) or a torn-down
1004
+ // mirror must never break the overlay kind loop.
1005
+ logger.warn('[Renderer] nid rect resolution failed', nid, err);
1006
+ return null;
1007
+ }
1008
+ }
1009
+
1010
+ function resolveNode(nid) {
1011
+ if (nid === undefined || nid === null) return null;
1012
+ var key = String(nid);
1013
+ try {
1014
+ var el = resolveIndexedNode(key);
1015
+ if (!el) return null;
1016
+ var rect = hostRectForElement(el);
1017
+ return {
1018
+ nid: key,
1019
+ exists: true,
1020
+ rect: {
1021
+ top: rect.top,
1022
+ left: rect.left,
1023
+ width: rect.width,
1024
+ height: rect.height
1025
+ },
1026
+ streamSessionId: active.streamSessionId || '',
1027
+ snapshotId: active.snapshotId || 0
1028
+ };
1029
+ } catch (err) {
1030
+ logger.warn('[Renderer] node resolution failed', key, err);
1031
+ return null;
1032
+ }
1033
+ }
1034
+
1035
+ function ensureNodeHighlight() {
1036
+ if (nodeHighlightEl && nodeHighlightEl.parentNode === overlays.layer) {
1037
+ return nodeHighlightEl;
1038
+ }
1039
+ nodeHighlightEl = doc.createElement('div');
1040
+ nodeHighlightEl.className = 'ps-node-highlight';
1041
+ nodeHighlightEl.setAttribute('aria-hidden', 'true');
1042
+ nodeHighlightEl.style.zIndex = '15';
1043
+ nodeHighlightEl.style.display = 'none';
1044
+ overlays.layer.appendChild(nodeHighlightEl);
1045
+ return nodeHighlightEl;
1046
+ }
1047
+
1048
+ function clearHighlight() {
1049
+ if (!nodeHighlightEl) return;
1050
+ nodeHighlightEl.hidden = true;
1051
+ nodeHighlightEl.style.display = 'none';
1052
+ nodeHighlightEl.textContent = '';
1053
+ }
1054
+
1055
+ function highlightNode(nid, options) {
1056
+ var resolved = resolveNode(nid);
1057
+ if (!resolved) return false;
1058
+ var el = ensureNodeHighlight();
1059
+ var rect = resolved.rect;
1060
+ el.hidden = false;
1061
+ el.style.top = rect.top + 'px';
1062
+ el.style.left = rect.left + 'px';
1063
+ el.style.width = rect.width + 'px';
1064
+ el.style.height = rect.height + 'px';
1065
+ el.style.display = 'block';
1066
+ el.textContent = '';
1067
+ var opts = options || {};
1068
+ if (opts.label !== undefined && opts.label !== null && String(opts.label) !== '') {
1069
+ var label = doc.createElement('div');
1070
+ label.className = 'ps-node-highlight-label';
1071
+ label.textContent = String(opts.label);
1072
+ el.appendChild(label);
1073
+ }
1074
+ return true;
1075
+ }
1076
+
1077
+ /**
1078
+ * STREAM.SNAPSHOT handler (dashboard.js:2723-2829). Snapshots are NEVER
1079
+ * staleness-checked -- they DEFINE the new identity (2742-2756). Missing
1080
+ * html keeps the last good frame (no state change; logger only -- the
1081
+ * reference's error-state UI is FSB chrome). Sequence: adopt identity ->
1082
+ * reset generation state (counters + latch, 200-204) -> reset overlays
1083
+ * (2762-2764) -> store scroll (2758-2759) -> write srcdoc; the creation-
1084
+ * time load listener (above) then runs scale, initial scrollTo, marks
1085
+ * streaming, and un-hides the iframe.
1086
+ * @param {Object} payload
1087
+ */
1088
+ function handleSnapshot(payload) {
1089
+ var p = payload || {};
1090
+ if (typeof p.html !== 'string') {
1091
+ logger.error('[Renderer] snapshot missing html');
1092
+ return;
1093
+ }
1094
+ active.streamSessionId = p.streamSessionId || '';
1095
+ active.snapshotId = p.snapshotId || 0;
1096
+ counters.staleMisses = 0;
1097
+ counters.applyFailures = 0;
1098
+ resyncPending = false; // the latch's ONLY release site
1099
+ pendingSubtreeRequests.clear();
1100
+ lastSnapshotAt = Date.now();
1101
+ overlays.resetOverlays();
1102
+ clearHighlight();
1103
+ lastScroll.x = p.scrollX || 0;
1104
+ lastScroll.y = p.scrollY || 0;
1105
+ lastSnapshotPayload = p;
1106
+ clearIdentityIndex();
1107
+ iframe.srcdoc = buildSnapshotHtml(p);
1108
+ markLive('snapshot');
1109
+ }
1110
+
1111
+ /**
1112
+ * STREAM.MUTATIONS handler (dashboard.js:3209-3356). Gated on streaming
1113
+ * (mutations before the first load are dropped -- Pitfall 4 parity; the
1114
+ * resync path self-heals any resulting drift) AND stream identity. The
1115
+ * contentDocument is read FRESH per call (never cached); the last known
1116
+ * scroll is re-applied exactly ONCE per batch (3340-3342), never per op.
1117
+ * @param {Object} payload
1118
+ */
1119
+ function handleMutations(payload) {
1120
+ if (viewerState !== 'streaming') return;
1121
+ if (!isCurrentStream(payload, active)) return;
1122
+ lastMutationAt = Date.now();
1123
+ var cd = iframe.contentDocument;
1124
+ applyMutations(cd, payload.mutations, counters, {
1125
+ logger: logger,
1126
+ requestResync: requestResync,
1127
+ sanitizeCounters: sanitizeCounters,
1128
+ identity: {
1129
+ resolve: resolveIndexedNode,
1130
+ indexSubtree: indexSubtree,
1131
+ removeSubtree: removeIndexedSubtree,
1132
+ installShadowRoot: function(hostNid, payload) {
1133
+ var opPayload = Object.assign({}, payload || {}, { hostNid: hostNid });
1134
+ installOneShadowRoot(cd, opPayload);
1135
+ },
1136
+ installFrames: function(frames) {
1137
+ installFrames(cd, frames || []);
1138
+ },
1139
+ applyStyleSource: applyStyleSource,
1140
+ removeStyleSource: removeStyleSource
1141
+ }
1142
+ });
1143
+ if (!resyncPending) markLive('mutations');
1144
+ try {
1145
+ iframe.contentWindow.scrollTo(lastScroll.x, lastScroll.y);
1146
+ } catch (e) { /* ignore: scroll maintenance is best-effort */ }
1147
+ }
1148
+
1149
+ function handleSubtreeResponse(payload) {
1150
+ var p = payload || {};
1151
+ if (!isCurrentStream(p, active)) {
1152
+ clearSubtreeLatch(p);
1153
+ return;
1154
+ }
1155
+ if (!clearSubtreeLatch(p)) return;
1156
+ if (p.status !== 'ok') return;
1157
+
1158
+ var target = resolveIndexedNode(p.nid);
1159
+ if (!target || !target.parentNode || typeof target.getAttribute !== 'function') return;
1160
+ if (target.getAttribute('data-phantomstream-truncated') !== 'true') return;
1161
+ var targetDoc = target.ownerDocument || iframe.contentDocument;
1162
+ if (!targetDoc || !targetDoc.createElement) return;
1163
+
1164
+ var tpl = targetDoc.createElement('template');
1165
+ tpl.innerHTML = p.html || '';
1166
+ sanitizeFragment(tpl.content, sanitizeCounters, logger);
1167
+ var newNode = tpl.content.firstElementChild;
1168
+ if (!newNode) {
1169
+ logger.warn('[Renderer] subtree response dropped: html parsed to no element', {
1170
+ nid: p.nid || ''
1171
+ });
1172
+ return;
1173
+ }
1174
+ var imported = targetDoc.importNode(newNode, true);
1175
+ removeIndexedSubtree(target);
1176
+ target.parentNode.replaceChild(imported, target);
1177
+ indexSubtree(imported, p.nodeIds || []);
1178
+ installShadowRoots(targetDoc, p.shadowRoots || []);
1179
+ installFrames(targetDoc, p.frames || []);
1180
+ lastMutationAt = Date.now();
1181
+ markLive('subtree');
1182
+ }
1183
+
1184
+ /**
1185
+ * STREAM.SCROLL handler (dashboard.js:3358-3372). Store FIRST so the
1186
+ * post-mutation re-apply always uses the freshest captured position,
1187
+ * then follow with a smooth scroll only while streaming (read-only
1188
+ * follow this phase, D-14/D-15).
1189
+ * @param {Object} payload
1190
+ */
1191
+ function handleScroll(payload) {
1192
+ if (!isCurrentStream(payload, active)) return;
1193
+ lastScroll.x = (payload && payload.scrollX) || 0;
1194
+ lastScroll.y = (payload && payload.scrollY) || 0;
1195
+ if (viewerState !== 'streaming') return;
1196
+ markLive('scroll');
1197
+ try {
1198
+ iframe.contentWindow.scrollTo({
1199
+ left: lastScroll.x,
1200
+ top: lastScroll.y,
1201
+ behavior: 'smooth'
1202
+ });
1203
+ } catch (e) { /* ignore: smooth follow is best-effort */ }
1204
+ }
1205
+
1206
+ /**
1207
+ * STREAM.OVERLAY handler: streaming + identity gate, then registry
1208
+ * dispatch with the current scale state and the nid rect resolver.
1209
+ * @param {Object} payload
1210
+ */
1211
+ function handleOverlay(payload) {
1212
+ if (viewerState !== 'streaming') return;
1213
+ if (!isCurrentStream(payload, active)) return;
1214
+ overlays.handleOverlayMessage(payload, {
1215
+ scale: scaleState,
1216
+ resolveNidRect: resolveNidRect
1217
+ });
1218
+ markLive('overlay');
1219
+ }
1220
+
1221
+ /**
1222
+ * STREAM.DIALOG handler: streaming gate + TOP-LEVEL identity check only.
1223
+ * Capture nests stream identity inside payload.dialog, so this check
1224
+ * finds no top-level identity and effectively always accepts -- the
1225
+ * ported reference quirk (Pitfall 8), kept deliberately and ledgered in
1226
+ * plan 02-04. Loopback has a single stream; revisit at Phase 4.
1227
+ * @param {Object} payload
1228
+ */
1229
+ function handleDialog(payload) {
1230
+ if (viewerState !== 'streaming') return;
1231
+ if (!isCurrentStream(payload, active)) return;
1232
+ overlays.handleDialogMessage(payload);
1233
+ markLive('dialog');
1234
+ }
1235
+
1236
+ /**
1237
+ * Transport message dispatch. The whole handler is containment-wrapped:
1238
+ * one malformed message routes to the logger and never kills the
1239
+ * subscription. Unknown types (STREAM.READY, STREAM.STATE, ...) are
1240
+ * ignored silently (forward-compatible).
1241
+ * @param {string} type
1242
+ * @param {Object} payload
1243
+ */
1244
+ function dispatch(type, payload) {
1245
+ if (detached) return;
1246
+ incrementCounter(receivedByType, type);
1247
+ lastFrameAt = Date.now();
1248
+ try {
1249
+ switch (type) {
1250
+ case STREAM.SNAPSHOT:
1251
+ handleSnapshot(payload);
1252
+ break;
1253
+ case STREAM.MUTATIONS:
1254
+ handleMutations(payload);
1255
+ break;
1256
+ case STREAM.SUBTREE_RESPONSE:
1257
+ handleSubtreeResponse(payload);
1258
+ break;
1259
+ case STREAM.SCROLL:
1260
+ handleScroll(payload);
1261
+ break;
1262
+ case STREAM.OVERLAY:
1263
+ handleOverlay(payload);
1264
+ break;
1265
+ case STREAM.DIALOG:
1266
+ handleDialog(payload);
1267
+ break;
1268
+ case STREAM.STATE:
1269
+ handleStreamState(payload);
1270
+ break;
1271
+ default:
1272
+ break;
1273
+ }
1274
+ } catch (err) {
1275
+ logger.error('[Renderer] message handler failed', type, err);
1276
+ }
1277
+ notifyHealth();
1278
+ }
1279
+
1280
+ var unsubscribe = transport.onMessage(dispatch);
1281
+ var unsubscribeStatus = null;
1282
+ if (typeof transport.onStatus === 'function') {
1283
+ unsubscribeStatus = transport.onStatus(handleTransportStatus);
1284
+ }
1285
+
1286
+ // --- Resize wiring (dashboard.js:3194-3207): window resize listener
1287
+ // plus a typeof-guarded ResizeObserver on the container (jsdom lacks
1288
+ // ResizeObserver -- Pitfall 5; the reference keeps both). Both gated on
1289
+ // streaming so the waiting placeholder never triggers geometry writes. ---
1290
+ function onWindowResize() {
1291
+ if (viewerState === 'streaming') updateScale();
1292
+ }
1293
+ if (win && typeof win.addEventListener === 'function') {
1294
+ win.addEventListener('resize', onWindowResize);
1295
+ }
1296
+ var resizeObserver = null;
1297
+ if (typeof ResizeObserver !== 'undefined') {
1298
+ resizeObserver = new ResizeObserver(function () {
1299
+ if (viewerState === 'streaming') updateScale();
1300
+ });
1301
+ resizeObserver.observe(container);
1302
+ }
1303
+
1304
+ /**
1305
+ * Unsubscribe from the transport, remove resize listeners, disconnect
1306
+ * the ResizeObserver, and remove the viewer root from the container.
1307
+ * Idempotent (02-RESEARCH Open Question 3 recommendation).
1308
+ */
1309
+ function detach() {
1310
+ if (detached) return;
1311
+ detached = true;
1312
+ try {
1313
+ if (typeof unsubscribe === 'function') unsubscribe();
1314
+ } catch (err) {
1315
+ logger.error('[Renderer] transport unsubscribe failed', err);
1316
+ }
1317
+ try {
1318
+ if (typeof unsubscribeStatus === 'function') unsubscribeStatus();
1319
+ } catch (err) {
1320
+ logger.error('[Renderer] transport status unsubscribe failed', err);
1321
+ }
1322
+ clearDisconnectTimer();
1323
+ if (win && typeof win.removeEventListener === 'function') {
1324
+ win.removeEventListener('resize', onWindowResize);
1325
+ }
1326
+ if (resizeObserver) {
1327
+ try {
1328
+ resizeObserver.disconnect();
1329
+ } catch (err) { /* observer already torn down */ }
1330
+ resizeObserver = null;
1331
+ }
1332
+ if (root.parentNode) root.parentNode.removeChild(root);
1333
+ }
1334
+
1335
+ /**
1336
+ * detach() plus state/overlay reset. Idempotent; safe after detach().
1337
+ */
1338
+ function destroy() {
1339
+ detach();
1340
+ if (destroyed) return;
1341
+ destroyed = true;
1342
+ overlays.resetOverlays();
1343
+ clearHighlight();
1344
+ nodeHighlightEl = null;
1345
+ clearIdentityIndex();
1346
+ frameLoadHandlers = new WeakMap();
1347
+ lastSnapshotPayload = null;
1348
+ active.streamSessionId = '';
1349
+ active.snapshotId = 0;
1350
+ counters.staleMisses = 0;
1351
+ counters.applyFailures = 0;
1352
+ // The ONLY sanitize-counter reset site (per-session lifecycle --
1353
+ // see the declaration comment; handleSnapshot never resets these).
1354
+ sanitizeCounters.strippedHandlers = 0;
1355
+ sanitizeCounters.blockedUrls = 0;
1356
+ sanitizeCounters.droppedSubtrees = 0;
1357
+ sanitizeCounters.cssScrubs = 0;
1358
+ resyncPending = false;
1359
+ pendingSubtreeRequests.clear();
1360
+ receivedByType = {};
1361
+ sentByType = {};
1362
+ lastFrameAt = 0;
1363
+ lastSnapshotAt = 0;
1364
+ lastMutationAt = 0;
1365
+ lastTransportStatus = {};
1366
+ stateListeners.clear();
1367
+ healthListeners.clear();
1368
+ viewerState = 'waiting';
1369
+ }
1370
+
1371
+ /**
1372
+ * Register a custom overlay kind (delegates to the overlays registry --
1373
+ * the host-facing extension seam, D-10). Viewer state/health events live
1374
+ * on on(); semantic node addressing lives on resolveNode/highlightNode.
1375
+ * See overlays.register() for the
1376
+ * renderFn contract (raw payload, host rect or null, layer element).
1377
+ * @param {string} kind
1378
+ * @param {(payload: *, anchorRect: ?Object, layer: Element) => void} renderFn
1379
+ */
1380
+ function registerOverlay(kind, renderFn) {
1381
+ overlays.register(kind, renderFn);
1382
+ }
1383
+
1384
+ return {
1385
+ detach: detach,
1386
+ destroy: destroy,
1387
+ clearHighlight: clearHighlight,
1388
+ getViewportMapping: getViewportMapping,
1389
+ highlightNode: highlightNode,
1390
+ on: on,
1391
+ registerOverlay: registerOverlay,
1392
+ requestSubtree: requestSubtree,
1393
+ resolveNode: resolveNode
1394
+ };
1395
+ }
1396
+
1397
+ // Barrel re-exports: the renderer's full public surface through one module
1398
+ // (package exports map "./renderer" -> this file in plan 02-05).
1399
+ export { escapeAttribute, buildShellAttributeString, buildSnapshotHtml, buildFramePlaceholderHtml } from './snapshot.js';
1400
+ export { applyMutations } from './diff.js';
1401
+ export { createOverlays, mapRectToHost, mapHostPointToViewport, OVERLAY_CSS } from './overlays.js';