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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,6 +38,10 @@
38
38
 
39
39
  import { DIFF_OP } from '../protocol/messages.js';
40
40
  import { sanitizeFragment, sanitizeAttrValue, parseSrcsetCandidates } from './sanitize.js';
41
+ import { restoreParserSafePlaceholders } from './parser-safe.js';
42
+
43
+ var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
44
+ var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
41
45
 
42
46
  /**
43
47
  * True when any candidate in a srcset value is blocked by the injected fetch
@@ -64,6 +68,29 @@ function srcsetHasBlockedCandidate(srcset, gateAssetUrl) {
64
68
  }
65
69
  }
66
70
 
71
+ /**
72
+ * Foreign-content parse context for an ADD op (quick task 261202-jwf). A
73
+ * child of an SVG or MathML element must be parsed inside an <svg> or <math>
74
+ * wrapper, or the HTML <template> parse creates HTML elements (an HTML
75
+ * <clippath> instead of SVG <clipPath>). The HTML integration points
76
+ * (foreignObject, desc, title; mi, mo, mn, ms, mtext, annotation-xml) hold
77
+ * HTML content, so they need no wrapper.
78
+ * @param {Element} parent The resolved ADD parent.
79
+ * @returns {'svg'|'math'|''}
80
+ */
81
+ function foreignParseContextTag(parent) {
82
+ if (!parent || !parent.namespaceURI) return '';
83
+ var name = parent.localName;
84
+ if (parent.namespaceURI === SVG_NAMESPACE) {
85
+ return (name === 'foreignObject' || name === 'desc' || name === 'title') ? '' : 'svg';
86
+ }
87
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
88
+ return (name === 'mi' || name === 'mo' || name === 'mn' || name === 'ms'
89
+ || name === 'mtext' || name === 'annotation-xml') ? '' : 'math';
90
+ }
91
+ return '';
92
+ }
93
+
67
94
  function installShadowRootDirect(doc, host, payload, sanitizeCounters, logger, indexSubtree, removeSubtree) {
68
95
  var p = payload || {};
69
96
  if (!doc || !host) return false;
@@ -82,6 +109,7 @@ function installShadowRootDirect(doc, host, payload, sanitizeCounters, logger, i
82
109
 
83
110
  var tpl = doc.createElement('template');
84
111
  tpl.innerHTML = p.html || '';
112
+ restoreParserSafePlaceholders(tpl.content);
85
113
  sanitizeFragment(tpl.content, sanitizeCounters, logger);
86
114
  shadowRoot.appendChild(doc.importNode(tpl.content, true));
87
115
  indexSubtree(shadowRoot, p.nodeIds || []);
@@ -174,6 +202,26 @@ export function applyMutations(doc, mutations, counters, hooks) {
174
202
  ? function (url, kind) { return identity.gateAssetUrl(url, kind); }
175
203
  : null;
176
204
 
205
+ // ADD-op parse: the renderer's single add-op innerHTML sink. TEMPLATE-context
206
+ // parse (03-RESEARCH Pattern 2, jsdom-29-verified): template content accepts
207
+ // any HTML, so context-dependent elements (<tr>, <td>, <col>, <option>, ...)
208
+ // do not drop. wrapTag is '' or a STATIC 'svg' / 'math' wrapper from
209
+ // foreignParseContextTag, so add ops under SVG or MathML parents keep their
210
+ // namespace (quick task 261202-jwf). Parser-safe placeholders are restored
211
+ // right after the parse; then the RENDER-SIDE CHOKEPOINT (SEC-02) scrubs the
212
+ // PARSED fragment -- DOM-fragment based, never string-scrub-then-reparse
213
+ // (mXSS) -- and the PRE-WRITE FETCH GATE (MSEC-01) gates the inert content
214
+ // before importNode. Returns the first parsed element, or null.
215
+ function parseAddOpNode(html, wrapTag) {
216
+ var tpl = doc.createElement('template');
217
+ tpl.innerHTML = wrapTag ? '<' + wrapTag + '>' + html + '</' + wrapTag + '>' : html;
218
+ restoreParserSafePlaceholders(tpl.content);
219
+ sanitizeFragment(tpl.content, sanitizeCounters, logger);
220
+ gateFragmentAssets(tpl.content);
221
+ var parsedRoot = wrapTag ? tpl.content.firstElementChild : tpl.content;
222
+ return parsedRoot ? parsedRoot.firstElementChild : null;
223
+ }
224
+
177
225
  // Shared miss path: count, warn, and escalate at the parity threshold.
178
226
  function recordStaleMiss(op, nid) {
179
227
  tallies.staleMisses += 1;
@@ -237,25 +285,16 @@ export function applyMutations(doc, mutations, counters, hooks) {
237
285
  recordStaleMiss(DIFF_OP.ADD, m.parentNid);
238
286
  break;
239
287
  }
240
- // TEMPLATE-context parse (03-RESEARCH Pattern 2, jsdom-29-
241
- // verified): template content accepts any HTML, so context-
242
- // dependent elements (<tr>, <td>, <col>, <option>, ...) no
243
- // longer drop. This is one of the renderer's two sanctioned
288
+ // parseAddOpNode holds one of the renderer's two sanctioned
244
289
  // innerHTML sinks for wire content; the other is the Phase 8
245
- // shadow-root replacement parser above. Both are followed by
246
- // sanitizeFragment and pinned by the purity scan.
247
- var tpl = doc.createElement('template');
248
- tpl.innerHTML = m.html;
249
- // RENDER-SIDE CHOKEPOINT (SEC-02): scrub the PARSED fragment
250
- // before it gets anywhere near the mirror document -- DOM-
251
- // fragment based, never string-scrub-then-reparse (mXSS).
252
- sanitizeFragment(tpl.content, sanitizeCounters, logger);
253
- // PRE-WRITE FETCH GATE (MSEC-01): the parsed template content is
254
- // inert (fires no fetch), so gating it here -- before importNode --
255
- // is pre-write. Applies the currentSrc pin and replaces blocked
256
- // origins with the dimensioned placeholder.
257
- gateFragmentAssets(tpl.content);
258
- var newNode = tpl.content.firstElementChild;
290
+ // shadow-root replacement parser above. Both are followed by the
291
+ // parser-safe restore and sanitizeFragment, and pinned by the
292
+ // purity scan. Under an SVG or MathML parent the op parses inside
293
+ // a static wrapper; when that yields no element (an HTML breakout
294
+ // tag such as <div>), it parses again without the wrapper.
295
+ var wrapTag = foreignParseContextTag(parent);
296
+ var newNode = parseAddOpNode(m.html, wrapTag);
297
+ if (!newNode && wrapTag) newNode = parseAddOpNode(m.html, '');
259
298
  if (!newNode) {
260
299
  // Still possible: empty/whitespace-only m.html, or html whose
261
300
  // only element was a dropped hostile subtree. Never silent
@@ -37,10 +37,11 @@
37
37
  import { buildSnapshotHtml, buildFramePlaceholderHtml, gateSnapshotAssets } from './snapshot.js';
38
38
  import { applyMutations } from './diff.js';
39
39
  import { sanitizeFragment, scrubCssText, parseSrcsetCandidates } from './sanitize.js';
40
+ import { restoreParserSafePlaceholders } from './parser-safe.js';
40
41
  import { createOverlays, mapRectToHost, OVERLAY_CSS } from './overlays.js';
41
42
  import { classifyAssetOrigin } from './asset-policy.js';
42
43
  import { createMediaPlayer } from './media-player.js';
43
- import { STREAM, CONTROL, isCurrentStream } from '../protocol/messages.js';
44
+ import { STREAM, CONTROL, BODY_NID, isCurrentStream } from '../protocol/messages.js';
44
45
  import { reconcileMediaDrift, DEFAULT_MEDIA_RECONCILE_CONFIG } from '../protocol/media-reconcile.js';
45
46
 
46
47
  // ---- Phase 12 (MSEC-01/MSEC-02): the renderer pre-write fetch gate ----
@@ -230,13 +231,33 @@ export function gateAssetUrl(url, ctx) {
230
231
  * Hide the local node highlight. Idempotent.
231
232
  * @property {(nid: string|number, options?: {reason?: string}) => string|null} requestSubtree
232
233
  * Request a bounded fresh subtree for an indexed truncated marker. Returns
233
- * the generated requestId, or null when the nid is invalid, missing, or
234
- * already in flight.
234
+ * the generated requestId, or null when the nid is invalid, missing,
235
+ * already in flight, or the reserved BODY_NID (the body is a structural
236
+ * anchor, not a recoverable subtree).
235
237
  * @property {(kind: string, renderFn: (payload: *, anchorRect: ?Object, layer: Element) => void) => void} registerOverlay
236
238
  * Register a custom overlay kind (delegates to the overlays registry --
237
239
  * the host-facing extension seam from D-10).
238
- * @property {(eventName: 'state'|'health', handler: (event: Object) => void) => (() => void)} on
239
- * Subscribe to host-facing lifecycle and health events. Returns unsubscribe.
240
+ * @property {(eventName: 'state'|'health'|'loaded', handler: (event: Object) => void) => (() => void)} on
241
+ * Subscribe to host-facing lifecycle, health, and loaded events. Returns
242
+ * unsubscribe. 'state' and 'health' call the handler immediately with the
243
+ * current value; 'loaded' never replays loads that happened before the
244
+ * subscription (see ViewerLoadedEvent).
245
+ * @property {(payload: Object) => void} handleSnapshot
246
+ * Host-driven snapshot entry point. Accepts a bare SnapshotPayload or a
247
+ * { type, payload } envelope and behaves exactly like the STREAM.SNAPSHOT
248
+ * dispatch target (identity adopted synchronously, mirror document loaded
249
+ * later; subscribe to 'loaded' to learn when it is ready).
250
+ */
251
+
252
+ /**
253
+ * Payload of the viewer 'loaded' event: the stream identity active when a
254
+ * snapshot's mirror document finished loading. Fired after the viewer has
255
+ * flipped to streaming, once per loaded snapshot document, never for the
256
+ * bare about:blank load, and never replayed to late subscribers.
257
+ *
258
+ * @typedef {Object} ViewerLoadedEvent
259
+ * @property {string} streamSessionId
260
+ * @property {number} snapshotId
240
261
  */
241
262
 
242
263
  /**
@@ -364,6 +385,18 @@ export function createViewer(options) {
364
385
  });
365
386
  }
366
387
 
388
+ // URL gate for parser-safe restores in LIVE documents (quick task
389
+ // 261202-jwf). The snapshot string-layer gate never scans <ps-node>, and a
390
+ // restored <img> in the live mirror would fetch as soon as its src is set,
391
+ // before the post-parse gate runs. restoreParserSafePlaceholders therefore
392
+ // asks this filter for src / srcset / data-ps-currentsrc on restored img,
393
+ // input, source and track, and never sets a blocked value (null = drop).
394
+ function restoreUrlFilter(tag, attr, value) {
395
+ if (attr === 'srcset') return srcsetHasBlockedCandidate(value, gateAsset) ? null : value;
396
+ var kind = tag === 'source' ? 'source' : (tag === 'track' ? 'media' : 'image');
397
+ return gateAsset(value, kind).allow ? value : null;
398
+ }
399
+
367
400
  /**
368
401
  * Build the renderer-owned dimensioned blocked-origin placeholder ELEMENT
369
402
  * (the DOM-fragment twin of snapshot.js's string placeholder; renderer-owned
@@ -558,6 +591,9 @@ export function createViewer(options) {
558
591
  try {
559
592
  var scrubDoc = iframe.contentDocument;
560
593
  if (scrubDoc && scrubDoc.body) {
594
+ // Parser-safe restore (quick task 261202-jwf): right after the parse,
595
+ // before the scrub and identity pairing, with the live-document URL gate.
596
+ restoreParserSafePlaceholders(scrubDoc.body, { filterUrl: restoreUrlFilter });
561
597
  sanitizeFragment(scrubDoc.body, sanitizeCounters, logger);
562
598
  // DEFENSE-IN-DEPTH (MSEC-01): the authoritative snapshot gate already
563
599
  // ran at the string layer (handleSnapshot) so the parser never saw a
@@ -566,7 +602,7 @@ export function createViewer(options) {
566
602
  // consistent on the live mirror DOM.
567
603
  gateFragmentAssets(scrubDoc.body);
568
604
  if (lastSnapshotPayload) {
569
- resetIdentityIndex(scrubDoc, lastSnapshotPayload.nodeIds || []);
605
+ resetIdentityIndex(scrubDoc, lastSnapshotPayload.nodeIds || [], lastSnapshotPayload.bodyNid);
570
606
  installStyleSources(scrubDoc, lastSnapshotPayload.styleSources || [], { kind: 'document' });
571
607
  installShadowRoots(scrubDoc, lastSnapshotPayload.shadowRoots || []);
572
608
  installFrames(scrubDoc, lastSnapshotPayload.frames || []);
@@ -602,6 +638,14 @@ export function createViewer(options) {
602
638
  } catch (e) { /* ignore: scroll restore is best-effort */ }
603
639
  viewerState = 'streaming';
604
640
  iframe.style.display = '';
641
+ // The 'loaded' event exists because handleSnapshot adopts the new
642
+ // identity synchronously while the mirror document loads later, and
643
+ // mutations sent before this load are dropped (or miss against the
644
+ // cleared identity index). Hosts that drive snapshots themselves (the
645
+ // player) wait for this event before sending that snapshot's
646
+ // mutations. It is the LAST statement so the viewer is already
647
+ // streaming and un-hidden when handlers run.
648
+ notifyLoaded();
605
649
  });
606
650
  root.appendChild(iframe);
607
651
 
@@ -663,6 +707,7 @@ export function createViewer(options) {
663
707
  };
664
708
  var stateListeners = new Set();
665
709
  var healthListeners = new Set();
710
+ var loadedListeners = new Set(); // 'loaded' subscribers; never replayed
666
711
  var disconnectTimer = null;
667
712
  var active = { streamSessionId: '', snapshotId: 0 };
668
713
  var lastScroll = { x: 0, y: 0 };
@@ -792,6 +837,26 @@ export function createViewer(options) {
792
837
  });
793
838
  }
794
839
 
840
+ /**
841
+ * Tell 'loaded' subscribers that the current snapshot's mirror document
842
+ * finished loading. Each handler gets its own fresh payload copy; a
843
+ * throwing handler is contained to the logger and never starves the
844
+ * others. Iterates a copy so a handler may unsubscribe itself.
845
+ */
846
+ function notifyLoaded() {
847
+ var event = {
848
+ streamSessionId: active.streamSessionId || '',
849
+ snapshotId: active.snapshotId || 0
850
+ };
851
+ Array.from(loadedListeners).forEach(function (handler) {
852
+ try {
853
+ handler({ streamSessionId: event.streamSessionId, snapshotId: event.snapshotId });
854
+ } catch (err) {
855
+ logger.error('[Renderer] event handler failed', 'loaded', err);
856
+ }
857
+ });
858
+ }
859
+
795
860
  function notifyHealth() {
796
861
  var event = healthSnapshot();
797
862
  healthListeners.forEach(function (handler) {
@@ -837,9 +902,18 @@ export function createViewer(options) {
837
902
  }
838
903
 
839
904
  function on(eventName, handler) {
840
- if ((eventName !== 'state' && eventName !== 'health') || typeof handler !== 'function') {
905
+ if ((eventName !== 'state' && eventName !== 'health' && eventName !== 'loaded') ||
906
+ typeof handler !== 'function') {
841
907
  throw new Error('viewer-event-unsupported');
842
908
  }
909
+ if (eventName === 'loaded') {
910
+ // No immediate call: 'loaded' reports future document loads only and
911
+ // never replays loads that happened before the subscription.
912
+ loadedListeners.add(handler);
913
+ return function unsubscribeViewerEvent() {
914
+ loadedListeners.delete(handler);
915
+ };
916
+ }
843
917
  var listeners = eventName === 'state' ? stateListeners : healthListeners;
844
918
  listeners.add(handler);
845
919
  try {
@@ -911,6 +985,10 @@ export function createViewer(options) {
911
985
  if (nid === undefined || nid === null) return null;
912
986
  var key = String(nid);
913
987
  if (!key) return null;
988
+ // The body is a structural anchor, not a recoverable subtree (capture
989
+ // answers a body request content-free 'untracked'); hosts that need a
990
+ // full refresh call stop() then start() on the capture.
991
+ if (key === BODY_NID) return null;
914
992
  var target = resolveIndexedNode(key);
915
993
  if (!target) return null;
916
994
  if (pendingSubtreeRequests.has(key)) return null;
@@ -1041,7 +1119,7 @@ export function createViewer(options) {
1041
1119
  }
1042
1120
  }
1043
1121
 
1044
- function resetIdentityIndex(targetDoc, nodeIds) {
1122
+ function resetIdentityIndex(targetDoc, nodeIds, bodyNid) {
1045
1123
  clearIdentityIndex();
1046
1124
  if (!targetDoc || !targetDoc.body) return;
1047
1125
  pairIdentityElements(
@@ -1049,6 +1127,16 @@ export function createViewer(options) {
1049
1127
  nodeIds,
1050
1128
  'snapshot'
1051
1129
  );
1130
+ // Reserved main-body identity (quick task 261127-u5c): body-level add ops
1131
+ // use it as their parent and body attr ops as their target. Captures older
1132
+ // than that fix send no bodyNid and index exactly as before. Sidecar
1133
+ // pairing stays authoritative: a non-conforming payload whose bodyNid
1134
+ // reuses an already paired nid never re-points that nid at the body.
1135
+ if (bodyNid !== undefined && bodyNid !== null && bodyNid !== ''
1136
+ && !nidToNode.has(String(bodyNid))) {
1137
+ nidToNode.set(String(bodyNid), targetDoc.body);
1138
+ nodeToNid.set(targetDoc.body, String(bodyNid));
1139
+ }
1052
1140
  }
1053
1141
 
1054
1142
  function resolveIndexedNode(nid) {
@@ -1104,11 +1192,25 @@ export function createViewer(options) {
1104
1192
  }
1105
1193
  }
1106
1194
 
1195
+ // First DIRECT child of rootNode that is an installed style source with a
1196
+ // numeric data-ps-style-order greater than order, or null (append). Children
1197
+ // without a parsable order, such as string-level snapshot tags before the
1198
+ // load-time re-install, are skipped.
1199
+ function nextStyleSourceByOrder(rootNode, order) {
1200
+ for (var child = rootNode.firstElementChild; child; child = child.nextElementSibling) {
1201
+ if (!child.hasAttribute('data-ps-style-source-id')) continue;
1202
+ var raw = child.getAttribute('data-ps-style-order');
1203
+ if (raw === null || raw === '') continue;
1204
+ var childOrder = Number(raw);
1205
+ if (isFinite(childOrder) && childOrder > order) return child;
1206
+ }
1207
+ return null;
1208
+ }
1209
+
1107
1210
  function installOneStyleSource(targetDoc, rootNode, source) {
1108
1211
  var s = source || {};
1109
1212
  if (!targetDoc || !rootNode || !s.sourceId) return false;
1110
1213
  var existing = findStyleSourceElement(rootNode, s.sourceId);
1111
- if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
1112
1214
  var el = null;
1113
1215
  if (s.href && !hasDangerousStylesheetUrl(s.href)) {
1114
1216
  el = targetDoc.createElement('link');
@@ -1118,10 +1220,20 @@ export function createViewer(options) {
1118
1220
  el = targetDoc.createElement('style');
1119
1221
  setScopedStyleText(el, s.cssText || '');
1120
1222
  }
1223
+ var order = typeof s.order === 'number' ? s.order : 0;
1121
1224
  el.setAttribute('data-ps-style-source-id', String(s.sourceId));
1225
+ el.setAttribute('data-ps-style-order', String(order));
1122
1226
  if (s.media) el.setAttribute('media', String(s.media));
1123
1227
  if (s.disabled) el.setAttribute('data-ps-style-disabled', 'true');
1124
- rootNode.appendChild(el);
1228
+ // Cascade order (quick task 261202-jwf, D 1.5). Capture sends only the
1229
+ // sources that changed, so a replaced source keeps its position and a new
1230
+ // source goes before the first source in this root with a greater order.
1231
+ if (existing && existing.parentNode) {
1232
+ existing.parentNode.insertBefore(el, existing);
1233
+ existing.parentNode.removeChild(existing);
1234
+ } else {
1235
+ rootNode.insertBefore(el, nextStyleSourceByOrder(rootNode, order));
1236
+ }
1125
1237
  // A disabled source must not apply in the mirror -- the diagnostic
1126
1238
  // attribute above is not enough. Disable the sheet itself, set after
1127
1239
  // insertion so the StyleSheet object exists to be disabled.
@@ -1200,8 +1312,7 @@ export function createViewer(options) {
1200
1312
  });
1201
1313
  return false;
1202
1314
  }
1203
- var existing = findStyleSourceElement(resolved.root, sourceId);
1204
- if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
1315
+ // installOneStyleSource replaces an existing node in place (cascade order).
1205
1316
  return installOneStyleSource(resolved.doc, resolved.root, source || {});
1206
1317
  }
1207
1318
 
@@ -1252,6 +1363,7 @@ export function createViewer(options) {
1252
1363
 
1253
1364
  var tpl = targetDoc.createElement('template');
1254
1365
  tpl.innerHTML = p.html || '';
1366
+ restoreParserSafePlaceholders(tpl.content);
1255
1367
  sanitizeFragment(tpl.content, sanitizeCounters, logger);
1256
1368
  shadowRoot.appendChild(targetDoc.importNode(tpl.content, true));
1257
1369
  installStyleSources(targetDoc, p.styleSources || [], { kind: 'shadow', hostNid: p.hostNid });
@@ -1286,6 +1398,9 @@ export function createViewer(options) {
1286
1398
  var frameDoc = frameEl && frameEl.contentDocument;
1287
1399
  if (!frameDoc || !frameDoc.documentElement || !frameDoc.body) return false;
1288
1400
  removeIndexedSubtree(frameDoc.documentElement);
1401
+ // Parser-safe restore before the scrub and pairing. This also runs from
1402
+ // the frame load handler; repeating it is harmless.
1403
+ restoreParserSafePlaceholders(frameDoc.body, { filterUrl: restoreUrlFilter });
1289
1404
  sanitizeFragment(frameDoc.body, sanitizeCounters, logger);
1290
1405
  if (p.htmlNid) {
1291
1406
  nidToNode.set(String(p.htmlNid), frameDoc.documentElement);
@@ -1590,6 +1705,7 @@ export function createViewer(options) {
1590
1705
 
1591
1706
  var tpl = targetDoc.createElement('template');
1592
1707
  tpl.innerHTML = p.html || '';
1708
+ restoreParserSafePlaceholders(tpl.content);
1593
1709
  sanitizeFragment(tpl.content, sanitizeCounters, logger);
1594
1710
  // PRE-WRITE FETCH GATE (MSEC-01): template content is inert (no fetch), so
1595
1711
  // gating here -- before importNode -- is pre-write and safe.
@@ -2200,6 +2316,7 @@ export function createViewer(options) {
2200
2316
  lastTransportStatus = {};
2201
2317
  stateListeners.clear();
2202
2318
  healthListeners.clear();
2319
+ loadedListeners.clear();
2203
2320
  viewerState = 'waiting';
2204
2321
  }
2205
2322
 
@@ -0,0 +1,111 @@
1
+ // PhantomStream renderer: parser-safe placeholder restore (quick task
2
+ // 261202-jwf).
3
+ //
4
+ // A DOM built by scripts can hold nesting that HTML text cannot express (a
5
+ // button inside a button, a link inside a link, a div inside a paragraph, a
6
+ // row without a tbody). Capture renames such elements to
7
+ // <ps-node data-ps-tag="original-tag"> placeholders
8
+ // (neutralizeParserHostileNesting), so the viewer's parse keeps the tree and
9
+ // the positional nodeIds pairing intact. restoreParserSafePlaceholders turns
10
+ // them back into their original tags right after EVERY renderer parse, before
11
+ // sanitizeFragment and identity pairing, so restored elements always pass
12
+ // through the post-parse scrub and the asset gate.
13
+ //
14
+ // Only an allowlist is restored. script, iframe, object, embed, style, link,
15
+ // meta, base, html, head, body and frameset (and any other tag) stay inert
16
+ // generic <ps-node> elements. This module never assigns innerHTML and touches
17
+ // no DOM at import time.
18
+
19
+ import { PARSER_SAFE_TAG, PARSER_SAFE_TAG_ATTR } from '../protocol/messages.js';
20
+
21
+ // The tags capture's rename rules can produce that are safe to recreate.
22
+ var RESTORABLE = {
23
+ button: true, a: true, form: true, nobr: true, p: true,
24
+ h1: true, h2: true, h3: true, h4: true, h5: true, h6: true,
25
+ li: true, dd: true, dt: true, option: true, optgroup: true, select: true,
26
+ textarea: true, xmp: true, plaintext: true,
27
+ img: true, input: true, br: true, hr: true, wbr: true, area: true,
28
+ col: true, source: true, track: true,
29
+ table: true, tbody: true, thead: true, tfoot: true, tr: true, td: true,
30
+ th: true, caption: true, colgroup: true
31
+ };
32
+
33
+ // Restored tags whose URL attributes fetch as soon as they are set in a live
34
+ // document, and those attributes. data-ps-currentsrc is included because the
35
+ // asset gate promotes it to an <img> src (the ASST-03 currentSrc pin).
36
+ var URL_FILTERED_TAGS = { img: true, input: true, source: true, track: true };
37
+ var URL_FILTERED_ATTRS = { src: true, srcset: true, 'data-ps-currentsrc': true };
38
+
39
+ function filteredUrlValue(filterUrl, tag, attr, value) {
40
+ try {
41
+ var out = filterUrl(tag, attr, value);
42
+ return out === null || out === undefined ? null : String(out);
43
+ } catch (err) {
44
+ return null; // a throwing filter fails closed: the URL is dropped
45
+ }
46
+ }
47
+
48
+ function copyAttribute(el, attr, value) {
49
+ try {
50
+ el.setAttribute(attr.name, value);
51
+ } catch (err) {
52
+ try {
53
+ var clone = attr.cloneNode(true);
54
+ clone.value = value;
55
+ el.setAttributeNode(clone);
56
+ } catch (err2) { /* an attribute no element can carry is dropped */ }
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Restore capture's parser-safe placeholders under root, in document order.
62
+ *
63
+ * Each `ps-node[data-ps-tag]` whose trimmed, lowercased tag is on the
64
+ * restorable allowlist becomes a real element created by root's owner
65
+ * document: every attribute except data-ps-tag is copied, the children are
66
+ * moved, and the element takes the placeholder's position. Placeholders for
67
+ * any other tag, and `ps-node` elements without data-ps-tag, are left as they
68
+ * are.
69
+ *
70
+ * Call it right after a parse and BEFORE sanitizeFragment and identity
71
+ * pairing. In a live document (the snapshot and frame mirrors) pass
72
+ * `options.filterUrl`: restored img, input, source and track elements then
73
+ * get their src / srcset / data-ps-currentsrc only through it, so a blocked
74
+ * URL is never set (and never fetched). Template content is inert and is
75
+ * gated before importNode instead.
76
+ *
77
+ * @param {ParentNode} root A parsed body, document or template content.
78
+ * @param {{ filterUrl?: (tag: string, attr: string, value: string) => (string|null) }} [options]
79
+ * filterUrl returns the value to set, or null to drop the attribute.
80
+ * @returns {number} How many placeholders were restored.
81
+ */
82
+ export function restoreParserSafePlaceholders(root, options) {
83
+ if (!root || typeof root.querySelectorAll !== 'function') return 0;
84
+ var opts = options || {};
85
+ var filterUrl = typeof opts.filterUrl === 'function' ? opts.filterUrl : null;
86
+ var doc = root.ownerDocument || root;
87
+ if (!doc || typeof doc.createElement !== 'function') return 0;
88
+ var placeholders = root.querySelectorAll(PARSER_SAFE_TAG + '[' + PARSER_SAFE_TAG_ATTR + ']');
89
+ var restored = 0;
90
+ for (var i = 0; i < placeholders.length; i++) {
91
+ var placeholder = placeholders[i];
92
+ var tag = String(placeholder.getAttribute(PARSER_SAFE_TAG_ATTR) || '').trim().toLowerCase();
93
+ if (RESTORABLE[tag] !== true || !placeholder.parentNode) continue;
94
+ var el = doc.createElement(tag);
95
+ var attrs = placeholder.attributes;
96
+ for (var a = 0; a < attrs.length; a++) {
97
+ var name = String(attrs[a].name).toLowerCase();
98
+ if (name === PARSER_SAFE_TAG_ATTR) continue;
99
+ var value = attrs[a].value;
100
+ if (filterUrl && URL_FILTERED_TAGS[tag] === true && URL_FILTERED_ATTRS[name] === true) {
101
+ value = filteredUrlValue(filterUrl, tag, name, value);
102
+ if (value === null) continue;
103
+ }
104
+ copyAttribute(el, attrs[a], value);
105
+ }
106
+ while (placeholder.firstChild) el.appendChild(placeholder.firstChild);
107
+ placeholder.parentNode.replaceChild(el, placeholder);
108
+ restored++;
109
+ }
110
+ return restored;
111
+ }