@full-self-browsing/phantom-stream 0.1.0 → 0.2.1

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 (46) hide show
  1. package/dist/types/adapters/extension.d.ts.map +1 -1
  2. package/dist/types/adapters/playwright.d.ts.map +1 -1
  3. package/dist/types/capture/index.d.ts +112 -0
  4. package/dist/types/capture/index.d.ts.map +1 -1
  5. package/dist/types/protocol/constants.d.ts +22 -0
  6. package/dist/types/protocol/constants.d.ts.map +1 -1
  7. package/dist/types/protocol/index.d.ts +1 -0
  8. package/dist/types/protocol/media-reconcile.d.ts +53 -0
  9. package/dist/types/protocol/media-reconcile.d.ts.map +1 -0
  10. package/dist/types/protocol/messages.d.ts +266 -2
  11. package/dist/types/protocol/messages.d.ts.map +1 -1
  12. package/dist/types/renderer/asset-policy.d.ts +72 -0
  13. package/dist/types/renderer/asset-policy.d.ts.map +1 -0
  14. package/dist/types/renderer/diff.d.ts.map +1 -1
  15. package/dist/types/renderer/index.d.ts +13 -0
  16. package/dist/types/renderer/index.d.ts.map +1 -1
  17. package/dist/types/renderer/media-player.d.ts +114 -0
  18. package/dist/types/renderer/media-player.d.ts.map +1 -0
  19. package/dist/types/renderer/overlays.d.ts +12 -0
  20. package/dist/types/renderer/overlays.d.ts.map +1 -1
  21. package/dist/types/renderer/sanitize.d.ts +22 -0
  22. package/dist/types/renderer/sanitize.d.ts.map +1 -1
  23. package/dist/types/renderer/snapshot.d.ts +38 -0
  24. package/dist/types/renderer/snapshot.d.ts.map +1 -1
  25. package/dist/types/transport/websocket.d.ts.map +1 -1
  26. package/docs/ARCHITECTURE.md +13 -4
  27. package/docs/SECURITY.md +233 -2
  28. package/examples/bookmarklet-demo/viewer.html +12 -3
  29. package/examples/extension-mv3/viewer.html +10 -3
  30. package/package.json +9 -1
  31. package/src/adapters/extension.js +202 -7
  32. package/src/adapters/playwright-inject.js +50 -0
  33. package/src/adapters/playwright.js +159 -0
  34. package/src/capture/index.js +1071 -11
  35. package/src/protocol/constants.js +24 -0
  36. package/src/protocol/index.js +1 -0
  37. package/src/protocol/media-reconcile.js +188 -0
  38. package/src/protocol/messages.js +145 -2
  39. package/src/renderer/asset-policy.js +172 -0
  40. package/src/renderer/diff.js +106 -2
  41. package/src/renderer/index.js +849 -9
  42. package/src/renderer/media-player.js +367 -0
  43. package/src/renderer/overlays.js +324 -0
  44. package/src/renderer/sanitize.js +25 -3
  45. package/src/renderer/snapshot.js +534 -3
  46. package/src/transport/websocket.js +36 -0
@@ -34,11 +34,141 @@
34
34
  // || inline defaulting, function expressions, named exports, explicit .js
35
35
  // import extensions, factory-time validation as the ONLY throwing site.
36
36
 
37
- import { buildSnapshotHtml, buildFramePlaceholderHtml } from './snapshot.js';
37
+ import { buildSnapshotHtml, buildFramePlaceholderHtml, gateSnapshotAssets } from './snapshot.js';
38
38
  import { applyMutations } from './diff.js';
39
- import { sanitizeFragment, scrubCssText } from './sanitize.js';
39
+ import { sanitizeFragment, scrubCssText, parseSrcsetCandidates } from './sanitize.js';
40
40
  import { createOverlays, mapRectToHost, OVERLAY_CSS } from './overlays.js';
41
+ import { classifyAssetOrigin } from './asset-policy.js';
42
+ import { createMediaPlayer } from './media-player.js';
41
43
  import { STREAM, CONTROL, isCurrentStream } from '../protocol/messages.js';
44
+ import { reconcileMediaDrift, DEFAULT_MEDIA_RECONCILE_CONFIG } from '../protocol/media-reconcile.js';
45
+
46
+ // ---- Phase 12 (MSEC-01/MSEC-02): the renderer pre-write fetch gate ----
47
+ //
48
+ // v2.0 changes the viewer's verb from render-inert to FETCH. gateAssetUrl is
49
+ // the single orchestrator every write site consults BEFORE an asset URL
50
+ // reaches the mirror DOM, so the viewer's browser never issues a GET for a
51
+ // blocked origin (snapshot: pre-srcdoc string layer; diff ADD/subtree:
52
+ // pre-importNode on inert template content; diff ATTR: pre-setAttribute).
53
+ //
54
+ // Pure and fail-closed (mirrors compileMaskSelector's fail-closed-and-loud
55
+ // precedent): it takes the per-viewer posture in ctx so it is unit-testable
56
+ // in isolation and reused unchanged across all four sites. Precedence:
57
+ // 1. mediaMode 'off' -> block ALL asset fetch (no surface).
58
+ // 2. allowAssetOrigins host match -> ALLOW (explicit host widen of the
59
+ // conservative default; the only way a
60
+ // private/non-https host is reachable).
61
+ // 3. classifyAssetOrigin(url) -> classifier deny is authoritative
62
+ // (https-only + private-range deny)
63
+ // unless (2) widened it.
64
+ // 4. assetOriginPolicy(url, ctx) -> host hook, fail-closed: a throw OR any
65
+ // non-true return BLOCKS (never opens).
66
+ // 5. mediaMode 'poster' | 'reference' -> in 'poster' mode the playable-media
67
+ // kinds ('media' = <video src>, 'source'
68
+ // = <source src>) are BLOCKED so no media
69
+ // GET issues (Phase 13 CR-01: the poster
70
+ // image is the only fetch poster mode
71
+ // permits); poster images and <img>
72
+ // pass under 'poster'. 'reference' permits
73
+ // all by-reference assets.
74
+ var VALID_MEDIA_MODES = { off: true, poster: true, reference: true };
75
+
76
+ /** Extract a lowercased hostname from a URL string, or '' on parse failure. */
77
+ function assetUrlHost(url) {
78
+ try {
79
+ return new URL(String(url)).hostname.toLowerCase();
80
+ } catch (e) {
81
+ return '';
82
+ }
83
+ }
84
+
85
+ /**
86
+ * True when any candidate in a srcset value is blocked by the supplied gate.
87
+ * Reuses the shared per-candidate parser so the fragment gate covers srcset
88
+ * with the same vocabulary as the snapshot/diff gates (review WR-03/WR-04).
89
+ * Unparseable input fails closed (treated as blocked).
90
+ * @param {string} srcset
91
+ * @param {(url: string, kind: string) => { allow: boolean }} gateAsset
92
+ * @returns {boolean}
93
+ */
94
+ function srcsetHasBlockedCandidate(srcset, gateAsset) {
95
+ if (!srcset) return false;
96
+ try {
97
+ var candidates = parseSrcsetCandidates(srcset);
98
+ for (var i = 0; i < candidates.length; i++) {
99
+ var url = candidates[i].url;
100
+ if (!url) continue;
101
+ var verdict = gateAsset(url, 'image');
102
+ if (!verdict || !verdict.allow) return true;
103
+ }
104
+ return false;
105
+ } catch (e) {
106
+ return true; // unparseable srcset: fail closed
107
+ }
108
+ }
109
+
110
+ /**
111
+ * The renderer's pre-write asset fetch gate (MSEC-01/MSEC-02). Pure: decides
112
+ * allow/deny for a single asset URL under the posture carried in ctx. Every
113
+ * branch that is not an explicit allow fails closed.
114
+ *
115
+ * @param {string} url Absolute asset URL about to be written into the mirror.
116
+ * @param {Object} [ctx] Posture: { mediaMode, allowAssetOrigins, assetOriginPolicy, kind }.
117
+ * @returns {{ allow: boolean, reason: string }}
118
+ */
119
+ export function gateAssetUrl(url, ctx) {
120
+ var c = ctx || {};
121
+ var mode = VALID_MEDIA_MODES[c.mediaMode] ? c.mediaMode : 'reference';
122
+
123
+ // (1) mediaMode 'off': no viewer fetch surface at all.
124
+ if (mode === 'off') return { allow: false, reason: 'media-off' };
125
+
126
+ // (2) allowAssetOrigins widen: an explicitly allowlisted host is reachable
127
+ // even if the conservative classifier would otherwise deny it.
128
+ var host = assetUrlHost(url);
129
+ var allowlist = Array.isArray(c.allowAssetOrigins) ? c.allowAssetOrigins : null;
130
+ var widened = false;
131
+ if (allowlist && host) {
132
+ for (var i = 0; i < allowlist.length; i++) {
133
+ if (String(allowlist[i]).toLowerCase() === host) { widened = true; break; }
134
+ }
135
+ }
136
+
137
+ // (3) classifier: authoritative deny unless (2) widened the host.
138
+ if (!widened) {
139
+ var verdict = classifyAssetOrigin(url);
140
+ if (!verdict.allowed) return { allow: false, reason: verdict.reason };
141
+ }
142
+
143
+ // (4) host hook, fail-closed: throw OR non-true -> block.
144
+ if (typeof c.assetOriginPolicy === 'function') {
145
+ var ok;
146
+ try {
147
+ ok = c.assetOriginPolicy(url, c);
148
+ } catch (e) {
149
+ return { allow: false, reason: 'hook-threw' };
150
+ }
151
+ if (ok !== true) return { allow: false, reason: 'hook-denied' };
152
+ }
153
+
154
+ // (5) posture: in 'poster' mode the ONLY fetch poster mode permits is the
155
+ // poster image itself -- no playable media source may issue a GET (CR-01 /
156
+ // 13-RESEARCH Open Q3). A playable source fetches the full media bytes, which
157
+ // is exactly the GET poster mode exists to suppress; this MUST be enforced at
158
+ // the STRING layer (the authoritative pre-srcdoc gate -- the parser prefetches
159
+ // <video src>/<source src> DURING parse, before any post-parse scrub can run).
160
+ // kinds 'media' (<video src>) and 'source' (<source src>) are the playable-
161
+ // source kinds; 'poster' and 'image' stay allowed (the poster image is the
162
+ // one thing poster mode renders). 'reference' mode permits all by-reference
163
+ // assets and is unaffected. Fail-closed posture, mirroring the gate's other
164
+ // explicit denies.
165
+ if (mode === 'poster' && (c.kind === 'media' || c.kind === 'source')) {
166
+ return { allow: false, reason: 'poster-mode-media' };
167
+ }
168
+
169
+ // 'poster' permits poster images; 'reference' permits all by-reference assets.
170
+ return { allow: true, reason: 'ok' };
171
+ }
42
172
 
43
173
  /**
44
174
  * The host-injected viewer transport. Mirrors the capture Transport's
@@ -152,13 +282,33 @@ export function computeScale(pageW, pageH, containerW, containerH) {
152
282
  export function createViewer(options) {
153
283
  var cfg = options || {};
154
284
 
155
- var container = cfg.container;
285
+ // Container resolution: `mount` is accepted as an alias for `container`
286
+ // (the host-driven asset-gate path and embedders that think in "mount
287
+ // points" use it). When the resolved container carries no ownerDocument,
288
+ // cfg.document is the construction-document fallback (see `doc` below).
289
+ var hostDriven = !cfg.container && !!cfg.mount; // mount alias == host-driven API
290
+ var container = cfg.container || cfg.mount;
156
291
  if (!container || typeof container.appendChild !== 'function') {
157
292
  throw new Error('viewer-container-required');
158
293
  }
294
+ // Transport requirement depends on the API style. The wire-driven API
295
+ // (cfg.container) REQUIRES a complete transport -- the original contract,
296
+ // and a partial { send } / { onMessage } still throws. The host-driven API
297
+ // (cfg.mount) makes transport OPTIONAL: such viewers drive handleSnapshot
298
+ // directly (Phase 12 asset path) and need no socket, so a no-op transport
299
+ // keeps the dispatch wiring intact without one. A provided transport is
300
+ // always validated regardless of style.
159
301
  var transport = cfg.transport;
160
- if (!transport || typeof transport.send !== 'function'
161
- || typeof transport.onMessage !== 'function') {
302
+ if (transport) {
303
+ if (typeof transport.send !== 'function' || typeof transport.onMessage !== 'function') {
304
+ throw new Error('viewer-transport-required');
305
+ }
306
+ } else if (hostDriven) {
307
+ transport = {
308
+ send: function () {},
309
+ onMessage: function () { return function () {}; }
310
+ };
311
+ } else {
162
312
  throw new Error('viewer-transport-required');
163
313
  }
164
314
  var logger = cfg.logger || {
@@ -170,9 +320,190 @@ export function createViewer(options) {
170
320
  ? Math.max(0, cfg.disconnectDelayMs)
171
321
  : 750;
172
322
 
323
+ // Phase 12 asset-fetch posture (MSEC-01/MSEC-02). Validate mediaMode at
324
+ // factory time -- the ONLY sanctioned throw site (capture precedent); an
325
+ // invalid value is a host misconfiguration, not a per-message error.
326
+ var mediaMode = cfg.mediaMode == null ? 'reference' : String(cfg.mediaMode);
327
+ if (!VALID_MEDIA_MODES[mediaMode]) {
328
+ throw new Error('viewer-mediamode-invalid');
329
+ }
330
+ var assetOriginPolicy = typeof cfg.assetOriginPolicy === 'function'
331
+ ? cfg.assetOriginPolicy
332
+ : null;
333
+ var allowAssetOrigins = Array.isArray(cfg.allowAssetOrigins)
334
+ ? cfg.allowAssetOrigins.slice()
335
+ : null;
336
+ // Phase 13 (MEDIA-05): onMediaBlocked is a CONFIG callback (the
337
+ // assetOriginPolicy-hook family), NOT an on('state'|'health') subscription
338
+ // (which throws on other names). Invoked with the element nid when a
339
+ // programmatic play() rejects with NotAllowedError; its errors are contained
340
+ // to the logger (never rethrown). mediaReconcileConfig overrides merge over
341
+ // DEFAULT_MEDIA_RECONCILE_CONFIG (the reconciler tolerances stay tunable).
342
+ var onMediaBlocked = typeof cfg.onMediaBlocked === 'function' ? cfg.onMediaBlocked : null;
343
+ var mediaReconcileConfig = (cfg.mediaReconcileConfig && typeof cfg.mediaReconcileConfig === 'object')
344
+ ? cfg.mediaReconcileConfig
345
+ : DEFAULT_MEDIA_RECONCILE_CONFIG;
346
+ // Phase 14 (MADPT-01/03): the adaptive-player config-callback family (the
347
+ // onMediaBlocked/assetOriginPolicy family, NOT the throwing on() allowlist).
348
+ // playerFactory is the host-provided HLS/DASH/Shaka player seam; absent, the
349
+ // optional lazy hls.js path (or degrade-to-poster) handles HLS. onMediaUnavailable
350
+ // is the degrade-reason callback (no-manifest|no-player|mse-opaque|drm); a non-
351
+ // function is ignored (graceful absence). Both are contained -- a throwing host
352
+ // callback can never wedge the mirror.
353
+ var playerFactory = typeof cfg.playerFactory === 'function' ? cfg.playerFactory : null;
354
+ var onMediaUnavailable = typeof cfg.onMediaUnavailable === 'function' ? cfg.onMediaUnavailable : null;
355
+ // Per-viewer gate closure: every write site (snapshot string layer, diff
356
+ // ADD/ATTR, subtree) calls this so the posture is applied uniformly and
357
+ // fail-closed. kind defaults to 'image' (P12 image scope).
358
+ function gateAsset(url, kind) {
359
+ return gateAssetUrl(url, {
360
+ mediaMode: mediaMode,
361
+ allowAssetOrigins: allowAssetOrigins,
362
+ assetOriginPolicy: assetOriginPolicy,
363
+ kind: kind || 'image'
364
+ });
365
+ }
366
+
367
+ /**
368
+ * Build the renderer-owned dimensioned blocked-origin placeholder ELEMENT
369
+ * (the DOM-fragment twin of snapshot.js's string placeholder; renderer-owned
370
+ * per the project's duplicate-don't-couple style). Preserves the source
371
+ * element's dimensions (rr_width/rr_height or width/height) so layout stays
372
+ * stable; replacing an <img> 1:1 with this <div> keeps the positional nid
373
+ * index consistent (the renderer pairs elements by the nodeIds sidecar
374
+ * positionally, not by any live identity attribute -- Phase 7). No fetchable
375
+ * attribute is set.
376
+ * @param {Document} ownerDoc
377
+ * @param {Element} el The blocked <img>.
378
+ * @returns {Element}
379
+ */
380
+ function buildAssetPlaceholderEl(ownerDoc, el) {
381
+ var ph = ownerDoc.createElement('div');
382
+ ph.setAttribute('data-ps-asset-unavailable', 'blocked-origin');
383
+ var w = (el.getAttribute && (el.getAttribute('rr_width') || el.getAttribute('width'))) || '';
384
+ var h = (el.getAttribute && (el.getAttribute('rr_height') || el.getAttribute('height'))) || '';
385
+ if (w) ph.setAttribute('rr_width', w);
386
+ if (h) ph.setAttribute('rr_height', h);
387
+ return ph;
388
+ }
389
+
390
+ /**
391
+ * Pre-write asset gate over a PARSED, inert DOM subtree (defense-in-depth
392
+ * for the post-parse mirror body and the authoritative gate for diff ADD /
393
+ * subtree-response template content, which is inert and fires no fetch). For
394
+ * each <img>: apply the ASST-03 currentSrc pin (effective src =
395
+ * data-ps-currentsrc, neutralize srcset/sizes), then gateAsset the effective
396
+ * src; blocked -> replace the <img> with the dimensioned placeholder. Safe
397
+ * on any Document-owned root; contained per-element so one bad node never
398
+ * aborts the pass.
399
+ * @param {Node} rootNode A parsed fragment/body (template.content or mirror body).
400
+ */
401
+ function gateFragmentAssets(rootNode) {
402
+ if (!rootNode || typeof rootNode.querySelectorAll !== 'function') return;
403
+ var ownerDoc = rootNode.ownerDocument || (rootNode.nodeType === 9 ? rootNode : null);
404
+ if (!ownerDoc) return;
405
+ var imgs = rootNode.querySelectorAll('img');
406
+ for (var i = 0; i < imgs.length; i++) {
407
+ var el = imgs[i];
408
+ try {
409
+ var pinned = el.getAttribute('data-ps-currentsrc');
410
+ var effective = el.getAttribute('src');
411
+ if (pinned) {
412
+ effective = pinned;
413
+ el.setAttribute('src', pinned);
414
+ el.removeAttribute('srcset');
415
+ el.removeAttribute('sizes');
416
+ el.removeAttribute('data-ps-currentsrc');
417
+ }
418
+ if (effective && !gateAsset(effective, 'image').allow) {
419
+ var ph = buildAssetPlaceholderEl(ownerDoc, el);
420
+ if (el.parentNode) el.parentNode.replaceChild(ph, el);
421
+ continue;
422
+ }
423
+ // srcset gate (review WR-04): an <img srcset> with NO src (and no
424
+ // currentsrc pin, which removes srcset above) is otherwise imported
425
+ // with its blocked candidate intact, where the browser can fetch it.
426
+ // Gate every candidate; if any is blocked, replace with the
427
+ // placeholder when there is no allowed src, else strip srcset so only
428
+ // the allowed src can fetch.
429
+ var srcset = el.getAttribute('srcset');
430
+ if (srcset && srcsetHasBlockedCandidate(srcset, gateAsset)) {
431
+ if (!effective) {
432
+ var phSrcset = buildAssetPlaceholderEl(ownerDoc, el);
433
+ if (el.parentNode) el.parentNode.replaceChild(phSrcset, el);
434
+ } else {
435
+ el.removeAttribute('srcset');
436
+ }
437
+ }
438
+ } catch (e) {
439
+ logger.warn('[Renderer] asset gate pass failed for an element', {
440
+ error: e && e.message ? e.message : String(e)
441
+ });
442
+ }
443
+ }
444
+ gateFragmentMedia(rootNode, ownerDoc);
445
+ }
446
+
447
+ /**
448
+ * Post-parse media-asset gate (Phase 13 defense-in-depth + poster-mode
449
+ * source neutralization). The STRING-layer gateSnapshotAssets is the
450
+ * authoritative pre-parse control (the parser fetches during parse); this
451
+ * pass covers the diff ADD/subtree inert-fragment path and re-asserts the
452
+ * posture on the parsed body. For each <video>/<audio>:
453
+ * - gate src + poster; a blocked URL is removed (no fetchable attribute).
454
+ * - mediaMode 'poster': strip src and every child <source src> so NO media
455
+ * GET issues while the gated poster is kept (13-RESEARCH Open Q3).
456
+ * For each standalone <source>: gate src; blocked or poster-mode -> removed.
457
+ * @param {Node} rootNode
458
+ * @param {Document} ownerDoc
459
+ */
460
+ function gateFragmentMedia(rootNode, ownerDoc) {
461
+ var posterOnly = (mediaMode === 'poster');
462
+ var media = rootNode.querySelectorAll('video, audio');
463
+ for (var i = 0; i < media.length; i++) {
464
+ var el = media[i];
465
+ try {
466
+ var src = el.getAttribute('src');
467
+ if (src && (posterOnly || !gateAsset(src, 'media').allow)) {
468
+ el.removeAttribute('src');
469
+ }
470
+ var poster = el.getAttribute('poster');
471
+ if (poster && !gateAsset(poster, 'poster').allow) {
472
+ el.removeAttribute('poster');
473
+ }
474
+ // Child <source> elements bind the playable source; in poster mode or
475
+ // when blocked, neutralize their src so the element selects nothing.
476
+ var childSources = el.querySelectorAll('source');
477
+ for (var j = 0; j < childSources.length; j++) {
478
+ var cs = childSources[j];
479
+ var csSrc = cs.getAttribute('src');
480
+ if (csSrc && (posterOnly || !gateAsset(csSrc, 'media').allow)) {
481
+ cs.removeAttribute('src');
482
+ }
483
+ }
484
+ } catch (e) {
485
+ logger.warn('[Renderer] media gate pass failed for an element', {
486
+ error: e && e.message ? e.message : String(e)
487
+ });
488
+ }
489
+ }
490
+ // Standalone <source> (not under a video/audio we already walked, e.g. a
491
+ // detached fragment) -- gate defensively.
492
+ var looseSources = rootNode.querySelectorAll('source');
493
+ for (var k = 0; k < looseSources.length; k++) {
494
+ var ls = looseSources[k];
495
+ try {
496
+ var lsSrc = ls.getAttribute('src');
497
+ if (lsSrc && (posterOnly || !gateAsset(lsSrc, 'media').allow)) {
498
+ ls.removeAttribute('src');
499
+ }
500
+ } catch (e2) { /* contained: one bad node never aborts the pass */ }
501
+ }
502
+ }
503
+
173
504
  // All DOM construction happens in the container's own document so the
174
505
  // viewer works in any window (host page, jsdom test, future multi-doc).
175
- var doc = container.ownerDocument;
506
+ var doc = container.ownerDocument || cfg.document;
176
507
  var win = doc.defaultView;
177
508
 
178
509
  // --- Viewer root: fills the container, clips the scaled mirror, and
@@ -228,11 +559,21 @@ export function createViewer(options) {
228
559
  var scrubDoc = iframe.contentDocument;
229
560
  if (scrubDoc && scrubDoc.body) {
230
561
  sanitizeFragment(scrubDoc.body, sanitizeCounters, logger);
562
+ // DEFENSE-IN-DEPTH (MSEC-01): the authoritative snapshot gate already
563
+ // ran at the string layer (handleSnapshot) so the parser never saw a
564
+ // blocked URL; this post-parse pass re-gates the parsed mirror body to
565
+ // catch any asset a future write path introduces and to keep the pin
566
+ // consistent on the live mirror DOM.
567
+ gateFragmentAssets(scrubDoc.body);
231
568
  if (lastSnapshotPayload) {
232
569
  resetIdentityIndex(scrubDoc, lastSnapshotPayload.nodeIds || []);
233
570
  installStyleSources(scrubDoc, lastSnapshotPayload.styleSources || [], { kind: 'document' });
234
571
  installShadowRoots(scrubDoc, lastSnapshotPayload.shadowRoots || []);
235
572
  installFrames(scrubDoc, lastSnapshotPayload.frames || []);
573
+ // Phase 13 (MEDIA-02, Pitfall 7): apply the snapshot media[] baseline
574
+ // once now that nids are paired -- the INITIAL desired state -- then
575
+ // defer to the reconciler. No-op in poster/off mode (no playback).
576
+ applyMediaBaseline(lastSnapshotPayload.media);
236
577
  }
237
578
  }
238
579
  } catch (e) {
@@ -270,6 +611,45 @@ export function createViewer(options) {
270
611
  var overlays = createOverlays({ document: doc, logger: logger });
271
612
  root.appendChild(overlays.layer);
272
613
 
614
+ // --- Phase 14 (MADPT-01/03): the parent-realm adaptive media player. Runs
615
+ // ENTIRELY in this (host/parent) realm; the mirror iframe stays exactly
616
+ // sandbox="allow-same-origin" (no allow-scripts). attach() binds an HLS/DASH
617
+ // manifest to the inert in-iframe <video> (native-HLS-first -> playerFactory
618
+ // -> optional lazy hls.js -> degrade-to-poster); the single degrade(nid,reason)
619
+ // sink shows the media-unavailable overlay + invokes onMediaUnavailable. The
620
+ // onMediaUnavailable host callback is wrapped in the same containment as
621
+ // onMediaBlocked (safeInvokeMediaHook) so a throwing host hook can never wedge
622
+ // the mirror; a throwing playerFactory is contained by the player's degrade
623
+ // sink. Plan 03 routes STREAM.MEDIA_HINT to attach() and calls destroyAll() on
624
+ // a re-snapshot (Pattern 2 -- teardown on new identity). gateAsset reuses the
625
+ // Phase 12 fail-closed gate so a manifest/segment URL is re-gated at the viewer
626
+ // (defense in depth -- a hint is attacker-influenced). win is the PARENT realm
627
+ // (the MSE feature-detect surface), NOT iframe.contentWindow. ---
628
+ var mediaPlayer = createMediaPlayer({
629
+ doc: doc,
630
+ win: win,
631
+ gateAsset: gateAsset,
632
+ logger: logger,
633
+ playerFactory: playerFactory,
634
+ onMediaUnavailable: function (nid, reason) {
635
+ safeInvokeMediaHook(function (n) {
636
+ if (onMediaUnavailable) onMediaUnavailable(n, reason);
637
+ }, nid);
638
+ },
639
+ showOverlay: function (kind, payload, ctx) { return overlays.show(kind, payload, ctx); },
640
+ resolveNidRect: resolveNidRect,
641
+ ensurePlaying: ensurePlaying
642
+ });
643
+ // Page-scope adaptive hints awaiting an MSE-opaque element to play (most-
644
+ // recent-wins per kind). An element-scope hint binds immediately; a page-scope
645
+ // hint sits here until handleMedia sees a source-less element start, then is
646
+ // consumed (14-RESEARCH "manifest->element correlation": never block on perfect
647
+ // correlation). Cleared on every new stream identity in handleSnapshot.
648
+ var pendingHints = new Map();
649
+ // nids that have already consumed/bound an adaptive hint this generation, so a
650
+ // page hint is attached at most once per element (idempotent consumption).
651
+ var hintBoundNids = new Set();
652
+
273
653
  // Auto-attach (D-01): creation yields a live, ready-to-stream mirror.
274
654
  container.appendChild(root);
275
655
 
@@ -310,6 +690,11 @@ export function createViewer(options) {
310
690
  var destroyed = false;
311
691
  var nidToNode = new Map();
312
692
  var nodeToNid = new WeakMap();
693
+ // Phase 13 (Pitfall 7): nids whose snapshot media[] baseline has been applied
694
+ // once. The baseline is the INITIAL desired state; after first bind control
695
+ // passes to the reconciler (subsequent STREAM.MEDIA), so the baseline never
696
+ // re-fights live drift on a re-snapshot. Reset per snapshot identity.
697
+ var mediaFirstBind = new Set();
313
698
  var frameLoadHandlers = new WeakMap();
314
699
  var nodeHighlightEl = null;
315
700
  var pendingSubtreeRequests = new Map();
@@ -737,6 +1122,12 @@ export function createViewer(options) {
737
1122
  if (s.media) el.setAttribute('media', String(s.media));
738
1123
  if (s.disabled) el.setAttribute('data-ps-style-disabled', 'true');
739
1124
  rootNode.appendChild(el);
1125
+ // A disabled source must not apply in the mirror -- the diagnostic
1126
+ // attribute above is not enough. Disable the sheet itself, set after
1127
+ // insertion so the StyleSheet object exists to be disabled.
1128
+ if (s.disabled) {
1129
+ try { el.disabled = true; } catch (err) { /* CSSOM disabled unsupported */ }
1130
+ }
740
1131
  return true;
741
1132
  }
742
1133
 
@@ -1087,6 +1478,13 @@ export function createViewer(options) {
1087
1478
  */
1088
1479
  function handleSnapshot(payload) {
1089
1480
  var p = payload || {};
1481
+ // Accept either a bare SnapshotPayload (the dispatch() path passes
1482
+ // payload directly) or a full { type, payload } message envelope (the
1483
+ // host-driven handleSnapshot entry point on the returned handle). Unwrap
1484
+ // the envelope so both call shapes resolve the same payload.
1485
+ if (typeof p.html !== 'string' && p.payload && typeof p.payload === 'object') {
1486
+ p = p.payload;
1487
+ }
1090
1488
  if (typeof p.html !== 'string') {
1091
1489
  logger.error('[Renderer] snapshot missing html');
1092
1490
  return;
@@ -1104,7 +1502,31 @@ export function createViewer(options) {
1104
1502
  lastScroll.y = p.scrollY || 0;
1105
1503
  lastSnapshotPayload = p;
1106
1504
  clearIdentityIndex();
1107
- iframe.srcdoc = buildSnapshotHtml(p);
1505
+ mediaFirstBind.clear(); // new identity: re-bind media baseline on next load
1506
+ // Phase 14 (Pattern 2 -- teardown on new identity / Pitfall 2 -- object-URL
1507
+ // leak): a new stream identity tears down EVERY live adaptive player before
1508
+ // the new mirror document replaces the prior child elements, revoking parent-
1509
+ // realm object URLs and freeing buffers so a re-snapshot never orphans a
1510
+ // player bound to a now-dead element. It also invalidates any stored page hint
1511
+ // and the per-element bound set (a prior page's manifest must never bind a new
1512
+ // page's element).
1513
+ mediaPlayer.destroyAll();
1514
+ pendingHints.clear();
1515
+ hintBoundNids.clear();
1516
+ // PRE-WRITE FETCH GATE (MSEC-01, THE timing rule -- 12-RESEARCH Pitfall 1):
1517
+ // rewrite blocked <img> assets to the dimensioned blocked-origin
1518
+ // placeholder and apply the ASST-03 currentSrc pin at the STRING layer,
1519
+ // BEFORE buildSnapshotHtml assembles the srcdoc, so a real browser's
1520
+ // parser never sees a blocked URL and never issues the GET. Operates on a
1521
+ // shallow payload copy (the wire payload object stays intact for the
1522
+ // post-parse scrub's nodeIds/styleSources re-read). This rewrites typed
1523
+ // values we are emitting -- NOT a scrub-then-reparse of sanitized HTML
1524
+ // (snapshot.js header lines 14-19 invariant preserved). The post-parse
1525
+ // DOM gate below is defense-in-depth for diffs/robustness.
1526
+ var gatedPayload = Object.assign({}, p, {
1527
+ html: gateSnapshotAssets(p.html, gateAsset)
1528
+ });
1529
+ iframe.srcdoc = buildSnapshotHtml(gatedPayload);
1108
1530
  markLive('snapshot');
1109
1531
  }
1110
1532
 
@@ -1137,7 +1559,12 @@ export function createViewer(options) {
1137
1559
  installFrames(cd, frames || []);
1138
1560
  },
1139
1561
  applyStyleSource: applyStyleSource,
1140
- removeStyleSource: removeStyleSource
1562
+ removeStyleSource: removeStyleSource,
1563
+ // Phase 12 (MSEC-01) pre-write asset gate hooks for the diff applier:
1564
+ // ADD template content is gated as an inert fragment; ATTR src/poster
1565
+ // is gated per-URL before setAttribute.
1566
+ gateFragmentAssets: gateFragmentAssets,
1567
+ gateAssetUrl: gateAsset
1141
1568
  }
1142
1569
  });
1143
1570
  if (!resyncPending) markLive('mutations');
@@ -1164,6 +1591,9 @@ export function createViewer(options) {
1164
1591
  var tpl = targetDoc.createElement('template');
1165
1592
  tpl.innerHTML = p.html || '';
1166
1593
  sanitizeFragment(tpl.content, sanitizeCounters, logger);
1594
+ // PRE-WRITE FETCH GATE (MSEC-01): template content is inert (no fetch), so
1595
+ // gating here -- before importNode -- is pre-write and safe.
1596
+ gateFragmentAssets(tpl.content);
1167
1597
  var newNode = tpl.content.firstElementChild;
1168
1598
  if (!newNode) {
1169
1599
  logger.warn('[Renderer] subtree response dropped: html parsed to no element', {
@@ -1233,6 +1663,405 @@ export function createViewer(options) {
1233
1663
  markLive('dialog');
1234
1664
  }
1235
1665
 
1666
+ // --- Phase 13 media driver (MEDIA-01/05): the in-iframe <video>/<audio> is
1667
+ // inert (no allow-scripts); the PARENT realm is the only tier that can drive
1668
+ // it cross-realm. handleMedia resolves the nid, runs the pure reconciler, and
1669
+ // applies the action by calling methods on the in-iframe element. The element
1670
+ // is NEVER scripted; affordances live in the parent-realm overlay layer. ---
1671
+
1672
+ /** Invoke a host hook in containment -> logger, never rethrow (T-13-12). */
1673
+ function safeInvokeMediaHook(fn, nid) {
1674
+ if (typeof fn !== 'function') return;
1675
+ try {
1676
+ fn(nid);
1677
+ } catch (err) {
1678
+ logger.error('[Renderer] onMediaBlocked hook failed', err);
1679
+ }
1680
+ }
1681
+
1682
+ /**
1683
+ * Show the blocked-play affordance over the element rect and arm its onActivate
1684
+ * to re-issue play() (user-gesture-backed, so autoplay policy permits it). On
1685
+ * a successful re-play the affordance hides. Never wedges the mirror.
1686
+ * @param {Element} el
1687
+ * @param {number|string} nid
1688
+ */
1689
+ function showBlockedPlayAffordance(el, nid) {
1690
+ overlays.show('media-blocked', {
1691
+ nid: nid,
1692
+ onActivate: function () {
1693
+ try {
1694
+ var p = el.play();
1695
+ if (p !== undefined && typeof p.then === 'function') {
1696
+ p.then(function () { overlays.show('media-blocked', null); })
1697
+ .catch(function () { /* still blocked: keep the affordance up */ });
1698
+ } else {
1699
+ overlays.show('media-blocked', null);
1700
+ }
1701
+ } catch (e) { /* contained: a re-play failure keeps the affordance */ }
1702
+ }
1703
+ }, { anchorRect: resolveNidRect(nid) });
1704
+ }
1705
+
1706
+ /**
1707
+ * Ensure the element is playing under autoplay policy. Sets muted=true before
1708
+ * the first programmatic play (muted autoplay is always allowed), then guards
1709
+ * play()'s return: jsdom (and very old browsers) return undefined, so the
1710
+ * `if (p !== undefined && typeof p.catch === 'function')` guard avoids a
1711
+ * TypeError; a NotAllowedError rejection shows the blocked-play affordance and
1712
+ * invokes onMediaBlocked(nid). Any other rejection falls through to the
1713
+ * Phase 12 load-error path (no affordance). (13-RESEARCH Example 4.)
1714
+ * @param {Element} el
1715
+ * @param {number|string} nid
1716
+ */
1717
+ function ensurePlaying(el, nid) {
1718
+ if (!el.paused) return;
1719
+ try { el.muted = true; } catch (e) { /* muted-autoplay default best-effort */ }
1720
+ var p;
1721
+ try {
1722
+ p = el.play();
1723
+ } catch (e) {
1724
+ return; // a synchronous play() throw is contained (never wedges)
1725
+ }
1726
+ if (p !== undefined && typeof p.catch === 'function') {
1727
+ p.catch(function (err) {
1728
+ if (err && err.name === 'NotAllowedError') {
1729
+ showBlockedPlayAffordance(el, nid);
1730
+ safeInvokeMediaHook(onMediaBlocked, nid);
1731
+ }
1732
+ // Any other rejection: defer to the Phase 12 load-error placeholder.
1733
+ });
1734
+ }
1735
+ }
1736
+
1737
+ /**
1738
+ * Apply one reconciler action to the in-iframe element from the parent realm.
1739
+ * Driver guards (13-RESEARCH Example 4 + Pitfalls 4/6): hold while
1740
+ * element.seeking; only seek when readyState >= HAVE_METADATA (1); rejoin-edge
1741
+ * reads seekable.end only when seekable.length > 0 (else holds). All element
1742
+ * mutations are try/caught so one failure never wedges the mirror.
1743
+ * @param {Element} el
1744
+ * @param {{action: string, toTime?: number, rate?: number, revertRate?: number}} action
1745
+ * @param {number|string} nid
1746
+ */
1747
+ function applyMediaAction(el, action, nid) {
1748
+ if (!action || typeof action.action !== 'string') return;
1749
+ // Pitfall 6 driver guard: never apply a new seek while a seek is in flight.
1750
+ if (el.seeking) {
1751
+ // Still allow pause to flow even mid-seek; a new seek is the only thing held.
1752
+ if (action.action === 'pause') { try { el.pause(); } catch (e) {} }
1753
+ return;
1754
+ }
1755
+ switch (action.action) {
1756
+ case 'pause':
1757
+ try { el.pause(); } catch (e) { /* contained */ }
1758
+ break;
1759
+ case 'seek':
1760
+ case 'rejoin-edge': {
1761
+ var target;
1762
+ if (action.action === 'rejoin-edge') {
1763
+ // Live rejoin: seekable.end only when the range is non-empty (Pitfall 4).
1764
+ target = (el.seekable && el.seekable.length > 0)
1765
+ ? el.seekable.end(el.seekable.length - 1)
1766
+ : null;
1767
+ } else {
1768
+ target = action.toTime;
1769
+ }
1770
+ if (target != null && el.readyState >= 1 /* HAVE_METADATA */) {
1771
+ try { el.currentTime = target; } catch (e) { /* contained */ }
1772
+ }
1773
+ ensurePlaying(el, nid);
1774
+ break;
1775
+ }
1776
+ case 'nudge':
1777
+ try { el.playbackRate = action.rate; } catch (e) { /* contained */ }
1778
+ ensurePlaying(el, nid);
1779
+ break;
1780
+ case 'hold':
1781
+ // Restore the true rate if a nudge was active and drifted the rate.
1782
+ if (action.revertRate != null && el.playbackRate !== action.revertRate) {
1783
+ try { el.playbackRate = action.revertRate; } catch (e) { /* contained */ }
1784
+ }
1785
+ ensurePlaying(el, nid);
1786
+ break;
1787
+ default:
1788
+ break;
1789
+ }
1790
+ }
1791
+
1792
+ /**
1793
+ * STREAM.MEDIA handler (MEDIA-01/05, MWIRE-01): the side-channel twin of
1794
+ * handleScroll/handleOverlay. Streaming + identity gate, then resolve the nid,
1795
+ * run the pure reconciler over the element's observed state, and drive the
1796
+ * in-iframe element cross-realm. After ensurePlaying, evaluate the unmute
1797
+ * trigger. In mediaMode 'poster'/'off' no source is bound and no driver runs
1798
+ * (the Task 1 string/fragment gate already neutralized the source) and no
1799
+ * affordance is surfaced. A viewer without this case (the dispatch default)
1800
+ * silently ignores the message (backward-compat).
1801
+ * @param {Object} payload
1802
+ */
1803
+ function handleMedia(payload) {
1804
+ if (viewerState !== 'streaming') return;
1805
+ if (!isCurrentStream(payload, active)) return;
1806
+ // poster/off: the source is neutralized at the gate; never drive playback or
1807
+ // surface a playback affordance (13-UI-SPEC State C: poster is a still frame).
1808
+ if (mediaMode !== 'reference') {
1809
+ // State C wire (13-UI-REVIEW Fix 1 -- the dead-code BLOCKER): in POSTER mode
1810
+ // a media element whose gated `poster` did NOT survive renders as an
1811
+ // unexplained blank, so drive the registered-but-never-shown media-poster
1812
+ // caption: show it IFF the element has no surviving poster, else hide it
1813
+ // (the poster image is the explanation). 'off' mode renders nothing.
1814
+ if (mediaMode === 'poster') {
1815
+ var posterNid = payload && payload.nid;
1816
+ var posterEl = resolveIndexedNode(posterNid);
1817
+ var hasPoster = !!(posterEl && posterEl.getAttribute && posterEl.getAttribute('poster'));
1818
+ if (posterEl && !hasPoster) {
1819
+ overlays.show('media-poster', { nid: posterNid }, { anchorRect: resolveNidRect(posterNid) });
1820
+ } else {
1821
+ overlays.show('media-poster', null);
1822
+ }
1823
+ }
1824
+ markLive('media');
1825
+ return;
1826
+ }
1827
+ var nid = payload && payload.nid;
1828
+ var el = resolveIndexedNode(nid);
1829
+ if (!el || typeof el.play !== 'function') return;
1830
+
1831
+ // Phase 14 (MADPT-02 page correlation): an MSE-opaque element (no resolvable
1832
+ // source) that starts is the consumer for the most-recent stored page hint.
1833
+ // Consume at most once per element per generation, then let the player +
1834
+ // reconciler own it (the source-less element otherwise plays nothing).
1835
+ maybeConsumePageHint(el, nid);
1836
+
1837
+ var localState = {
1838
+ currentTime: el.currentTime,
1839
+ paused: !!el.paused,
1840
+ playbackRate: el.playbackRate,
1841
+ seeking: !!el.seeking,
1842
+ readyState: el.readyState
1843
+ };
1844
+ var action = reconcileMediaDrift(localState, payload, Date.now(), mediaReconcileConfig);
1845
+ applyMediaAction(el, action, nid);
1846
+ evaluateUnmuteTrigger(el, payload, nid);
1847
+ markLive('media');
1848
+ }
1849
+
1850
+ /**
1851
+ * Is this media element MSE-opaque / source-less -- i.e. it resolves to no
1852
+ * playable source the viewer can reference (no `src` attribute survived the
1853
+ * gate, no current child <source src>, and an empty currentSrc)? Such an
1854
+ * element is the candidate consumer for a page-scope adaptive hint (an
1855
+ * adaptive manifest never appears as a plain element src). All reads are
1856
+ * guarded so a hostile/odd element never wedges the media path.
1857
+ * @param {Element} el
1858
+ * @returns {boolean}
1859
+ */
1860
+ function mediaElementHasNoSource(el) {
1861
+ try {
1862
+ if (el.getAttribute && el.getAttribute('src')) return false;
1863
+ if (el.currentSrc) return false;
1864
+ if (typeof el.querySelector === 'function') {
1865
+ var sourced = el.querySelector('source[src]');
1866
+ if (sourced) return false;
1867
+ }
1868
+ return true;
1869
+ } catch (e) {
1870
+ return false; // unknowable -> do not consume (conservative)
1871
+ }
1872
+ }
1873
+
1874
+ /**
1875
+ * Consume the most-recent stored page hint for an MSE-opaque element on play
1876
+ * (14-RESEARCH page-level correlation). Idempotent per nid per generation: an
1877
+ * element binds at most one page hint, and only when it is source-less. The
1878
+ * stored hint is removed once bound so a single page hint maps to a single
1879
+ * consumer. No-op when the element already has a source or no hint is pending.
1880
+ * @param {Element} el
1881
+ * @param {number|string} nid
1882
+ */
1883
+ function maybeConsumePageHint(el, nid) {
1884
+ if (pendingHints.size === 0) return;
1885
+ var key = String(nid);
1886
+ if (hintBoundNids.has(key)) return;
1887
+ if (!mediaElementHasNoSource(el)) return;
1888
+ // Most-recent-wins per kind: prefer 'hls' (the optional lazy path needs no
1889
+ // host player), else 'dash' (host playerFactory only). Either is correct;
1890
+ // pick the most-recently stored across kinds.
1891
+ var chosen = null;
1892
+ pendingHints.forEach(function (hint) {
1893
+ if (!chosen || hint.storedAt >= chosen.storedAt) chosen = hint;
1894
+ });
1895
+ if (!chosen) return;
1896
+ pendingHints.delete(chosen.kind);
1897
+ hintBoundNids.add(key);
1898
+ bindAdaptiveHint(el, key, chosen.manifestUrl, chosen.kind, chosen.contentType);
1899
+ }
1900
+
1901
+ /**
1902
+ * Bind an adaptive manifest to an in-iframe element through the parent-realm
1903
+ * player. The manifestUrl was already re-gated by handleMediaHint before it
1904
+ * reached pendingHints (page scope) or before an element-scope bind; the
1905
+ * player re-gates a third time internally (defense in depth). attach() is
1906
+ * fire-and-forget (the native/factory/dash branches are synchronous; the lazy-
1907
+ * hls branch returns a promise the player self-contains) and never throws.
1908
+ * @param {Element} el
1909
+ * @param {number|string} nid
1910
+ * @param {string} manifestUrl
1911
+ * @param {'hls'|'dash'} kind
1912
+ * @param {?string} contentType
1913
+ */
1914
+ function bindAdaptiveHint(el, nid, manifestUrl, kind, contentType) {
1915
+ try {
1916
+ mediaPlayer.attach(el, manifestUrl, { nid: String(nid), kind: kind, contentType: contentType });
1917
+ } catch (e) {
1918
+ // attach() is contained internally, but guard the call site too so a
1919
+ // correlation bug never wedges the media dispatch.
1920
+ logger.warn('[Renderer] adaptive hint bind failed', { nid: String(nid) });
1921
+ }
1922
+ }
1923
+
1924
+ /**
1925
+ * STREAM.MEDIA_HINT handler (MADPT-02 consumption): the adapter-originated
1926
+ * adaptive-manifest discovery op (a structural twin of STREAM.MEDIA; old
1927
+ * viewers ignore it via the dispatch default). Flow (14-RESEARCH hint-
1928
+ * consumption spec):
1929
+ * 1. streaming + identity gate (isCurrentStream) -- drop a stale/late hint
1930
+ * from a prior page so it can never bind the wrong media (T-14-11).
1931
+ * 2. poster/off mode binds no adaptive player at all (no player surface).
1932
+ * 3. RE-GATE manifestUrl through gateAsset(url,'media') BEFORE any use -- the
1933
+ * hint is attacker-influenced; a blocked origin degrades to poster and is
1934
+ * NEVER fetched (T-14-10 / V12 SSRF defense in depth).
1935
+ * 4. element scope (payload.nid set, element resolves & is MSE-opaque) ->
1936
+ * bind immediately via the player; page scope -> store most-recent-wins
1937
+ * per kind for an opaque element to consume on play.
1938
+ * @param {Object} payload MediaHintPayload
1939
+ */
1940
+ function handleMediaHint(payload) {
1941
+ if (viewerState !== 'streaming') return;
1942
+ if (!isCurrentStream(payload, active)) return;
1943
+ // WR-03: an empty-identity hint bypasses isCurrentStream (the backward-compat
1944
+ // clause accepts any message with no identity). Before the first identity-
1945
+ // bearing snapshot establishes a generation (active.streamSessionId === ''),
1946
+ // such a hint could out-race the snapshot that defines its generation and be
1947
+ // consumed by an element it was never meant for. Do NOT accept a hint until a
1948
+ // current stream identity exists: drop an empty-identity hint that arrives in
1949
+ // the pre-snapshot window. Once a generation exists, isCurrentStream governs.
1950
+ if ((!payload || !payload.streamSessionId) && !active.streamSessionId) return;
1951
+ // Poster/off mode: no adaptive player surface (the source is neutralized at
1952
+ // the gate and poster is a still frame -- 13-UI-SPEC State C). Drop hints.
1953
+ if (mediaMode !== 'reference') { markLive('media'); return; }
1954
+ var p = payload || {};
1955
+ var manifestUrl = p.manifestUrl;
1956
+ if (!manifestUrl || typeof manifestUrl !== 'string') { markLive('media'); return; }
1957
+ var nid = (p.nid != null) ? p.nid : null;
1958
+ // RE-GATE at the viewer (defense in depth): a blocked manifest origin must
1959
+ // never be fetched -> degrade to poster instead.
1960
+ if (!gateAsset(manifestUrl, 'media').allow) {
1961
+ mediaPlayer.degrade(nid != null ? String(nid) : null, 'no-manifest');
1962
+ markLive('media');
1963
+ return;
1964
+ }
1965
+ var kind = (p.kind === 'hls' || p.kind === 'dash') ? p.kind : null;
1966
+ var scope = (p.scope === 'element') ? 'element' : (p.scope === 'page' ? 'page' : (nid != null ? 'element' : 'page'));
1967
+ if (scope === 'element' && nid != null) {
1968
+ var el = resolveIndexedNode(nid);
1969
+ // Element-scope: bind immediately when the element resolves and is MSE-
1970
+ // opaque (no resolvable source). A correlated element that already has a
1971
+ // playable source is left to the Phase 13 progressive path.
1972
+ if (el && typeof el.play === 'function' && mediaElementHasNoSource(el)) {
1973
+ hintBoundNids.add(String(nid));
1974
+ bindAdaptiveHint(el, nid, manifestUrl, kind, p.contentType);
1975
+ } else {
1976
+ // WR-05: the named element cannot take the adaptive stream -- either the
1977
+ // nid does not resolve (stale / wrong generation) or it resolves but is
1978
+ // not MSE-opaque (a resolved-but-sourced element stays with the
1979
+ // progressive path). Surface ONE concise diagnostic so a dropped hint is
1980
+ // observable instead of indistinguishable from "successfully handled".
1981
+ // Never throws (logger is advisory); the never-break contract holds.
1982
+ logger.warn('[Renderer] element-scope media hint dropped (unresolved or non-opaque nid)', {
1983
+ nid: String(nid),
1984
+ reason: el ? 'not-opaque' : 'unresolved'
1985
+ });
1986
+ }
1987
+ markLive('media');
1988
+ return;
1989
+ }
1990
+ // Page scope (nid omitted): store most-recent-wins per kind; consumed when an
1991
+ // MSE-opaque element next plays (handleMedia -> maybeConsumePageHint).
1992
+ pendingHints.set(kind || 'hls', {
1993
+ manifestUrl: manifestUrl,
1994
+ kind: kind || 'hls',
1995
+ contentType: p.contentType,
1996
+ storedAt: Date.now()
1997
+ });
1998
+ markLive('media');
1999
+ }
2000
+
2001
+ /**
2002
+ * Unmute trigger (MEDIA-05, 13-UI-SPEC State B): after the muted-default play,
2003
+ * when the in-iframe element is muted but the source reports unmuted
2004
+ * (payload.muted === false) in mediaMode 'reference', SHOW the media-unmute
2005
+ * affordance; activating it sets muted=false + restores volume and hides the
2006
+ * affordance. When the source is still muted (or no muted field), hide/skip
2007
+ * the affordance (the null-payload contract).
2008
+ * @param {Element} el
2009
+ * @param {Object} payload
2010
+ * @param {number|string} nid
2011
+ */
2012
+ function evaluateUnmuteTrigger(el, payload, nid) {
2013
+ var sourceUnmuted = payload && payload.muted === false;
2014
+ if (el.muted === true && sourceUnmuted) {
2015
+ var vol = (payload && typeof payload.volume === 'number') ? payload.volume : null;
2016
+ overlays.show('media-unmute', {
2017
+ nid: nid,
2018
+ onActivate: function () {
2019
+ try { el.muted = false; } catch (e) { /* contained */ }
2020
+ if (vol != null) { try { el.volume = vol; } catch (e2) { /* contained */ } }
2021
+ overlays.show('media-unmute', null); // hide after activation
2022
+ }
2023
+ }, { anchorRect: resolveNidRect(nid) });
2024
+ } else {
2025
+ // Source muted / field absent / element already unmuted -> hide.
2026
+ overlays.show('media-unmute', null);
2027
+ }
2028
+ }
2029
+
2030
+ /**
2031
+ * Apply the snapshot media[] baseline (Plan 02) once per element, on first
2032
+ * bind only (Pitfall 7: the baseline is the INITIAL desired state; after this,
2033
+ * live STREAM.MEDIA hands control to the reconciler so a re-snapshot never
2034
+ * jumps playback back). Each entry is nid-addressed; the seek is readyState-
2035
+ * gated (>= HAVE_METADATA) and contained. No-op in poster/off mode (the source
2036
+ * is neutralized; nothing plays). All element mutations are best-effort.
2037
+ * @param {Array<Object>} baseline payload.media (absent on media-free pages)
2038
+ */
2039
+ function applyMediaBaseline(baseline) {
2040
+ if (mediaMode !== 'reference') return;
2041
+ if (!Array.isArray(baseline) || baseline.length === 0) return;
2042
+ for (var i = 0; i < baseline.length; i++) {
2043
+ var entry = baseline[i];
2044
+ if (!entry || entry.nid == null) continue;
2045
+ var key = String(entry.nid);
2046
+ if (mediaFirstBind.has(key)) continue; // already bound -> reconciler owns it
2047
+ var el = resolveIndexedNode(key);
2048
+ if (!el || typeof el.play !== 'function') continue;
2049
+ mediaFirstBind.add(key);
2050
+ try {
2051
+ // Initial currentTime only when ready (live entries carry no duration).
2052
+ if (typeof entry.currentTime === 'number' && el.readyState >= 1) {
2053
+ el.currentTime = entry.currentTime;
2054
+ }
2055
+ if (typeof entry.playbackRate === 'number') el.playbackRate = entry.playbackRate;
2056
+ if (entry.paused === false) {
2057
+ ensurePlaying(el, key);
2058
+ }
2059
+ } catch (e) {
2060
+ logger.warn('[Renderer] media baseline apply failed', { nid: key });
2061
+ }
2062
+ }
2063
+ }
2064
+
1236
2065
  /**
1237
2066
  * Transport message dispatch. The whole handler is containment-wrapped:
1238
2067
  * one malformed message routes to the logger and never kills the
@@ -1265,6 +2094,12 @@ export function createViewer(options) {
1265
2094
  case STREAM.DIALOG:
1266
2095
  handleDialog(payload);
1267
2096
  break;
2097
+ case STREAM.MEDIA:
2098
+ handleMedia(payload);
2099
+ break;
2100
+ case STREAM.MEDIA_HINT:
2101
+ handleMediaHint(payload);
2102
+ break;
1268
2103
  case STREAM.STATE:
1269
2104
  handleStreamState(payload);
1270
2105
  break;
@@ -1390,7 +2225,12 @@ export function createViewer(options) {
1390
2225
  on: on,
1391
2226
  registerOverlay: registerOverlay,
1392
2227
  requestSubtree: requestSubtree,
1393
- resolveNode: resolveNode
2228
+ resolveNode: resolveNode,
2229
+ // Host-driven snapshot entry point (Phase 12): viewers wired without a
2230
+ // wire transport (the asset-fetch-gate path) render a snapshot by calling
2231
+ // this directly. Identical to the dispatch() STREAM.SNAPSHOT target and
2232
+ // accepts either a bare payload or a { type, payload } envelope.
2233
+ handleSnapshot: handleSnapshot
1394
2234
  };
1395
2235
  }
1396
2236